{"record":{"id":"6baccea3f1186d26","repo":"Lightning-AI/pytorch-lightning","slug":"cannot-set-the-dtype-explicitly-please-use-module","errorCode":null,"errorMessage":"Cannot set the dtype explicitly. Please use module.to(new_dtype).","messagePattern":"Cannot set the dtype explicitly\\. Please use module\\.to\\(new_dtype\\)\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"src/lightning/fabric/utilities/device_dtype_mixin.py","lineNumber":42,"sourceCode":"class _DeviceDtypeModuleMixin(Module):\n    __jit_unused_properties__: list[str] = [\"device\", \"dtype\"]\n\n    def __init__(self) -> None:\n        super().__init__()\n        self._dtype: Union[str, torch.dtype] = torch.get_default_dtype()\n        # Workarounds from the original pytorch issue:\n        # https://github.com/pytorch/pytorch/issues/115333#issuecomment-1848449687\n        # `get_default_device` only honors the `torch.device` context manager from 2.8 onwards\n        self._device = torch.get_default_device() if _TORCH_GREATER_EQUAL_2_8 else torch.empty(0).device\n\n    @property\n    def dtype(self) -> Union[str, torch.dtype]:\n        return self._dtype\n\n    @dtype.setter\n    def dtype(self, new_dtype: Union[str, torch.dtype]) -> None:\n        # necessary to avoid infinite recursion\n        raise RuntimeError(\"Cannot set the dtype explicitly. Please use module.to(new_dtype).\")\n\n    @property\n    def device(self) -> torch.device:\n        device = self._device\n\n        # make this more explicit to always include the index\n        if device.type == \"cuda\" and device.index is None:\n            return torch.device(f\"cuda:{torch.cuda.current_device()}\")\n\n        return device\n\n    @override\n    def to(self, *args: Any, **kwargs: Any) -> Self:\n        \"\"\"See :meth:`torch.nn.Module.to`.\"\"\"\n        # this converts `str` device to `torch.device`\n        device, dtype = torch._C._nn._parse_to(*args, **kwargs)[:2]\n        _update_properties(self, device=device, dtype=dtype)\n        return super().to(*args, **kwargs)","sourceCodeStart":24,"sourceCodeEnd":60,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/fabric/utilities/device_dtype_mixin.py#L24-L60","documentation":"The `_DeviceDtypeModuleMixin` (used by Lightning modules to track device/dtype) defines a `dtype` property with a setter that deliberately raises, because dtype must be changed through `module.to(new_dtype)` so the change propagates to parameters and buffers. Assigning `obj.dtype = torch.float16` triggers this RuntimeError (the setter exists mainly to block the infinite-recursion path that a bare property would cause).","triggerScenarios":"Executing `model.dtype = torch.float16` (or any dtype assignment) on a LightningModule or Fabric-managed module that mixes in `_DeviceDtypeModuleMixin`, instead of calling `.to()`.","commonSituations":"Porting plain PyTorch code that assigned `.dtype` on wrapper/inner modules; helper functions trying to record intended dtype on a module; stale tutorials using attribute assignment.","solutions":["Replace assignment with a `.to()` call: `module.to(torch.float16)`.","If storing a target dtype for later, keep it in a plain attribute with a different name (e.g. `self._target_dtype`).","Audit code for any `x.dtype = ...` on Lightning modules."],"exampleFix":"# before\nmodel.dtype = torch.float16\n\n# after\nmodel.to(torch.float16)","handlingStrategy":"validation","validationCode":"# there is nothing to pre-validate; simply never assign .dtype\nmodel.to(torch.float16)  # correct way","typeGuard":null,"tryCatchPattern":"try:\n    model.dtype = torch.float16\nexcept RuntimeError:\n    model.to(torch.float16)","preventionTips":["Never assign to module.dtype; always use .to(dtype).","Store intended dtypes in separate named attributes.","Grep codebases for `.dtype =` during PyTorch->Lightning migration."],"tags":["pytorch-lightning","dtype","module","property-setter"],"backgroundTag":"read-only-property-assignment","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}