Abstract
Deep neural network models (DNNs) are essential to modern AI and provide powerful models of information processing in biological neural networks. Researchers in both neuroscience and engineering are pursuing a better understanding of the internal representations and operations that undergird the successes and failures of DNNs. Neuroscientists additionally evaluate DNNs as models of brain computation by comparing their internal representations to those found in brains. It is therefore essential to have a method to easily and exhaustively extract and characterize the results of the internal operations of any DNN. Many models are implemented in PyTorch, the leading framework for building DNN models. Here we introduce TorchLens, a new open-source Python package for extracting and characterizing hidden-layer activations in PyTorch models. Uniquely among existing approaches to this problem, TorchLens has the following features: (1) it exhaustively extracts the results of all intermediate operations, not just those associated with PyTorch module objects, yielding a full record of every step in the model's computational graph, (2) it provides an intuitive visualization of the model's complete computational graph along with metadata about each computational step in a model's forward pass for further analysis, (3) it contains a built-in validation procedure to algorithmically verify the accuracy of all saved hidden-layer activations, and (4) the approach it uses can be automatically applied to any PyTorch model with no modifications, including models with conditional (if-then) logic in their forward pass, recurrent models, branching models where layer outputs are fed into multiple subsequent layers in parallel, and models with internally generated tensors (e.g., injections of noise). Furthermore, using TorchLens requires minimal additional code, making it easy to incorporate into existing pipelines for model development and analysis, and useful as a pedagogical aid when teaching deep learning concepts. We hope this contribution will help researchers in AI and neuroscience understand the internal representations of DNNs.
Introduction
Deep Neural Networks (DNNs) are often treated as "black boxes." While we see the input and the final output, understanding the internal representations—the "hidden activations"—is crucial for both neuroscientists (who compare DNNs to biological brains) and engineers (who need to debug or optimize architectures).
Existing methods for extracting these activations in PyTorch have significant gaps. Standard "forward hooks" only capture outputs from formal PyTorch nn.Module objects, leaving functional calls (like x + y or F.relu(x)) invisible. Furthermore, many tools struggle with dynamic control flow (e.g., if-else statements) or require significant manual effort that is prone to "silent errors," where a tensor is saved with the correct shape but incorrect values.
Methods: Dynamic Tracing and Validation
TorchLens introduces a dynamic tracing approach to solve these issues. Instead of relying on the user to define hooks, it uses Python decorators to transiently modify all built-in PyTorch functions that return a tensor.
Technical Innovations
- Tensor Barcoding: Every output tensor is tagged with a unique identifier (a "barcode"). When a subsequent function uses that tensor, TorchLens establishes a parent-child relationship, automatically mapping the model's connectivity.
- Heuristic Graph Inference: The package includes logic to identify "recurrent" layers and "if-then" branches by tracing childless Boolean tensors back to their ancestors.
- Automated Validation: To prevent silent errors, TorchLens features a built-in validation suite. It re-executes every individual operation using the saved inputs and compares the result to the saved output, ensuring 100% data integrity.
- Visualization Engine: Using the
graphvizlibrary, it generates intuitive diagrams where nodes are color-coded by function and shapes indicate whether an operation is a module or a raw function.
Evaluation and Key Results
TorchLens was rigorously evaluated for robustness across a massive library of over 800 pre-existing models, including TorchVision, TIMM (over 700 diverse computer vision models), TorchAudio, and large-scale NLP models like BERT and GPT-2.
Key results include:
- Exhaustive Coverage: TorchLens successfully extracted activations from every operation across vision, audio, and NLP domains.
- Ease of Use: The core functionality is triggered by a single function call:
get_model_activations(model, input). - Rich Metadata: Beyond activations, the tool returns a
ModelHistoryobject containing execution time per layer, memory usage, and parameter shapes, making it a powerful tool for performance profiling. - Dynamic Support: It successfully visualized and extracted data from models with complex branching and stochastic components (like noise injection) that typically break static graph exporters.
Discussion and Future Work
The authors argue that PyTorch "modules" are often arbitrary organizational choices. To truly understand a model, one must look at the elementary computational units (individual tensor operations), which TorchLens exposes. Furthermore, automated validation is presented as a necessity for reliable scientific analysis.
While powerful, TorchLens has limitations. It can be RAM-intensive because it saves every intermediate tensor for validation and extraction. It also has not been fully tested in multi-GPU or distributed computing environments. Future directions include the ability to "re-run" models from intermediate stages to allow for "lesioning" studies—zeroing out specific units to see how they causally contribute to the model's behavior.
Summary updated