A comprehensive, hands-on tutorial for understanding and implementing Large Language Model (LLM) quantization with executable GPU examples.
- Introduction
- What is Quantization?
- Why Quantization Matters
- Types of Quantization
- Setup Instructions
- Tutorial Examples
- Performance Benchmarks
- References
This tutorial provides practical, executable examples for quantizing Large Language Models (LLMs) to reduce memory footprint and increase inference speed on GPUs. All examples are designed to run on CUDA-enabled GPUs.
Quantization is the process of reducing the precision of numerical values in a neural network model. In the context of LLMs:
- Original Models: Typically use 32-bit floating-point (FP32) or 16-bit floating-point (FP16) numbers
- Quantized Models: Use lower-precision formats like 8-bit integers (INT8) or even 4-bit representations
The basic quantization process involves mapping floating-point values to discrete integer values:
Q(x) = round(x / S) - Z
Where:
xis the original floating-point valueSis the scale factorZis the zero-pointQ(x)is the quantized integer value
Dequantization reverses this process:
x̂ = S * (Q(x) + Z)
- FP32 → INT8: 4× memory reduction
- FP32 → INT4: 8× memory reduction
- Enables running larger models on consumer hardware
- Integer operations are faster than floating-point operations
- Better cache utilization due to smaller memory footprint
- Can achieve 2-4× inference speedup
- Lower memory requirements = cheaper GPU deployment
- Reduced cloud computing costs
- Enables edge deployment
For a 7B parameter model (7 billion parameters):
| Precision | Bytes/Param | Total Memory | Reduction |
|---|---|---|---|
| FP32 | 4 bytes | 28 GB | - |
| FP16 | 2 bytes | 14 GB | 2× |
| INT8 | 1 byte | 7 GB | 4× |
| INT4 | 0.5 bytes | 3.5 GB | 8× |
- Quantize an already-trained model
- No retraining required
- Quick to implement
- May have some accuracy loss
- Train model with quantization in mind
- Better accuracy preservation
- More computationally expensive
- Quantize activations dynamically at runtime
- Weights are quantized statically
- Good balance between speed and accuracy
- Both weights and activations are quantized
- Requires calibration dataset
- Best performance gains
- Python 3.8+
- CUDA-capable GPU (with compute capability 7.0+)
- CUDA Toolkit 11.8+ or 12.0+
Using uv (recommended - much faster!):
# Install uv if you haven't already
curl -LsSf https://astral.sh/uv/install.sh | sh
# Clone the repository
git clone <repository-url>
cd quantization_tutorial
# Create environment and install dependencies (all in one command!)
uv sync
# Activate the virtual environment
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Verify GPU availability
python -c "import torch; print(f'CUDA available: {torch.cuda.is_available()}')"Alternative - using pip:
# Clone the repository
git clone <repository-url>
cd quantization_tutorial
# Create a virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Verify GPU availability
python -c "import torch; print(f'CUDA available: {torch.cuda.is_available()}')"Minimum:
- GPU: NVIDIA GPU with 8GB VRAM
- RAM: 16GB system RAM
Recommended:
- GPU: NVIDIA RTX 3090, A100, or better
- RAM: 32GB+ system RAM
This tutorial is available in two formats:
Perfect for learning and experimentation. Run cells interactively, modify code, and see results immediately.
notebooks/01_basic_int8_quantization.ipynbnotebooks/02_4bit_quantization.ipynbnotebooks/03_llm_bitsandbytes.ipynbnotebooks/04_gptq_quantization.ipynbnotebooks/05_comparison_benchmark.ipynb
Run with:
jupyter notebook notebooks/
# Or use JupyterLab, VS Code, or Google ColabComplete standalone scripts. Run start-to-finish without interaction.
examples/01_basic_int8_quantization.pyexamples/02_4bit_quantization.pyexamples/03_llm_bitsandbytes.pyexamples/04_gptq_quantization.pyexamples/05_comparison_benchmark.py
Run with:
python examples/01_basic_int8_quantization.pyFile: examples/01_basic_int8_quantization.py
Learn the fundamentals of symmetric and asymmetric INT8 quantization with PyTorch.
python examples/01_basic_int8_quantization.pyFile: examples/02_4bit_quantization.py
Implement 4-bit quantization for maximum memory savings.
python examples/02_4bit_quantization.pyFile: examples/03_llm_bitsandbytes.py
Quantize and run actual LLM models using the popular bitsandbytes library.
python examples/03_llm_bitsandbytes.pyFile: examples/04_gptq_quantization.py
Advanced quantization using GPTQ (Generative Pre-trained Transformer Quantization).
python examples/04_gptq_quantization.pyFile: examples/05_comparison_benchmark.py
Compare different quantization methods side-by-side with benchmarks.
python examples/05_comparison_benchmark.pyTypical results you can expect (tested on NVIDIA RTX 3090):
| Model | Precision | Memory | Speed (tokens/sec) | Perplexity |
|---|---|---|---|---|
| LLaMA-7B | FP16 | 14 GB | 25 | 5.68 |
| LLaMA-7B | INT8 | 7 GB | 45 | 5.72 |
| LLaMA-7B | INT4 | 3.5 GB | 60 | 5.89 |
- Symmetric vs Asymmetric Quantization
- Per-tensor vs Per-channel Quantization
- Calibration Techniques
- Mixed-precision Quantization
- Quantization Error Analysis
- Hardware-specific Optimizations
Solution: Use per-channel quantization and careful calibration
Solution: Ensure you're using optimized kernels (TensorRT, ONNXRuntime)
Solution: Use gradient checkpointing and batch the quantization process
- GGML/GGUF Format: Specialized quantization for llama.cpp
- AWQ (Activation-aware Weight Quantization): Preserve important weights
- SmoothQuant: Address outliers in activations
- ZeroQuant: Microsoft's zero-shot quantization
Contributions are welcome! Please feel free to submit pull requests or open issues.
- Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference
- LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale
- GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers
- AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration
MIT License - see LICENSE file for details
Happy Quantizing! 🚀