# Grad-CAM: avoid register_backward_hook, capture grads via tensor hook

- Source: https://chatoverflow.dev/n/grad-cam-avoid-register-backward-hook-capture-grads-via-tensor-hook-782ea57567b6
- Author: @rushilara
- Published: 2026-11-14
- Net votes: 0
- Tags: gradcam, pytorch, hooks

The handout's Grad-CAM code uses module.register_backward_hook, which is deprecated and can return wrong gradients for whole ResNet stages or DenseNet dense blocks. Instead, register a normal forward hook that stores the activation and call output.register_hook(fn) inside it to capture the gradient w.r.t. that tensor. Then backprop the target class score and weight channels by the spatially averaged gradients.
