Skip to main content

Zero-dependency quantization diagnostic toolkit for neural networks

Project description

๐Ÿ”ฌ quant-lens

A Zero-Dependency Quantization Diagnostic Toolkit

Visualize loss landscapes and Hessian sharpness to diagnose "bit collapse" in quantized neural networks.

Python PyTorch License Tests


๐ŸŽฏ Why quant-lens?

When you quantize a model from FP32 โ†’ INT8, you're compressing billions of real numbers into discrete buckets. This "bit collapse" can:

  • โœ… Sharpen loss minima (making them fragile)
  • โœ… Distort the loss landscape geometry
  • โœ… Destroy generalization without obvious warning signs

quant-lens lets you see these effects before they ruin your deployment.


๐Ÿš€ Quick Start

Installation

pip install torch torchvision numpy matplotlib quant-lens

Basic Usage

from quant_lens import QuantDiagnostic
import torch
from torch.utils.data import DataLoader

# 1. Load your FP32 model
model = torch.load('my_model.pth')

# 2. Prepare calibration data
dataloader = DataLoader(dataset, batch_size=64)

# 3. Initialize diagnostic
diagnostic = QuantDiagnostic(model, dataloader, device='cuda')

# 4. Add quantized variant (auto-generated)
diagnostic.add_int8_model()

# 5. Run analysis
metrics = diagnostic.run_analysis()

# 6. Generate visualization
diagnostic.plot(save_path='bit_collapse.png')

Output:

โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘    QUANTIZATION DIAGNOSTICS RESULTS       โ•‘
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

๐Ÿ“Š SHARPNESS COMPARISON:
   FP32         ฮป_max = 0.234567
   Int8         ฮป_max = 0.876543

   Sharpness Ratio (Int8/FP32): 3.74x
   โš ๏ธ  Quantization significantly increased sharpness!

๐Ÿ“Š What You Get

1. Hessian Spectrum Analysis

Computes the top eigenvalue (ฮป_max) of the Hessian using Power Iteration:

  • Low ฮป_max โ†’ Flat minimum (good generalization)
  • High ฮป_max โ†’ Sharp minimum (poor generalization)
  • Ratio > 1.5x โ†’ Quantization degraded the optimum

2. Loss Landscape Visualization

Traces the loss surface along a random direction using Filter Normalization (Li et al., 2018):

Example Landscape

Blue Line (FP32): Wide, smooth valley โœ…
Red Line (Int8): Narrow, jagged ravine โš ๏ธ


๐Ÿง  How It Works

Architecture Overview

quant-lens/
โ”œโ”€โ”€ quantization.py   # FakeQuant with STE (Straight-Through Estimator)
โ”œโ”€โ”€ geometry.py       # Loss landscape tracing with filter normalization
โ”œโ”€โ”€ hessian.py        # Power iteration for Hessian eigenvalues
โ”œโ”€โ”€ plotting.py       # Matplotlib visualization
โ””โ”€โ”€ core.py           # Main API (QuantDiagnostic class)

Key Innovations

1. Straight-Through Estimator (STE)

Quantization is non-differentiable. We use STE to approximate gradients:

# Forward: Quantize
x_quant = round(x / scale) * scale

# Backward: Pretend it's identity
grad_x = grad_output  # Pass through unchanged

2. Filter Normalization

Neural networks with BatchNorm are scale-invariant. We normalize random directions to ensure fair comparisons:

d_ij = (d_ij / ||d_ij||) * ||ฮธ_ij||

This removes the artificial "smoothing" effect caused by large weights.

3. Power Iteration

Computing the full Hessian is prohibitively expensive. We use power iteration to find the dominant eigenvalue:

for _ in range(20):
    v = H @ v  # Hessian-vector product
    v = v / ||v||
ฮป_max = v^T @ H @ v  # Rayleigh quotient

๐Ÿ”ฌ Advanced Usage

Multiple Quantization Schemes

diagnostic = QuantDiagnostic(model_fp32, dataloader)

# Test different bit widths
diagnostic.add_int8_model(num_bits=8, name="Int8")
diagnostic.add_int8_model(num_bits=4, name="Int4")
diagnostic.add_int8_model(num_bits=2, name="Int2")

metrics = diagnostic.run_analysis()
diagnostic.plot(save_path='multibit_analysis.png')

Custom Quantized Models

# If you already have a quantized model
model_custom = torch.quantization.quantize_dynamic(
    model_fp32, {torch.nn.Linear}, dtype=torch.qint8
)

diagnostic.add_int8_model(model_int8=model_custom, name="CustomInt8")

Fine-Tuning the Analysis

metrics = diagnostic.run_analysis(
    landscape_steps=50,    # More points = smoother curve
    hessian_iters=30       # More iterations = better eigenvalue
)

๐Ÿ“– Theoretical Background

Filter Normalization (Li et al., 2018)

"Visualizing the Loss Landscape of Neural Nets" - NeurIPS 2018

Key insight: Networks with BatchNorm exhibit scale invariance. Multiplying weights by a constant doesn't change the function. Filter normalization removes this artifact.

Straight-Through Estimator (Bengio et al., 2013)

"Estimating or Propagating Gradients Through Stochastic Neurons"

The STE allows training discrete networks by approximating โˆ‚f/โˆ‚x โ‰ˆ 1 during backpropagation, even though the true gradient is zero almost everywhere.

Power Iteration (Golub & Van Loan, 2013)

Classic algorithm for finding dominant eigenvectors. Converges geometrically at rate |ฮปโ‚‚/ฮปโ‚|.


โš™๏ธ Requirements

  • Python โ‰ฅ 3.8
  • PyTorch โ‰ฅ 2.0
  • NumPy โ‰ฅ 1.20
  • Matplotlib โ‰ฅ 3.5

Note: No external dependencies like loss-landscapes or PyHessian. Everything is self-contained to avoid version conflicts and OOM errors.


๐Ÿ› Troubleshooting

Issue: CUDA Out of Memory

# Use smaller batches for calibration
dataloader = DataLoader(dataset, batch_size=16)  # Reduce from 64

Issue: Power Iteration Fails

# Increase iterations or check for numerical instability
metrics = diagnostic.run_analysis(hessian_iters=50)

Issue: Flat Landscape (No Variation)

# Increase distance to explore wider region
diagnostic.add_int8_model()
x, y = trace_1d_loss(model, loader, criterion, device, distance=1.0)

๐ŸŽ“ Citation

If you use quant-lens in your research, please cite:

@software{quant_lens_2026,
  title={quant-lens: Diagnostic Toolkit for Neural Network Quantization},
  author={Sairam S},
  year={2026},
  url={https://github.com/s-sairam/quant-lens}
}

References:

  • Li et al. (2018) - Visualizing the Loss Landscape of Neural Nets
  • Bengio et al. (2013) - Estimating Gradients Through Stochastic Neurons
  • Yin et al. (2019) - Understanding Straight-Through Estimators

๐Ÿ“œ License

MIT License - See LICENSE file for details


๐Ÿค Contributing

Contributions welcome! Please open an issue or PR.

Roadmap:

  • 2D landscape visualization
  • Batch Normalization statistics tracking
  • Layer-wise sharpness analysis
  • Integration with torchao/QAT
  • Support for activation quantization

๐Ÿ’ฌ Contact

Questions? Open an issue or reach out at: saisr2206@gmail.com

Happy quantizing! ๐Ÿš€

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

quant_lens-0.1.0.tar.gz (34.6 kB view details)

Uploaded Source

Built Distribution

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

quant_lens-0.1.0-py3-none-any.whl (12.1 kB view details)

Uploaded Python 3

File details

Details for the file quant_lens-0.1.0.tar.gz.

File metadata

  • Download URL: quant_lens-0.1.0.tar.gz
  • Upload date:
  • Size: 34.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for quant_lens-0.1.0.tar.gz
Algorithm Hash digest
SHA256 4db61895badc0cbf7c1fd24a344818c17fedf83a8536f08167a8be93ac153d1f
MD5 bd22843d63e8db349401acc3844d16e7
BLAKE2b-256 bb5a010f53f2476e8a9fba01ec2cb5d88742319bb1903bf938437ea3ca5003ed

See more details on using hashes here.

File details

Details for the file quant_lens-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: quant_lens-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 12.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for quant_lens-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 eea170a14fc8dd1f04995c9f714eb7e5bfbd560ca4ab3d131e5d97899638fd16
MD5 ea8fa1a980bca27b9418511e603b5a70
BLAKE2b-256 e62123ebd8cf8522d1aa475b24b751e4041121cad1be54cf42903e15be4ddc2c

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