Feature extraction for model inspection
The torchvision.models.feature_extraction package contains
feature extraction utilities that let us tap into our models to access intermediate
transformations of our inputs. This could be useful for a variety of
applications in computer vision. Just a few examples are:
Visualizing feature maps.
Extracting features to compute image descriptors for tasks like facial recognition, copy-detection, or image retrieval.
Passing selected features to downstream sub-networks for end-to-end training with a specific task in mind. For example, passing a hierarchy of features to a Feature Pyramid Network with object detection heads.
Torchvision provides create_feature_extractor() for this purpose.
It works by following roughly these steps:
Symbolically tracing the model to get a graphical representation of how it transforms the input, step by step.
Setting the user-selected graph nodes as outputs.
Removing all redundant nodes (anything downstream of the output nodes).
Generating python code from the resulting graph and bundling that into a PyTorch module together with the graph itself.
The torch.fx documentation provides a more general and detailed explanation of the above procedure and the inner workings of the symbolic tracing.