{"record":{"id":"8d87284a09b44d82","repo":"Lightning-AI/pytorch-lightning","slug":"trying-to-inject-parameters-into-the-dataloader","errorCode":null,"errorMessage":"Trying to inject parameters into the `{dataloader_cls_name}` instance. This would fail as it doesn't expose all its attributes in the `__init__` signature. The missing arguments are {sorted_missing_kwargs}. HINT: If you wrote the `{dataloader_cls_name}` class, add the `__init__` arguments or allow passing `**kwargs`","messagePattern":"Trying to inject parameters into the `(.+?)` instance\\. This would fail as it doesn't expose all its attributes in the `__init__` signature\\. The missing arguments are (.+?)\\. HINT: If you wrote the `(.+?)` class, add the `__init__` arguments or allow passing `\\*\\*kwargs`","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"src/lightning/fabric/utilities/data.py","lineNumber":163,"sourceCode":"    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`\"\n            )\n\n    return dl_args, dl_kwargs\n\n\ndef _dataloader_init_kwargs_resolve_sampler(\n    dataloader: DataLoader,\n    sampler: Union[Sampler, Iterable],\n) -> dict[str, Any]:\n    \"\"\"This function is used to handle the sampler, batch_sampler arguments associated within a DataLoader for its re-\n    instantiation.\"\"\"\n    batch_sampler = getattr(dataloader, \"batch_sampler\")\n\n    if batch_sampler is not None and type(batch_sampler) is not BatchSampler:","sourceCodeStart":145,"sourceCodeEnd":181,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/fabric/utilities/data.py#L145-L181","documentation":"PyTorch Lightning's `_update_dataloader` tries to rebuild a DataLoader with modified settings (e.g., a new distributed sampler) by re-invoking its `__init__` with the attributes it introspected plus extra kwargs. If the dataloader's class has a closed `__init__` signature (no `**kwargs`) that doesn't accept one or more of the parameters Lightning needs to inject, this TypeError is raised listing the missing argument names.","triggerScenarios":"Using Fabric/Trainer with a custom DataLoader subclass whose `__init__` does not accept attributes like `sampler`, `batch_sampler`, `worker_init_fn`, etc. (or that sets them via properties/attributes not exposed as init params), then calling something that triggers dataloader re-creation such as `setup_dataloaders` with a distributed sampler, or trainer strategies that call `_update_dataloader`. Also happens when the dataloader was constructed with attributes that differ from its init signature.","commonSituations":"Custom DataLoader wrapper classes (e.g. a class that wraps tqdm progress or cycles iterators) that hard-code attributes in `__init__` without `**kwargs`; third-party dataloaders (e.g. from HuggingFace or torrential libraries) that don't forward extra kwargs; upgrading Lightning versions where new kwargs started being injected.","solutions":["Add the missing arguments listed in the error message to your custom DataLoader's `__init__` (e.g. `sampler=None`, `batch_sampler=None`).","Add `**kwargs` to your custom DataLoader's `__init__` and pass them through to `super().__init__(**kwargs)` so Lightning can inject anything it needs.","Return a plain `torch.utils.data.DataLoader` from your dataloader provider instead of a custom subclass.","Disable the injection path if applicable, e.g. `setup_dataloaders(..., use_distributed_sampler=False)` in Fabric."],"exampleFix":"// before\nclass MyLoader(DataLoader):\n    def __init__(self, dataset, batch_size=32):\n        super().__init__(dataset, batch_size=batch_size)\n\n// after\nclass MyLoader(DataLoader):\n    def __init__(self, dataset, batch_size=32, **kwargs):\n        super().__init__(dataset, batch_size=batch_size, **kwargs)","handlingStrategy":"validation","validationCode":"import inspect\n\ndef loader_accepts_kwargs(loader) -> bool:\n    sig = inspect.signature(type(loader).__init__)\n    for p in sig.parameters.values():\n        if p.kind is inspect.Parameter.VAR_KEYWORD:\n            return True\n    needed = {\"sampler\", \"batch_sampler\", \"worker_init_fn\", \"collate_fn\"}\n    have = set(sig.parameters)\n    return needed.issubset(have)","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Always give custom DataLoader subclasses `**kwargs` forwarded to super().__init__.","Expose every attribute you set in __init__ as an explicit parameter.","Test your dataloader under `fabric.setup_dataloaders` in a small DDP smoke run before full training."],"tags":["pytorch-lightning","dataloader","distributed","kwargs","init-signature"],"backgroundTag":"dataloader-init-signature-mismatch","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}