Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Delete stub forward() method in LightningModule #19423

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

BlackHC
Copy link
Contributor

@BlackHC BlackHC commented Feb 6, 2024

The current stub breaks TorchScript/to_torchscript with:

otSupportedError: Compiled functions can't take variable number of arguments or use keyword-only arguments with defaults:
  File "/opt/conda/envs/image-gen/lib/python3.11/site-packages/pytorch_lightning/core/module.py", line 657
    def forward(self, *args: Any, **kwargs: Any) -> Any:
                                   ~~~~~~~ <--- HERE
        r"""Same as :meth:`torch.nn.Module.forward`.

This becomes an issue when you use a module as container for other modules with bespoke methods and do not rely on the default forward call.

What does this PR do?

Fixes #<issue_number>

Before submitting
  • Was this discussed/agreed via a GitHub issue? (not for typos and docs)
  • Did you read the contributor guideline, Pull Request section?
  • Did you make sure your PR does only one thing, instead of bundling different changes together?
  • Did you make sure to update the documentation with your changes? (if necessary)
  • Did you write any new necessary tests? (not for typos and docs)
  • Did you verify new and existing tests pass locally with your changes?
  • Did you list all the breaking changes introduced by this pull request?
  • Did you update the CHANGELOG? (not for typos, docs, test updates, or minor internal changes/refactors)

PR review

Anyone in the community is welcome to review the PR.
Before you start reviewing, make sure you have read the review guidelines. In short, see the following bullet-list:

Reviewer checklist
  • Is this pull request ready for review? (if not, please submit in draft mode)
  • Check that all items from Before submitting are resolved
  • Make sure the title is self-explanatory and the description concisely explains the PR
  • Add labels and milestones (and optionally projects) to the PR so it can be classified

📚 Documentation preview 📚: https://pytorch-lightning--19423.org.readthedocs.build/en/19423/

The current stub breaks TorchScript/`to_torchscript` with:

```
otSupportedError: Compiled functions can't take variable number of arguments or use keyword-only arguments with defaults:
  File "/opt/conda/envs/image-gen/lib/python3.11/site-packages/pytorch_lightning/core/module.py", line 657
    def forward(self, *args: Any, **kwargs: Any) -> Any:
                                   ~~~~~~~ <--- HERE
        r"""Same as :meth:`torch.nn.Module.forward`.
```

This becomes an issue when you use a module as container for other modules with bespoke methods and do not rely on the default forward call.
@github-actions github-actions bot added the pl Generic label for PyTorch Lightning package label Feb 6, 2024
@BlackHC BlackHC changed the title Delete stub forward() method in Module Delete stub forward() method in LightningModule Feb 6, 2024
@awaelchli
Copy link
Member

Hey @BlackHC
Thanks for opening the PR. I am not against the change but I'm not sure we can do it. The override of forward was intentional to signal to the LightningModule user that forward can be implemented and used in their training_step for example. Since torchscript is deprecated / replaced by compile by PyTorch, I don't see a strong need to remove the forward() now. Thoughts @carmocca?

@BlackHC
Copy link
Contributor Author

BlackHC commented Feb 11, 2024

Well, to be fair, the stub is not the problem by itself. The problem is that you are using the wrong signature for the stub. The correct default signature as defined is forward(*inputs). (See https://pytorch.org/docs/stable/generated/torch.nn.Module.html.)

I think **kwargs was added to be forward-compatible which is unnecessary. I'll change the PR to only fix the signature.

@carmocca
Copy link
Member

This stub is only defined so it appears in the docs.

Removing kwargs will mean this now raises

class MyModel(LightningModule):
    def forward(self, *inputs, **kwargs):
        return super().forward(*inputs, **kwargs)

m = MyModel()
y = m("foo", bar="bar")
TypeError: LightningModule.forward() got an unexpected keyword argument 'bar'

Which before would've raised

TypeError: _forward_unimplemented() got an unexpected keyword argument 'bar'

This isn't a big deal since this is meant to always be overridden and the error type is the same.

However, I am worried about your statement:

This becomes an issue when you use a module as container for other modules with bespoke methods and do not rely on the default forward call.

All computations are intended to run inside forward. Not adhering to this means your code might now work in distributed setups. Even if this change is merged, I strongly suggest that you override and use forward yourself in your LightningModules.

@carmocca carmocca added the community This PR is from the community label Feb 12, 2024
@BlackHC
Copy link
Contributor Author

BlackHC commented Feb 12, 2024

All computations are intended to run inside forward. Not adhering to this means your code might now work in distributed setups. Even if this change is merged, I strongly suggest that you override and use forward yourself in your LightningModules.

To be precise, actually we only use a module as a container module and then access its submodules. (The advantage over ModuleDict is that you get nicer code completion etc.)

However, looking at the tests, torchscript does not like *inputs either :| That makes me wonder how it runs on a regular Torch Module in the first place (but that works as the fix showed).

The alternative is, I guess, to copy the _forward_unimplemented approach. I'll try that next.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
community This PR is from the community pl Generic label for PyTorch Lightning package
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants