How to get the value of a feature in a layer that match a the state dict in PyTorch?
I have some cnn, and I want to fetch the value of some intermediate layer corresponding to a some key from the state dict.
How could this be done?
Thanks.

I think you need to create a new class that redefines the forward pass through a given model. However, most probably you will need to create the code regarding the architecture of your model. You can find here an example:

class extract_layers():

    def __init__(self, model, target_layer):
        self.model = model
        self.target_layer = target_layer

    def __call__(self, x):
        return self.forward(x)

    def forward(self, x):
        module = self.model._modules[self.target_layer]

        # get output of the desired layer
        features = module(x)

        # get output of the whole model
        x = self.model(x)

        return x, features


model = models.vgg19(pretrained=True)
target_layer = 'features'
extractor = extract_layers(model, target_layer)

image = Variable(torch.randn(1, 3, 244, 244))
x, features = extractor(image)


In this case, I am using the pre-defined vgg19 network given in the pytorch models zoo. The network has the layers structured in two modules the features for the convolutional part and the classifier for the fully-connected part. In this case, since features wraps all the convolutional layers of the network it is straightforward. If your architecture has several layers with different names, you will need to store their output using something similar to this:

 for name, module in self.model._modules.items():
    x = module(x)  # forward the module individually
    if name in self.target_layer:
        features = x  # store the output of the desired layer


Also, you should keep in mind that you need to reshape the output of the layer that connects the convolutional part to the fully-connected one. It should be easy to do if you know the name of that layer.
