torchview Documentation

repository·main·Indexed 22 days ago

https://github.com/mert-kurttutan/torchview

A visualization tool for PyTorch models (version 0.2.7) that generates visual graphs of model architectures. It provides details on module hierarchy, torch functions, tensor shapes, and input/output information via the draw_graph() function. Features include support for recursive modules through a rolling mechanism, expanding nested modules, and the ability to visualize extremely large models using device='meta' to avoid memory exhaustion. Requires PyTorch > 1.6 and graphviz for rendering.

Tokens
6.7K
Snippets
18
Records
28
Agent score
76%

What's inside torchview

  1. Understand the MkDocs project layout

    main

    The documentation structure follows a standard MkDocs layout:

    • mkdocs.yml: The main configuration file for the documentation site.
    • docs/: The directory containing all documentation content.
      • index.md: The homepage of the documentation site.
      • Other .md files, images, and assets used within the documentation.
  2. Understand torchview graph notation

    main

    The visual graphs produced by torchview consist of nodes and directed edges. Nodes are categorized into three types:

    1. Tensor Node (Bright Yellow): Labeled as {tensor-name}{depth}: {tensor-shape}. Names include input-tensor, hidden-tensor, or output-tensor.
    2. Function Node (Bright Blue): Labeled as {Function-name}{depth}: {input and output shape}.
    3. Module Node (Bright Green): Labeled as {Module-name}{depth}: {input and output shape}.

    When roll=True is used for recursive modules, numbers on edges indicate how many times that specific edge occurs during the forward pass (e.g., a '4' indicates the connection is used 4 times).

  3. Node identification logic for rolling graphs

    main

    When Roll=True is enabled, torchview uses specific rules to decide which nodes should be merged into a single visual entity. The logic varies by node type:

    TensorNode

    TensorNodes are never rolled. Every tensor is uniquely identified because, unlike modules, each tensor instance is typically used uniquely in a computation graph.

    FunctionNode

    Functions are identified by the ID of the torch function associated with the output of that FunctionNode.

    • Why not input ID? Using the input node ID would cause multiple distinct function calls (e.g., two different torch.relu calls on the same input) to merge into a single branch, which is incorrect.
    • Why output ID? Identifying by the output tensor ensures that each unique function call results in a distinct branch, even if they share the same input or the same underlying torch function.

    ModuleNode

    Module identification depends on whether the module is stateless or stateful:

    • Stateless Modules (modules with no torch.nn.parameter.Parameter): These are identified similarly to FunctionNodes. They are treated as functional units to prevent all instances of a stateless module (like ReLU) from collapsing into a single, visually confusing node.
    • Stateful Modules (modules with parameters): These are identified by the ID of the Python object itself. This ensures that a specific module instance (with its specific parameters) appears as a single shared node in the graph, which is the intended behavior for visualizing recursive parameter usage.
  4. How the rolling mechanism works in torchview

    main

    The rolling mechanism determines whether recursive computations are displayed as unique nodes or collapsed into shared nodes in the visual graph. This is controlled by the Roll parameter.

    • Roll=False: Every computation step is displayed uniquely on the graph, even if the same module or function is used recursively. Each node is assigned a unique node_id based on its Python object ID (e.g., id(tensor_node_1)).
    • Roll=True: Recursively used modules are identified as the same node on the visual graph to simplify the visualization. The identification logic depends on the node type (see Node Identification Logic).
  5. View model visualizations in the Model Gallery

    main

    The torchview Model Gallery provides a collection of SVG vector visualizations for various deep learning architectures across different domains (Computer Vision, NLP, Recommender Systems, etc.).

    Because the visualizations are in SVG vector format, you can:

    • Click on any image to expand it.
    • Zoom in using your browser to inspect fine-grained details of the model architecture (e.g., skip connections, attention heads, or bottleneck structures).
  6. Contribute new models to the Model Gallery

    main

    To add a new model architecture to the gallery, follow these requirements:

    1. Ensure the model architecture is representative of its class.
    2. Use torchview to generate the visualization in SVG format to maintain clarity and scalability.
    3. Submit a Pull Request (PR) to the repository.
  7. Install torchview

    main

    To use torchview, you must first install the graphviz system dependency and its Python interface. Then, you can install torchview using uv, pip, or conda.

    1. Install Graphviz System Dependency

    Ensure the dot layout command is available in your system path:

    • Debian/Ubuntu: apt-get install graphviz
    • Windows: choco install graphviz
    • macOS: brew install graphviz

    2. Install Python Packages

    Install the Python interface for graphviz and then torchview using your preferred manager.

    # Install graphviz python interface
    # uv
    uv add graphviz
    # pip
    pip install graphviz
    
    # Install torchview
    # uv
    uv add torchview
    # pip
    pip install torchview
    # conda
    conda install -c conda-forge torchview
    
    # Install latest version from GitHub
    # uv
    uv add git+https://github.com/mert-kurttutan/torchview.git
    # pip
    pip install git+https://github.com/mert-kurttutan/torchview.git
  8. Manage documentation with MkDocs commands

    main

    The TorchView documentation is built using MkDocs. You can use the following commands to manage the documentation site:

    • Create a new project: mkdocs new [dir-name]
    • Start a live-reloading server for local preview: mkdocs serve
    • Build the static documentation site: mkdocs build
    • View help information: mkdocs -h
    mkdocs serve
    mkdocs build
  9. PyTorch version compatibility requirements

    main

    To use torchview, you must use a PyTorch version greater than 1.6. This is because torch.Tensor did not have __torch_function__ as a class method in versions 1.6 and earlier, which is required for the package to function.

    Additionally, be aware of the following behavior for specific operators in older PyTorch versions:

    • PyTorch 1.7.1, 1.8, and 1.9: F.linear and F.embedding return NotImplemented when called via __torch_function__ on a subclass. torchview includes internal workarounds to handle these specific versions and ensure they return RecorderTensor instead of standard torch.Tensor.
  10. Advanced visualization patterns

    main

    torchview supports several advanced visualization modes:

    Rolling recursive modules

    Use roll=True to visually roll/unroll recursive modules (like RNNs) instead of showing every single recursive call.

    Showing hidden tensors and functions

    By default, torchview hides inner tensors and module functions to keep graphs clean. To see the full computation details, set hide_inner_tensors=False and hide_module_functions=False.

    Expanding nested modules

    Use expand_nested=True to show nested modules with dashed borders, which is useful for complex architectures like ResNet.

    # Example: Rolling recursive networks
    model_graph = draw_graph(SimpleRNN(), input_size=(2, 3), graph_name='RecursiveNet', roll=True)
    
    # Example: Showing all details
    model_graph = draw_graph(MLP(), input_size=(2, 128), graph_name='MLP', hide_inner_tensors=False, hide_module_functions=False)
    
    # Example: Expanding nested modules
    model_graph = draw_graph(resnet18(), input_size=(1,3,32,32), expand_nested=True)