A lightweight debugging tool for tracking tensor shape transformations in PyTorch
Project description
DimViz ๐
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โmatmulaten::addmmโlinear_projaten::conv2dโconv2daten::bmmโbatch_matmulaten::catโconcataten::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
TorchDispatchModeAPI - Visualization powered by Rich (optional)
- Table formatting by tabulate
๐ง Contact
- GitHub: @himalaya-kaushik
- Email: himalaya341@gmail.com
Made with โค๏ธ for the PyTorch community
If you find DimViz helpful, please consider giving it a โญ on GitHub!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2ac3c1def4ce7c46d1ddc18c4a6be2c1925ea739cb1b142c40e0275f048d8760
|
|
| MD5 |
16ddfea26a3be25d23bcb6c4714a3db1
|
|
| BLAKE2b-256 |
ef102ba4b007978eac7ee91c4e2b6799ea60fceb3c20fb4225a61919d0b1952b
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
50ff2b90baec1368c4490744097e9607d414d8ad7bf28f4b8f7c2fe59e8921a8
|
|
| MD5 |
c5ffef72fa287d6a324ce62f29bde666
|
|
| BLAKE2b-256 |
d28f119470b7609b3b7f1535f59a79516c5dad5509e2ce39d1c53b31e308e52e
|