TensorGuard
A zero-overhead, declarative tensor shape and dtype validator for PyTorch, TensorFlow, and NumPy.
The Problem: Silent Broadcasting & Shape Mismatches
If you are a Data Scientist, ML Researcher, or AI Engineer, you know the pain: you wait 4 hours for a model to train, only for it to crash due to a Tensor Shape Mismatch deep inside a loss function. Even worse, Silent Broadcasting might occur where PyTorch or TensorFlow silently reshapes your matrices, leading to entirely incorrect mathematical calculations without throwing a single error.
Standard validation using assert x.shape == (batch, channels, h, w) has major flaws:
- It is repetitive and clutters your clean domain logic.
- It evaluates every time, slowing down your high-performance training loops.
- It cannot easily track variable consistencies (e.g., ensuring
batch_sizematches across 3 different arguments). - Error traces are unreadable.
The Solution: TensorGuard
TensorGuard introduces a beautiful, declarative decorator approach to validate tensor structures at the boundaries of your functions. Built from First-Principles, it acts as a strict compile-time/runtime checker during development, and completely vanishes during production.
Key Features
- Zero-Overhead in Production: Set
TENSORGUARD_ENV=productionand the decorators instantly return the original function, adding 0 nanoseconds of latency to your production pipelines. - Cross-Argument Consistency: If you declare
images="b c h w"andlabels="b", TensorGuard guarantees the value ofbis mathematically identical for both. - Rich Error Formatting: When a mismatch occurs, TensorGuard prints a beautiful, colorful visual table pointing exactly to which dimension failed, drastically reducing debugging time.
- Framework-Specific Strictness:
tensorguard.pytorch: Automatically enforces.deviceconsistency (no morecuda:0vscpucrashes) and checkstorch.dtype.tensorguard.tensorflow: Gracefully handlesNonedynamic dimensions in@tf.functiongraph compilation mode.tensorguard.numpy: Ensures strict adherence tonp.ndarraystructures for data engineering pipelines.
Installation
Install TensorGuard via pip:
pip install tensor-shape-guard
Quick Start & Usage
1. PyTorch
TensorGuard shines in PyTorch by also automatically validating device alignment.
import torch
from tensorguard.pytorch import validate
class VisionModel(torch.nn.Module):
# Enforces shape logic, return shapes, and dtypes
@validate(
images="batch channels height width",
labels="batch",
dtypes={"images": "float32"},
returns="batch classes"
)
def forward(self, images, labels):
# Business logic goes here
# If images is on cuda:0 and labels is on cpu, TensorGuard catches it!
return torch.zeros((images.shape[0], 10))
model = VisionModel()
img = torch.randn(32, 3, 224, 224, dtype=torch.float32)
lbl = torch.randint(0, 10, (32,))
# Works flawlessly
model(img, lbl)
2. TensorFlow
TensorGuard handles Symbolic variables seamlessly.
import tensorflow as tf
from tensorguard.tensorflow import validate
# Handles 'None' dynamic dimensions gracefully in graph mode
@validate(images="batch 224 224 3", dtypes={"images": "float32"})
@tf.function
def model_step(images):
return tf.zeros((tf.shape(images)[0], 10))
How to Bypass in Production
TensorGuard is built for zero-compromise performance. Once you are confident your shapes are correct and you are deploying to an edge device or high-traffic API, simply set the environment variable:
export TENSORGUARD_ENV=production
(All @validate decorators will now have zero overhead).
Support This Project
TensorGuard is an open-source project. If it has saved you valuable GPU hours and debugging time, consider supporting the creator by following on Instagram!
Contributing & Testing
We welcome PRs! To run the test suite locally:
# Clone the repository
git clone https://github.com/ginganomercy/tensorguard.git
cd tensorguard
# Install with development dependencies
pip install -e .[dev,numpy]
# Run tests
pytest tests/
Metadata
Release files for tensor-shape-guard 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| tensor_shape_guard-0.1.0.tar.gz | 10.2 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| tensor_shape_guard-0.1.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 21.3 kB
Release files / tensor_shape_guard-0.1.0.tar.gz
| Download URL | tensor_shape_guard-0.1.0.tar.gz |
|---|---|
| Size | 10.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7158e746a95e44137e5cf6477ad3e20ebef80b55f3d6b892406886843b8f36f5
|
|
BLAKE2b-256 checksum How to use checksums |
cdf37990f5189d65130c73dfe7fedeed7be255825acda87c7fb28bb7ec98aca0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 5, 2026.
Transparency logRelease files / tensor_shape_guard-0.1.0-py3-none-any.whl
| Download URL | tensor_shape_guard-0.1.0-py3-none-any.whl |
|---|---|
| Size | 11.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
76270a34ad139ab5bdd7646860ca3647a01fcf1b7479fea41fa9c1331dfda001
|
|
BLAKE2b-256 checksum How to use checksums |
61f1cba18467755834b36af97aa1e0d9c899ae7acb3c11f070984e1ff7d39bab
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 5, 2026.
Transparency log