register_forward_hook

I have a question about “register_forward_hook”. Part of my code is as follow,

def hook(module, input, output):
pass

with torch.no_grad():
model.layer3[0].conv2.register_forward_hook(hook)
embed=model(torch.unsqueeze(image_, 0))
It does not give me the intermediate feature. I am new to pytorch and I am not sure what is the problem.

Your current hook function doesn’t do anything with the activation, so you could add e.g. a print statement:

def hook(module, input, output):
    print(output.shape)

model = nn.Conv2d(1, 1, 3)

with torch.no_grad():
    model.register_forward_hook(hook)
    embed = model(torch.randn(1, 1, 4, 4))