Skip to main content

A lightweight debugging tool for tracking tensor shape transformations in PyTorch

Project description

DimViz ๐Ÿ”

PyPI version License: MIT Python 3.8+

A lightweight debugging tool for tracking tensor shape transformations in PyTorch models.

Stop guessing tensor shapesโ€”see them flow through your model in real-time! DimViz helps you debug shape mismatches, understand model architecture, and optimize tensor operations.

โœจ Features

  • ๐ŸŽฏ Zero Code Changes - Context manager and decorator patterns
  • ๐Ÿ“Š Rich Visualization - Beautiful terminal tables (with optional Rich library)
  • ๐Ÿ” Smart Filtering - Track only what matters
  • ๐Ÿ’พ Multiple Export Formats - JSON, CSV, TXT
  • ๐Ÿ“ˆ Memory Tracking - See memory allocation per operation
  • ๐ŸŽจ Friendly Names - Human-readable operation names
  • โšก Performance Aware - Minimal overhead with smart filtering

๐Ÿš€ Installation

pip install dimviz

For enhanced visualization with colors and styling:

pip install dimviz[rich]

๐Ÿ“– Quick Start

Basic Usage

import torch
import torch.nn as nn
from dimviz import DimViz

# Your model
model = nn.Sequential(
    nn.Linear(784, 256),
    nn.ReLU(),
    nn.Linear(256, 10)
)

# Track shape transformations
x = torch.randn(32, 784)

with DimViz():
    output = model(x)

Output:

[DimViz] ๐ŸŸข Tracking Started...
[DimViz] ๐Ÿ”ด Tracking Finished. (Elapsed: 0.02s)

โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ Step โ”‚ Operation  โ”‚ Input Shape โ”‚ Output Shape โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚    1 โ”‚ linear     โ”‚ (32, 784)   โ”‚ (32, 256)    โ”‚
โ”‚    2 โ”‚ relu       โ”‚ (32, 256)   โ”‚ (32, 256)    โ”‚
โ”‚    3 โ”‚ linear     โ”‚ (32, 256)   โ”‚ (32, 10)     โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

[DimViz] ๐Ÿ“Š Summary:
  โ€ข Total Operations: 3
  โ€ข Unique Operations: 2
  โ€ข Logged Operations: 3

Decorator Usage

from dimviz import visualize

@visualize()
def train_step(model, batch):
    output = model(batch)
    loss = criterion(output, target)
    loss.backward()
    return loss

loss = train_step(model, batch)

๐ŸŽ›๏ธ Advanced Features

Track Only Shape Changes

When you only care about shape transformations:

with DimViz(verbose=False):
    output = model(x)

This filters out operations that don't change tensor shapes (like activation functions on the same tensor).

Memory Tracking

Monitor memory allocation per operation:

with DimViz(track_memory=True):
    output = model(x)

Output includes memory columns:

โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ Step โ”‚ Operation โ”‚ Input Shape โ”‚ Output Shape โ”‚ Mem In  โ”‚ Mem Out  โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚    1 โ”‚ linear    โ”‚ (32, 784)   โ”‚ (32, 256)    โ”‚ 0.10MB  โ”‚ 0.03MB   โ”‚
โ”‚    2 โ”‚ relu      โ”‚ (32, 256)   โ”‚ (32, 256)    โ”‚ 0.03MB  โ”‚ 0.03MB   โ”‚
โ”‚    3 โ”‚ linear    โ”‚ (32, 256)   โ”‚ (32, 10)     โ”‚ 0.03MB  โ”‚ 0.00MB   โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

[DimViz] ๐Ÿ“Š Summary:
  โ€ข Peak Memory: 0.10MB
  โ€ข Total Memory Delta: -0.07MB

Filter Specific Operations

Focus on particular operation types:

with DimViz(filter_ops=['conv2d', 'matmul', 'linear']):
    output = model(x)

Export Logs

Save your debugging session for later analysis:

from dimviz import export_log

with DimViz() as viz:
    output = model(x)

# Export to various formats
export_log(viz.get_log(), 'debug_log.json')
export_log(viz.get_log(), 'debug_log.csv')
export_log(viz.get_log(), 'debug_log.txt')

Compare Model Runs

Compare shape flows between different model versions:

from dimviz.exporter import compare_logs

# First model
with DimViz() as viz1:
    output1 = model_v1(x)

# Second model
with DimViz() as viz2:
    output2 = model_v2(x)

# Compare
diff = compare_logs(viz1.get_log(), viz2.get_log(), "v1", "v2")
print(diff)

Use Cases

1. Debugging Shape Mismatches

# Find where dimensions go wrong
with DimViz():
    x = torch.randn(32, 3, 224, 224)
    x = conv1(x)  # (32, 64, 112, 112)
    x = conv2(x)  # (32, 128, 56, 56)
    x = x.view(32, -1)  # See the flattened size!
    x = fc(x)  # Does it match?

2. Understanding Complex Architectures

# Trace transformer attention mechanism
with DimViz(verbose=False):  # Only shape changes
    attention_output = transformer_layer(x)

3. Optimizing Memory Usage

# Find memory-hungry operations
with DimViz(track_memory=True, filter_ops=['conv2d', 'linear']):
    output = large_model(x)

4. Teaching & Documentation

# Generate shape flow documentation
@visualize(verbose=True)
def forward_pass(x):
    """Documented forward pass with shape tracking."""
    return model(x)

๐Ÿ”ง Configuration Options

DimViz()

Parameter Type Default Description
verbose bool True Log all operations (True) or only shape changes (False)
track_memory bool False Track memory allocation per operation
filter_ops List[str] None Only track specific operations
max_entries int None Limit number of logged operations
show_summary bool True Display summary statistics

@visualize()

Same parameters as DimViz(), used as a decorator:

@visualize(verbose=False, track_memory=True)
def my_function(x):
    return model(x)

๐Ÿ“Š Supported Operations

DimViz translates PyTorch operations to friendly names:

  • aten::mm โ†’ matmul
  • aten::addmm โ†’ linear_proj
  • aten::conv2d โ†’ conv2d
  • aten::bmm โ†’ batch_matmul
  • aten::cat โ†’ concat
  • aten::sigmoid โ†’ sigmoid
  • ...and many more!

Operations are automatically detected and logged with human-readable names.

๐ŸŽจ Output Formats

Terminal Output

With Rich (if installed):

  • Colored, styled tables
  • Better readability
  • Automatic terminal adaptation

Without Rich:

  • ASCII tables via tabulate
  • Still clear and readable
  • Works everywhere

Export Formats

JSON - Structured data with metadata:

{
  "metadata": {
    "timestamp": "2024-01-29T10:30:00",
    "total_operations": 10
  },
  "log": [
    {
      "step": 1,
      "operation": "linear",
      "input_shape": "(32, 784)",
      "output_shape": "(32, 256)"
    }
  ]
}

CSV - Spreadsheet-friendly:

step,operation,input_shape,output_shape
1,linear,"(32, 784)","(32, 256)"
2,relu,"(32, 256)","(32, 256)"

TXT - Human-readable logs:

DimViz Log Export
================================================================================
Step | Operation | Input Shape | Output Shape
1    | linear    | (32, 784)   | (32, 256)
2    | relu      | (32, 256)   | (32, 256)

โšก Performance

DimViz uses PyTorch's TorchDispatchMode for minimal overhead:

  • Verbose mode: ~5-10% slowdown (logs everything)
  • Non-verbose mode: ~2-5% slowdown (logs only shape changes)
  • With filtering: ~1-3% slowdown (logs specific ops only)

For production code, use verbose=False or filter_ops to minimize impact.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Development Setup

git clone https://github.com/yourhimalaya-kaushik/dimviz.git
cd dimviz
pip install -e ".[dev]"
pytest tests/

Running Tests

pytest tests/ -v
pytest tests/ --cov=dimviz --cov-report=html

๐Ÿ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Built on PyTorch's TorchDispatchMode API
  • Visualization powered by Rich (optional)
  • Table formatting by tabulate

๐Ÿ“ง Contact


Made with โค๏ธ for the PyTorch community

If you find DimViz helpful, please consider giving it a โญ on GitHub!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dimviz-0.1.0.tar.gz (38.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dimviz-0.1.0-py3-none-any.whl (12.2 kB view details)

Uploaded Python 3

File details

Details for the file dimviz-0.1.0.tar.gz.

File metadata

  • Download URL: dimviz-0.1.0.tar.gz
  • Upload date:
  • Size: 38.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.4

File hashes

Hashes for dimviz-0.1.0.tar.gz
Algorithm Hash digest
SHA256 2ac3c1def4ce7c46d1ddc18c4a6be2c1925ea739cb1b142c40e0275f048d8760
MD5 16ddfea26a3be25d23bcb6c4714a3db1
BLAKE2b-256 ef102ba4b007978eac7ee91c4e2b6799ea60fceb3c20fb4225a61919d0b1952b

See more details on using hashes here.

File details

Details for the file dimviz-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: dimviz-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 12.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.4

File hashes

Hashes for dimviz-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 50ff2b90baec1368c4490744097e9607d414d8ad7bf28f4b8f7c2fe59e8921a8
MD5 c5ffef72fa287d6a324ce62f29bde666
BLAKE2b-256 d28f119470b7609b3b7f1535f59a79516c5dad5509e2ce39d1c53b31e308e52e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page