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.
Introduction: The Challenge of Model Transparency
Deep Neural Networks (DNNs) are often criticized as "black boxes." While the input and final output are visible, the intermediate transformations—the "hidden activations"—are where the critical computations occur. For engineers, understanding these internal states is vital for debugging and optimization. For neuroscientists, these activations serve as proxies for biological brain activity, allowing for comparisons between AI models and human perception.
However, existing tools for extracting these activations often suffer from incompleteness, rigidity, or high manual labor. Many tools only capture outputs from PyTorch Modules, ignoring basic functional operations like torch.add or torch.relu if they aren't explicitly wrapped in a module. Furthermore, dynamic control flow (e.g., if-then statements) and recurrent loops often break standard tracing tools. TorchLens was developed to address these gaps by providing an exhaustive, automated, and flexible solution.
Methods: Automated Dynamic Tracing
TorchLens automates the extraction process using a technique called dynamic tracing. Instead of requiring manual code modifications or "hooks," TorchLens uses Python decorators to temporarily wrap all built-in PyTorch functions that return tensors. During a model's forward pass, these wrappers log every operation, its metadata (shapes, memory, execution time), and the parent-child relationships between tensors.
Key technical innovations include a universal layer nomenclature that assigns standardized names to every operation (e.g., relu_3_6) and a built-in algorithmic validation procedure. This procedure re-executes each operation using saved inputs to ensure that the stored activations match the ground truth, preventing "silent errors" in data extraction.
Key Features and Architectural Support
A primary strength of TorchLens is its ability to handle complex and diverse model architectures without user intervention. By targeting PyTorch functions rather than just modules, it captures the "connective tissue" of the model—the functional operations that other tools often miss.
TorchLens provides specialized support for:
- Conditional Logic: It identifies branching by tracing "childless" Boolean tensors back to the point of divergence, labeling branches clearly in the visualization.
- Recurrent Networks: It can display graphs in both "rolled" (compact) and "unrolled" (sequential) views, which is essential for understanding feedback loops.
- Nested Modules: It maintains the hierarchical structure of the model while still exposing every internal operation.
Results: Integration and Performance
The tool achieves "zero-effort" integration; a single call to tl.log_forward_pass (or tl.show_model_graph for visualization) generates a complete record of the model's execution. The resulting hierarchical, color-coded computational graphs provide a "picture of the code," detailing memory usage and parameter counts. This makes TorchLens not only a powerful research tool but also a valuable pedagogical aid for teaching deep learning concepts.
The robustness of TorchLens has been validated across a wide range of libraries, including TorchVision, TorchAudio, TIMM (over 700 vision models), and large-scale NLP models like BERT and GPT-2.
Conclusion and Future Directions
While TorchLens provides unprecedented transparency, it does involve memory overhead due to its exhaustive nature. Saving activations for every intermediate operation can be RAM-intensive for very large models or batches, though users can specify subsets of layers to mitigate this. Future work will focus on supporting parallel computing environments (multi-GPU) and enabling "live" interventions, such as mid-run layer lesioning, to observe causal effects on model behavior.
Summary updated