A zero-overhead, framework-specific tensor shape validator for PyTorch, TensorFlow, and NumPy.
Project description
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/
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 tensor_shape_guard-0.1.0.tar.gz.
File metadata
- Download URL: tensor_shape_guard-0.1.0.tar.gz
- Upload date:
- Size: 10.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7158e746a95e44137e5cf6477ad3e20ebef80b55f3d6b892406886843b8f36f5
|
|
| MD5 |
e7bfce76f9472089afe0dd5db6c0e398
|
|
| BLAKE2b-256 |
cdf37990f5189d65130c73dfe7fedeed7be255825acda87c7fb28bb7ec98aca0
|
Provenance
The following attestation bundles were made for tensor_shape_guard-0.1.0.tar.gz:
Publisher:
publish.yml on ginganomercy/tensorguard
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
tensor_shape_guard-0.1.0.tar.gz -
Subject digest:
7158e746a95e44137e5cf6477ad3e20ebef80b55f3d6b892406886843b8f36f5 - Sigstore transparency entry: 2073776448
- Sigstore integration time:
-
Permalink:
ginganomercy/tensorguard@e881a8952ba4ea440a23a0fb574bfc9f18cce679 -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/ginganomercy
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@e881a8952ba4ea440a23a0fb574bfc9f18cce679 -
Trigger Event:
push
-
Statement type:
File details
Details for the file tensor_shape_guard-0.1.0-py3-none-any.whl.
File metadata
- Download URL: tensor_shape_guard-0.1.0-py3-none-any.whl
- Upload date:
- Size: 11.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
76270a34ad139ab5bdd7646860ca3647a01fcf1b7479fea41fa9c1331dfda001
|
|
| MD5 |
e1586092ddb9a54a318ed9a4917a7858
|
|
| BLAKE2b-256 |
61f1cba18467755834b36af97aa1e0d9c899ae7acb3c11f070984e1ff7d39bab
|
Provenance
The following attestation bundles were made for tensor_shape_guard-0.1.0-py3-none-any.whl:
Publisher:
publish.yml on ginganomercy/tensorguard
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
tensor_shape_guard-0.1.0-py3-none-any.whl -
Subject digest:
76270a34ad139ab5bdd7646860ca3647a01fcf1b7479fea41fa9c1331dfda001 - Sigstore transparency entry: 2073776467
- Sigstore integration time:
-
Permalink:
ginganomercy/tensorguard@e881a8952ba4ea440a23a0fb574bfc9f18cce679 -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/ginganomercy
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@e881a8952ba4ea440a23a0fb574bfc9f18cce679 -
Trigger Event:
push
-
Statement type: