Skip to content

RuntimeError: cannot register a hook on a tensor that doesn't require gradient #256

Answered by frgfm
kvnae94 asked this question in Q&A
Discussion options

You must be logged in to vote

Alright, now it's clearer thanks!
So to make this minimal:

import torch
from torchvision.models import resnet18
from torchcam.methods import ScoreCAM, GradCAM
model = resnet18(pretrained=True).eval()
for param in model.parameters():
    param.requires_grad = True
cam_score = ScoreCAM(model, 'layer4')
# cam_grad = GradCAM(model, 'layer4')
input_tensor = torch.rand((1, 3, 3, 255))
out = model(input_tensor)
cam_score(class_idx=100)

this snippet works, no need to instantiate GradCAM. Now the reason why this throws an error is:

  • ScoreCAM doesn't require gradient, so it applied a @torch.no_grad decorator. And for that method at some point, we forward the input in the model (did this to avoid ex…

Replies: 1 comment 9 replies

Comment options

You must be logged in to vote
9 replies
@karnikkanojia
Comment options

@frgfm
Comment options

frgfm Jul 2, 2024
Maintainer

@karnikkanojia
Comment options

@frgfm
Comment options

frgfm Jul 3, 2024
Maintainer

Answer selected by frgfm
@karnikkanojia
Comment options

@frgfm
Comment options

@karnikkanojia
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
3 participants