Skip to content

AttributeError with LightningModule forward without Trainer #9716

@lucmos

Description

@lucmos

🐛 Bug

LightningModule with Lightning 1.4 assumes to always have the self.trainer not None. No issues with 1.3

To Reproduce

import pytorch_lightning as pl


class MyModule(pl.LightningModule):
    def forward(self, *args, **kwargs):
        self.log_dict({"key": 0})


print(pl.__version__)

model = MyModule()
model()

Outputs:

1.4.0
Traceback (most recent call last):
  File "/home/luca/Projects/CookieTesting/my-new-project/src/my_new_project/commands/mymodule.py", line 11, in <module>
    model()
  File "/home/luca/miniconda3/envs/my-new-project/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "/home/luca/Projects/CookieTesting/my-new-project/src/my_new_project/commands/mymodule.py", line 6, in forward
    self.log_dict({"key": 0})
  File "/home/luca/miniconda3/envs/my-new-project/lib/python3.8/site-packages/pytorch_lightning/core/lightning.py", line 507, in log_dict
    self.log(
  File "/home/luca/miniconda3/envs/my-new-project/lib/python3.8/site-packages/pytorch_lightning/core/lightning.py", line 407, in log
    results = self.trainer._results
AttributeError: 'NoneType' object has no attribute '_results'

Expected behavior

If the Trainer and/or logger are not defined, the log and log_dict calls should be only ignored.

Environment

* CUDA:
        - GPU:
        - available:         False
        - version:           10.2
* Packages:
        - numpy:             1.21.2
        - pyTorch_debug:     False
        - pyTorch_version:   1.9.0
        - pytorch-lightning: 1.4.0
        - tqdm:              4.62.3
* System:
        - OS:                Linux
        - architecture:
                - 64bit
                - ELF
        - processor:         x86_64
        - python:            3.8.11
        - version:           #40~20.04.1-Ubuntu SMP Sat Sep 18 02:14:19 UTC 2021

Additional context

The problem is caused by this line:

https://github.com/PyTorchLightning/pytorch-lightning/blob/ab069876cb19bb9de0179f74c6f83764876a73ff/pytorch_lightning/core/lightning.py#L398

Related PR: #7891

@carmocca

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinghelp wantedOpen to be worked on

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions