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.
๐ฏ 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):
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
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 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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4db61895badc0cbf7c1fd24a344818c17fedf83a8536f08167a8be93ac153d1f
|
|
| MD5 |
bd22843d63e8db349401acc3844d16e7
|
|
| BLAKE2b-256 |
bb5a010f53f2476e8a9fba01ec2cb5d88742319bb1903bf938437ea3ca5003ed
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
eea170a14fc8dd1f04995c9f714eb7e5bfbd560ca4ab3d131e5d97899638fd16
|
|
| MD5 |
ea8fa1a980bca27b9418511e603b5a70
|
|
| BLAKE2b-256 |
e62123ebd8cf8522d1aa475b24b751e4041121cad1be54cf42903e15be4ddc2c
|