We don’t have any support for hooks so anything you do is going to be pretty hacky; that said, you might be able to get something working by adding a custom operator to TorchScript that just calls a C++ autograd::Function that does nothing except let’s you grab the gradients in the backward pass.
There’s an example of a custom op used in this way in torchvision, see https://github.com/pytorch/vision/blob/master/torchvision/csrc/empty_tensor_op.h 8 and https://github.com/pytorch/vision/blob/43e94b39bcdda519c093ca11d99dfa2568aa7258/torchvision/csrc/vision.cpp#L51 13