Skip to content

Fix NoneType crash when model.eval() does not return self#578

Open
Pchambet wants to merge 1 commit intojacobgil:masterfrom
Pchambet:fix/base-cam-model-eval-none
Open

Fix NoneType crash when model.eval() does not return self#578
Pchambet wants to merge 1 commit intojacobgil:masterfrom
Pchambet:fix/base-cam-model-eval-none

Conversation

@Pchambet
Copy link

Problem

Passing a model whose .eval() does not return self causes an immediate crash in BaseCAM.__init__:

  File "pytorch_grad_cam/base_cam.py", line 28, in __init__
    self.device = next(self.model.parameters()).device
                       ^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'parameters'

Root cause

self.model = model.eval()  # None if eval() doesn't return self

Standard nn.Module.eval() returns self, but some third-party wrappers (quantization toolkits, custom tracing wrappers) override .eval() without propagating the return value — making model.eval() return None.

Fix

Separate assignment from the .eval() call:

self.model = model
self.model.eval()

This guarantees self.model always holds the model reference, regardless of what .eval() returns.

Precedent in this codebase

guided_backprop.py already uses the safe pattern:

# guided_backprop.py, line 49
self.model.eval()

This PR aligns base_cam.py with that existing convention.

Fixes #569

Separate model assignment from the eval() call so that self.model
is always the model instance, even when a custom Module subclass
overrides eval() without returning self.

Standard nn.Module.eval() returns self, but third-party wrappers
(e.g. some quantization or tracing toolkits) sometimes omit the
return, causing model.eval() to yield None.  The next line then
fails with:

    AttributeError: 'NoneType' object has no attribute 'parameters'

This follows the same defensive pattern already used in
guided_backprop.py (line 49).

Fixes jacobgil#569
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Potential NoneType model issue in base_cam.py

1 participant