{"record":{"id":"f3f074b6b138c916","repo":"Lightning-AI/pytorch-lightning","slug":"trying-to-inject-custom-sampler-into-the-datal","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/fabric/utilities/data.py","lineNumber":149,"sourceCode":"        dl_kwargs[\"batch_sampler\"] = None\n        dl_kwargs[\"sampler\"] = None\n    else:\n        dl_kwargs.update(_dataloader_init_kwargs_resolve_sampler(dataloader, sampler))\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 TypeError(\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":131,"sourceCodeEnd":167,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/fabric/utilities/data.py#L131-L167","documentation":"When Lightning re-creates a dataloader to inject a custom (distributed) sampler, it inspects the DataLoader.__init__ signature and reads each required argument from instance attributes of the same name. If some required init args (beyond dataset) are not stored as self.<arg> attributes — typical of custom __init__ overrides that rename or don't persist args — reconstruction is impossible and this MisconfigurationException is raised. Defining the attributes or constructing the loader inside a *_dataloader hook (where Lightning saves the original args) resolves it.","triggerScenarios":"A custom DataLoader subclass whose __init__ has required args (e.g. batch_sampler, collate_fn positional) that are not set as identically-named instance attributes, then passing an instance through a path that injects a sampler (fabric.setup_dataloaders / Trainer with distributed strategy).","commonSituations":"Custom loader subclasses that consume args without assigning self.<arg>; third-party loaders with non-standard attribute naming; upgrading Lightning/torch where sampler injection becomes required in distributed training.","solutions":["In your custom DataLoader.__init__, store every init argument as a same-named attribute: self.batch_size = batch_size, etc.","Or instantiate the loader inside a train_dataloader()/val_dataloader() hook so Lightning captures __pl_saved_args for you","Alternatively pre-configure a sampler manually and avoid Lightning's automatic sampler injection (e.g. pass a loader Lightning doesn't need to rewrap)"],"exampleFix":"# before\nclass MyLoader(DataLoader):\n    def __init__(self, dataset, batch_size):\n        super().__init__(dataset, batch_size=batch_size)\n        self.bs = batch_size  # renamed -> not discoverable\n\n# after\nclass MyLoader(DataLoader):\n    def __init__(self, dataset, batch_size):\n        super().__init__(dataset, batch_size=batch_size)\n        self.batch_size = batch_size  # attribute name matches init arg","handlingStrategy":"validation","validationCode":"import inspect\nfrom torch.utils.data import DataLoader\nmissing = [p for p in inspect.signature(MyLoader.__init__).parameters\n           if p not in ('self', 'dataset', 'args', 'kwargs') and not hasattr(loader, p)]\nassert not missing, f'store init args as attributes: {missing}'","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Always assign self.<arg> = <arg> for every custom DataLoader init argument","Or construct loaders inside *_dataloader hooks so Lightning captures the original args","Add a unit test that re-instantiates your loader from instance attributes"],"tags":["dataloader","distributed","sampler","misconfiguration","lightning-fabric"],"backgroundTag":"dataloader-reconstruction-failed","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}