Skip to main content

The Linter for PyTorch: Detects silent training bugs.

Project description

๐Ÿ”ฅ torch-audit

The Linter for PyTorch Models

PyPI License: MIT Python 3.8+ Code Style: Black

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 NCHW vs NHWC memory format issues.
  • Precision: Suggests AMP/BFloat16 if model is 100% FP32.

๐Ÿงช Optimization & Stability

  • Config: Warns if using Adam with weight_decay (suggests AdamW).
  • Regularization: Detects weight decay applied to Biases or Norm layers.
  • Dynamics: Checks for low epsilon in 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_mask actually masks the padding tokens in input_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 by BatchNorm.
  • 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

torch_audit-0.2.0.tar.gz (22.9 kB view details)

Uploaded Source

Built Distribution

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

torch_audit-0.2.0-py3-none-any.whl (29.0 kB view details)

Uploaded Python 3

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

Hashes for torch_audit-0.2.0.tar.gz
Algorithm Hash digest
SHA256 855aa3ac492760eff230625941a2fb805cf6f7a41eaaadd66c28df4b13c9f58e
MD5 498a62a6cfe39fbe0acefedc1c4f7b1b
BLAKE2b-256 b13ddc42a3979366fc050b6ce8eb5efd1f5ccd3dee088f04e937fee8b42c9277

See more details on using hashes here.

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

Hashes for torch_audit-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9728a0902e9faddc08c3b218b06aa8fe883b00ef08e2fa2054762d1a892ce5a0
MD5 8395cba2345a8f319035e8e0728011fa
BLAKE2b-256 78d4d098601b54d47adb4c0e2833a9495dd73ecd849e7dede859a19b98bbe19c

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