{"record":{"id":"11c5624afa5585ab","repo":"Lightning-AI/pytorch-lightning","slug":"trying-to-inject-a-modified-sampler-into-the-batch-11c562","errorCode":null,"errorMessage":"Trying to inject a modified sampler into the batch sampler; however, it seems the class `{batch_sampler_cls.__qualname__}` does not have an argument called `sampler.` To mitigate this, expose an argument `sampler` in the `__init__` method of your custom class.","messagePattern":"Trying to inject a modified sampler into the batch sampler; however, it seems the class `(.+?)` does not have an argument called `sampler\\.` To mitigate this, expose an argument `sampler` in the `__init__` method of your custom class\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"src/lightning/pytorch/utilities/data.py","lineNumber":273,"sourceCode":"            arg_names = batch_sampler.__pl_saved_arg_names\n\n            if is_predicting:\n                success, args, kwargs = _replace_value_in_saved_args(\n                    \"drop_last\", False, args, kwargs, default_kwargs, arg_names\n                )\n                if not success:\n                    rank_zero_warn(\n                        f\"Trying to inject `drop_last=False` into batch sampler since you are predicting, however \"\n                        f\"it seems the class `{batch_sampler_cls.__qualname__}` does not support it. \"\n                        \"Your predictions might be incomplete. To mitigate this, expose `drop_last` in \"\n                        \"the `__init__` method of your custom class.\"\n                    )\n\n            success, args, kwargs = _replace_value_in_saved_args(\n                \"sampler\", sampler, args, kwargs, default_kwargs, arg_names\n            )\n            if not success:\n                raise TypeError(\n                    \"Trying to inject a modified sampler into the batch sampler; however, it seems the class \"\n                    f\"`{batch_sampler_cls.__qualname__}` does not have an argument called `sampler.` To mitigate \"\n                    \"this, expose an argument `sampler` in the `__init__` method of your custom class.\"\n                )\n\n            batch_sampler = _reinstantiate_wrapped_cls(batch_sampler, *args, **kwargs)\n        elif hasattr(batch_sampler, \"batch_size\") and hasattr(batch_sampler, \"drop_last\"):\n            # This is a sampler for which we could not capture the init args, but it kinda looks like a batch sampler\n            # even if it does not inherit from PyTorch's interface.\n            try:\n                batch_sampler = batch_sampler_cls(\n                    sampler,\n                    batch_size=batch_sampler.batch_size,\n                    drop_last=(False if is_predicting else batch_sampler.drop_last),\n                )\n            except TypeError as ex:\n                import re\n","sourceCodeStart":255,"sourceCodeEnd":291,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/pytorch/utilities/data.py#L255-L291","documentation":"Raised as a TypeError when Lightning tries to replace the sampler inside a custom batch sampler (the batch_sampler argument of a DataLoader) but the batch sampler class's __init__ has no 'sampler' parameter to substitute. Lightning reinstantiates the batch sampler class with a modified sampler; without a 'sampler' init arg there is no way to inject the distributed one.","triggerScenarios":"Passing a DataLoader with a custom batch_sampler whose class's __init__ lacks a sampler argument, in a distributed run where Lightning replaces samplers (e.g. FSDP/DDP with use_distributed_sampler default).","commonSituations":"Custom batch samplers with signatures like __init__(self, indices, batch_size); porting single-device code to multi-device training; using weighted or curriculum batch samplers.","solutions":["Expose a sampler argument in your batch sampler's __init__ and use it to build batches","Or set Trainer(use_distributed_sampler=False) and handle distributed sampling inside your batch sampler yourself"],"exampleFix":"# before\nclass MyBatchSampler:\n    def __init__(self, dataset, batch_size): ...\n\n# after\nclass MyBatchSampler:\n    def __init__(self, sampler, batch_size): ...  # 'sampler' arg injectable","handlingStrategy":"validation","validationCode":"import inspect\nbs = loader.batch_sampler\nassert 'sampler' in inspect.signature(type(bs).__init__).parameters, 'batch sampler needs a sampler __init__ arg'","typeGuard":"import inspect\nfrom typing import Any\n\ndef batch_sampler_has_sampler_arg(bs: Any) -> bool:\n    return 'sampler' in inspect.signature(type(bs).__init__).parameters","tryCatchPattern":null,"preventionTips":["Design custom batch samplers with a sampler constructor argument","Follow torch.utils.data.sampler.BatchSampler's (sampler, batch_size, drop_last) API","Use Trainer(use_distributed_sampler=False) when you manage sharding yourself"],"tags":["pytorch-lightning","batch-sampler","sampler","distributed-training"],"backgroundTag":"batch-sampler-sampler-argument-missing","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}