{"record":{"id":"2876d4c47b28c3a5","repo":"Lightning-AI/pytorch-lightning","slug":"you-cannot-mark-the-forward-method-itself-as-a-for","errorCode":null,"errorMessage":"You cannot mark the forward method itself as a forward method.","messagePattern":"You cannot mark the forward method itself as a forward method\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/lightning/fabric/wrappers.py","lineNumber":171,"sourceCode":"        return self._original_module.state_dict(\n            destination=destination,  # type: ignore[type-var]\n            prefix=prefix,\n            keep_vars=keep_vars,\n        )\n\n    @override\n    def load_state_dict(  # type: ignore[override]\n        self, state_dict: Mapping[str, Any], strict: bool = True, **kwargs: Any\n    ) -> _IncompatibleKeys:\n        return self._original_module.load_state_dict(state_dict=state_dict, strict=strict, **kwargs)\n\n    def mark_forward_method(self, method: Union[MethodType, str]) -> None:\n        \"\"\"Mark a method as a 'forward' method to prevent it bypassing the strategy wrapper (e.g., DDP).\"\"\"\n        if not isinstance(method, (MethodType, str)):\n            raise TypeError(f\"Expected a method or a string, but got: {type(method).__name__}\")\n        name = method if isinstance(method, str) else method.__name__\n        if name == \"forward\":\n            raise ValueError(\"You cannot mark the forward method itself as a forward method.\")\n        if not isinstance(getattr(self._original_module, name, None), MethodType):\n            raise AttributeError(\n                f\"You marked '{name}' as a forward method, but `{type(self._original_module).__name__}.{name}` does not\"\n                f\" exist or is not a method.\"\n            )\n        self._forward_methods.add(name)\n\n    def _redirection_through_forward(self, method_name: str) -> Callable:\n        assert method_name != \"forward\"\n        original_forward = self._original_module.forward\n\n        def wrapped_forward(*args: Any, **kwargs: Any) -> Any:\n            # Unpatch ourselves immediately before calling the method `method_name`\n            # because itself may want to call the real `forward`\n            self._original_module.forward = original_forward\n            # Call the actual method e.g. `.training_step(...)`\n            method = getattr(self._original_module, method_name)\n            return method(*args, **kwargs)","sourceCodeStart":153,"sourceCodeEnd":189,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/fabric/wrappers.py#L153-L189","documentation":"mark_forward_method() exists to redirect non-standard methods (like generate) through the strategy's forward path. Marking 'forward' itself is rejected with ValueError because forward is already routed through the wrapper and self-redirection would recurse infinitely.","triggerScenarios":"Calling fabric_module.mark_forward_method('forward') or fabric_module.mark_forward_method(fabric_module.forward) after fabric.setup().","commonSituations":"Generic code that loops over dir(model) or a list of method names including 'forward' and marks them all; copy-pasted snippet adapted from a generate() example without changing the name; misunderstanding that forward needs no marking.","solutions":["Remove 'forward' from the list of methods you mark; it is handled automatically","Only mark auxiliary callable methods such as 'generate', 'encode', 'decode' that you invoke directly","If you meant a differently named method, fix the string typo"],"exampleFix":"# before\nfor name in ['forward', 'generate']:\n    fabric_module.mark_forward_method(name)\n\n# after\nfor name in ['generate']:\n    fabric_module.mark_forward_method(name)","handlingStrategy":"validation","validationCode":"assert name != 'forward', \"forward must not be marked; it is already routed through the strategy\"","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Keep an explicit allowlist of methods to mark and exclude 'forward'","Remember forward needs no marking by design"],"tags":["pytorch-lightning","fabric","invalid-argument"],"backgroundTag":"invalid-argument-validation","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}