The Linter for PyTorch: Detects silent training bugs.
Project description
๐ฅ torch-audit
The Linter for PyTorch Models
torch-audit is a "check engine light" for your Deep Learning training loop. It detects silent bugs that don't crash your code but ruin your training or waste compute.
- ๐ฅ๏ธ Hardware Efficiency: Detects slow memory layouts (NHWC vs NCHW), mixed-precision failures, and tensor core misalignment.
- ๐งช Data Integrity: Catches broken attention masks, CV layout bugs, and silent NaN/Inf propagation.
- ๐ Training Stability: Identifies exploding gradients, bad optimizer config (Adam vs AdamW), and "dead" neurons.
- ๐ง Graph Logic: Identifies DDP-unsafe "Zombie" layers and redundant computations (e.g., Bias before BatchNorm).
- ๐ง Domain Awareness: Deep inspection for NLP (Padding waste, Tokenizer quality) and CV (Dead filters, Redundant biases).
๐ฆ Installation
Install the standard version (lightweight):
pip install torch-audit
Optional Integrations:
# For PyTorch Lightning support
pip install "torch-audit[lightning]"
# For Hugging Face Transformers support
pip install "torch-audit[hf]"
# For everything
pip install "torch-audit[all]"
๐ Quick Start
You have two ways to use torch-audit: the Decorator (easiest) or the Context Manager (most control).
The Decorator Method (Recommended)
import torch
from torch_audit import Auditor, AuditConfig
# 1. Setup Auditor (Audits every 1000 steps)
config = AuditConfig(interval=1000)
auditor = Auditor(model, optimizer, config=config)
# 2. Static Audit (Run once before training)
# Checks architecture, unused layers, and weight initialization
auditor.audit_static()
# 3. Training Loop
# The decorator handles hooks, data auditing, and error reporting automatically.
@auditor.audit_step
def train_step(batch, targets):
optimizer.zero_grad()
pred = model(batch)
loss = criterion(pred, targets)
loss.backward()
optimizer.step()
for batch, targets in dataloader:
train_step(batch, targets)
The Context Manager Method
# 3. Training Loop
for batch in dataloader:
# Manual data check (optional but recommended)
auditor.audit_data(batch)
# Dynamic checks (Gradients, Activations, Stability)
with auditor.audit_dynamic():
pred = model(batch)
loss = criterion(pred, target)
loss.backward()
optimizer.step()
The Output
When a bug is found, torch-audit prints a structured report. It supports Rich Console tables (default) or JSON/System Logs for production.
๐ Audit Running (Step 5000)...
๐ก Batch size is tiny (4). BatchNorm is unstable. (in Input Batch)
โ ๏ธ Audit Report (Step 5000)
โโโโโโโโโโโโโโโโโโโโโณโโโโโโโโโโโโโโโโณโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Type โ Layer โ Message โ
โกโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฉ
โ ๐ด DDP Safety โ ghost_layer โ Layer defined but NEVER called (Zombie). โ
โ ๐ด Data Integrity โ Input Batch โ Attention Mask mismatch on 50 tokens. โ
โ ๐ก Tensor Core โ fc1 โ Dims (127->64) not divisible by 8. โ
โ ๐ก Stability โ Global โ Optimizer epsilon (1e-08) too low for AMP. โ
โ ๐ต CV Opt โ conv1 โ Bias=True followed by BatchNorm (Redundant).โ
โโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ Runnable Demos
Don't just take our word for it! Break things yourself! We have prepared sabotaged scripts that trigger auditor warnings.
Check out the examples/ folder:
python examples/demo_general.py(General hardware/optimizer issues)python examples/demo_nlp.py(NLP & Tokenizer bugs)python examples/demo_cv.py(Computer Vision bugs)python examples/demo_lightning.py(PyTorch Lightning integration)python examples/demo_hf.py(Hugging Face integration)python examples/demo_accelerate.py(Accelerate integration)
๐งฉ Integrations
We support the ecosystem you already use.
โก PyTorch Lightning
Zero code changes to your loop. Just add the callback.
from lightning.pytorch import Trainer
from torch_audit import Auditor, AuditConfig
from torch_audit.callbacks import LightningAuditCallback
auditor = Auditor(model, config=AuditConfig(interval=100))
trainer = Trainer(callbacks=[LightningAuditCallback(auditor)])
๐ค Hugging Face Trainer
Plug-and-play with the Trainer API.
from transformers import Trainer
from torch_audit import Auditor, AuditConfig
from torch_audit.callbacks import HFAuditCallback
config = AuditConfig(monitor_nlp=True, interval=500)
auditor = Auditor(model, config=config)
trainer = Trainer(..., callbacks=[HFAuditCallback(auditor)])
๐ ๏ธ Capabilities & Modules
๐ฅ๏ธ Hardware & System (Always Active)
- Device Placement: Detects "Split Brain" (CPU/GPU mix) and forgotten
.cuda()calls. - Tensor Cores: Warns if matrix multiplications aren't aligned to 8 (FP16) or 16 (INT8).
- Memory Layout: Detects
NCHWvsNHWCmemory format issues. - Precision: Suggests AMP/BFloat16 if model is 100% FP32.
๐งช Optimization & Stability
- Config: Warns if using
Adamwithweight_decay(suggestsAdamW). - Regularization: Detects weight decay applied to Biases or Norm layers.
- Dynamics: Checks for low
epsilonin Mixed Precision (underflow risk).
๐ NLP Mode
Detects tokenizer issues, padding waste, and untied embeddings.
config = {
'monitor_nlp': True,
'pad_token_id': tokenizer.pad_token_id,
'vocab_size': tokenizer.vocab_size
}
auditor = Auditor(model, config=config)
- Data Integrity: Checks if
attention_maskactually masks the padding tokens ininput_ids. - Efficiency: Calculates wasted compute due to excessive padding (>50%).
- Architecture: Checks if Embedding weights are tied to the Output Head.
๐ผ๏ธ Computer Vision Mode
Detects normalization bugs (0-255 inputs) and dead convolution filters.
auditor = Auditor(model, config={'monitor_cv': True})
- Layout: Detects accidental
[Batch, Height, Width, Channel]input (crashes PyTorch). - Redundant Bias: Detects
Conv2d(bias=True)followed immediately byBatchNorm. - Dead Filters: Identifies convolution filters that have been pruned or collapsed to zero.
โ๏ธ Configuration
You can configure the auditor via a dictionary or the AuditConfig object.
| Parameter | Default | Description |
|---|---|---|
interval |
1 |
Run audit every N steps. Set to 1000+ or more for production. |
limit |
None |
Stop auditing after N reports. |
float_threshold |
10.0 |
Max value allowed in inputs before warning. |
monitor_dead_neurons |
True |
Check for activations death. |
graph_atomic_modules |
[] |
List of custom layers (e.g. FlashAttn) to treat as leaves. |
monitor_graph |
True |
Check for unused (zombie) layers. |
monitor_nlp |
False |
Enable NLP-specific hooks (requires pad_token_id). |
monitor_cv |
False |
Enable CV-specific hooks. |
๐ญ Production Logging
For headless training where you can't see the console, switch to the LogReporter.
from torch_audit.core.reporter import LogReporter
# Writes to standard Python logging (INFO/WARN/ERROR)
auditor = Auditor(model, reporters=[LogReporter()])
๐ ๏ธ Manual Triggering
Sometimes you want to audit, for example, when the loss spikes.
loss = criterion(output, target)
if loss.item() > 10.0:
print("Loss spike! Debugging next step...")
auditor.schedule_next_step() # Forces audit on next forward pass
๐ค Contributing & Feedback
Found a silent bug that torch-audit missed? Have a suggestion for a new Validator?
Open an Issue! We love feedback and contributions.
License
Distributed under the MIT License.
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
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 torch_audit-0.2.0.tar.gz.
File metadata
- Download URL: torch_audit-0.2.0.tar.gz
- Upload date:
- Size: 22.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.1 CPython/3.11.4 Windows/10
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
855aa3ac492760eff230625941a2fb805cf6f7a41eaaadd66c28df4b13c9f58e
|
|
| MD5 |
498a62a6cfe39fbe0acefedc1c4f7b1b
|
|
| BLAKE2b-256 |
b13ddc42a3979366fc050b6ce8eb5efd1f5ccd3dee088f04e937fee8b42c9277
|
File details
Details for the file torch_audit-0.2.0-py3-none-any.whl.
File metadata
- Download URL: torch_audit-0.2.0-py3-none-any.whl
- Upload date:
- Size: 29.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.1 CPython/3.11.4 Windows/10
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9728a0902e9faddc08c3b218b06aa8fe883b00ef08e2fa2054762d1a892ce5a0
|
|
| MD5 |
8395cba2345a8f319035e8e0728011fa
|
|
| BLAKE2b-256 |
78d4d098601b54d47adb4c0e2833a9495dd73ecd849e7dede859a19b98bbe19c
|