Lightning-AI/pytorch-lightning · error · TypeError

Trying to inject parameters into the

Error message

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`

What it means

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.

Solutions

  1. Add the missing arguments listed in the error message to your custom DataLoader's `__init__` (e.g. `sampler=None`, `batch_sampler=None`).
  2. Add `**kwargs` to your custom DataLoader's `__init__` and pass them through to `super().__init__(**kwargs)` so Lightning can inject anything it needs.
  3. Return a plain `torch.utils.data.DataLoader` from your dataloader provider instead of a custom subclass.
  4. Disable the injection path if applicable, e.g. `setup_dataloaders(..., use_distributed_sampler=False)` in Fabric.

Example fix

// before
class MyLoader(DataLoader):
    def __init__(self, dataset, batch_size=32):
        super().__init__(dataset, batch_size=batch_size)

// after
class MyLoader(DataLoader):
    def __init__(self, dataset, batch_size=32, **kwargs):
        super().__init__(dataset, batch_size=batch_size, **kwargs)
Defensive patterns

Strategy: validation

Validate before calling

import inspect

def loader_accepts_kwargs(loader) -> bool:
    sig = inspect.signature(type(loader).__init__)
    for p in sig.parameters.values():
        if p.kind is inspect.Parameter.VAR_KEYWORD:
            return True
    needed = {"sampler", "batch_sampler", "worker_init_fn", "collate_fn"}
    have = set(sig.parameters)
    return needed.issubset(have)

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of Lightning-AI/pytorch-lightning@9fed5c27d2 (2026-08-28). Data as JSON: /api/errors/8d87284a09b44d82. Report an issue: GitHub.

Appendix: source

Thrown at src/lightning/fabric/utilities/data.py:163

    if required_args:
        sorted_required_args = sorted(required_args)
        dataloader_cls_name = dataloader.__class__.__name__
        missing_args_message = ", ".join(f"`self.{arg_name}`" for arg_name in sorted_required_args)
        raise MisconfigurationException(
            f"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. "
            f"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."
            f" Otherwise, define {missing_args_message} inside your `__init__`."
        )

    if not has_variadic_kwargs:
        # the dataloader signature does not allow keyword arguments that need to be passed
        missing_kwargs = (set(dl_kwargs) | set(arg_names)) - params.keys()
        if missing_kwargs:
            sorted_missing_kwargs = sorted(missing_kwargs)
            dataloader_cls_name = dataloader.__class__.__name__
            raise TypeError(
                f"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. "
                f"The missing arguments are {sorted_missing_kwargs}. HINT: If you wrote the `{dataloader_cls_name}` "
                "class, add the `__init__` arguments or allow passing `**kwargs`"
            )

    return dl_args, dl_kwargs


def _dataloader_init_kwargs_resolve_sampler(
    dataloader: DataLoader,
    sampler: Union[Sampler, Iterable],
) -> dict[str, Any]:
    """This function is used to handle the sampler, batch_sampler arguments associated within a DataLoader for its re-
    instantiation."""
    batch_sampler = getattr(dataloader, "batch_sampler")

    if batch_sampler is not None and type(batch_sampler) is not BatchSampler:

View on GitHub (pinned to 9fed5c27d2)