{"record":{"id":"653eb7dc61ad2c26","repo":"Lightning-AI/pytorch-lightning","slug":"trying-to-inject-custom-sampler-into-the-datal-653eb7","errorCode":null,"errorMessage":"Trying to inject custom `Sampler` into the `{dataloader_cls_name}` instance. This would fail as some of the `__init__` arguments are not available as instance attributes. The missing attributes are {sorted_required_args}. If you instantiate your `{dataloader_cls_name}` inside a `*_dataloader` hook of your module, we will do this for you. Otherwise, define {missing_args_message} inside your `__init__`.","messagePattern":"Trying to inject custom `Sampler` into the `(.+?)` instance\\. This would fail as some of the `__init__` arguments are not available as instance attributes\\. The missing attributes are (.+?)\\. If you instantiate your `(.+?)` inside a `\\*_dataloader` hook of your module, we will do this for you\\. Otherwise, define (.+?) inside your `__init__`\\.","errorType":"exception","errorClass":"MisconfigurationException","httpStatus":null,"severity":"error","filePath":"src/lightning/pytorch/utilities/data.py","lineNumber":209,"sourceCode":"        dl_kwargs[\"batch_sampler\"] = None\n        dl_kwargs[\"sampler\"] = None\n    else:\n        dl_kwargs.update(_dataloader_init_kwargs_resolve_sampler(dataloader, sampler, mode))\n\n    required_args = {\n        p.name\n        for p in params.values()\n        if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)\n        and p.default is p.empty\n        and p.name not in dl_kwargs\n        and p.name not in arg_names\n    }\n    # the dataloader has required args which we could not extract from the existing attributes\n    if required_args:\n        sorted_required_args = sorted(required_args)\n        dataloader_cls_name = dataloader.__class__.__name__\n        missing_args_message = \", \".join(f\"`self.{arg_name}`\" for arg_name in sorted_required_args)\n        raise MisconfigurationException(\n            f\"Trying to inject custom `Sampler` into the `{dataloader_cls_name}` instance. \"\n            \"This would fail as some of the `__init__` arguments are not available as instance attributes. \"\n            f\"The missing attributes are {sorted_required_args}. If you instantiate your `{dataloader_cls_name}` \"\n            \"inside a `*_dataloader` hook of your module, we will do this for you.\"\n            f\" Otherwise, define {missing_args_message} inside your `__init__`.\"\n        )\n\n    if not has_variadic_kwargs:\n        # the dataloader signature does not allow keyword arguments that need to be passed\n        missing_kwargs = (set(dl_kwargs) | set(arg_names)) - params.keys()\n        if missing_kwargs:\n            sorted_missing_kwargs = sorted(missing_kwargs)\n            dataloader_cls_name = dataloader.__class__.__name__\n            raise MisconfigurationException(\n                f\"Trying to inject parameters into the `{dataloader_cls_name}` instance. \"\n                \"This would fail as it doesn't expose all its attributes in the `__init__` signature. \"\n                f\"The missing arguments are {sorted_missing_kwargs}. HINT: If you wrote the `{dataloader_cls_name}` \"\n                \"class, add the `__init__` arguments or allow passing `**kwargs`\"","sourceCodeStart":191,"sourceCodeEnd":227,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/pytorch/utilities/data.py#L191-L227","documentation":"Raised as a MisconfigurationException when Lightning tries to inject a custom (distributed) Sampler into a DataLoader subclass but cannot reconstruct it: the subclass's __init__ has required arguments that Lightning cannot recover from the instance's attributes. Lightning reconstructs dataloaders by reading init args back from instance attributes (e.g. self.batch_size), so required init params without matching attributes are unrecoverable.","triggerScenarios":"Returning a DataLoader subclass with required __init__ parameters (other than the standard set) that are not stored as same-named instance attributes, from a *_dataloader hook during distributed training; e.g. def __init__(self, my_flag): ... without self.my_flag = my_flag.","commonSituations":"Custom DataLoader subclasses that rename or compute init args instead of storing them verbatim; changing a subclass's signature after Lightning worked before; distributed runs only (single device may not re-instantiate).","solutions":["Store every required __init__ argument as an identically named instance attribute: def __init__(self, my_flag): super().__init__(...); self.my_flag = my_flag","Give the required parameters defaults so they are not required","Instantiate the dataloader inside the *_dataloader hook so Lightning saves the original args"],"exampleFix":"# before\nclass MyDL(DataLoader):\n    def __init__(self, dataset, mode):\n        super().__init__(dataset, batch_size=2 if mode == 'train' else 1)\n\n# after\nclass MyDL(DataLoader):\n    def __init__(self, dataset, mode):\n        self.mode = mode  # attribute matching the init arg name\n        super().__init__(dataset, batch_size=2 if mode == 'train' else 1)","handlingStrategy":"validation","validationCode":"import inspect\nfrom torch.utils.data import DataLoader\n\ndef validate_dataloader_attrs(dl: DataLoader) -> None:\n    sig = inspect.signature(type(dl).__init__)\n    params = inspect.signature(DataLoader.__init__).parameters\n    for name in sig.parameters:\n        if name in ('self',) or name in params:\n            continue\n        assert hasattr(dl, name), f'{type(dl).__name__} must store self.{name}'","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Store every __init__ arg as self.<argname> in custom DataLoader subclasses","Give custom init parameters default values where possible","Instantiate custom dataloaders inside the *_dataloader hooks so Lightning records the original args"],"tags":["pytorch-lightning","dataloader","sampler","introspection"],"backgroundTag":"dataloader-introspection-missing-attribute","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}