Skip to content

Commit 4710be2

Browse files
Merge pull request #4 from Prajwal7-2002/feature/calibration-algorithms
feat: implement advanced calibration algorithms (SmoothQuant, AWQ, GPTQ)
2 parents 1c1410b + 74e3ffa commit 4710be2

9 files changed

Lines changed: 818 additions & 3 deletions

File tree

‎DEVLOG.md‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,17 @@
3333
- In-place recursive model converter traversing PyTorch module trees.
3434
- Swaps targeted linear layers (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`) while cleanly preserving sensitive layers (`lm_head`).
3535
- Reports layer conversion counts, memory reduction statistics, and elapsed conversion duration.
36-
- Added comprehensive unit tests in `tests/test_quant_linear.py`:
37-
- 31/31 unit tests passing across entire repo with 93% coverage in 2.27s. All Ruff checks passing.
36+
## 2026-10-26: Phase 4 — Advanced Calibration Algorithms (SmoothQuant, AWQ, GPTQ)
37+
38+
- Created `quantbench.quant.algorithms`:
39+
- `smoothquant.py`: Implemented activation outlier channel profiling and per-channel migration scale computation ($Y = (X \cdot \text{diag}(s)^{-1}) \cdot (\text{diag}(s) \cdot W)$). Mathematical verification confirms exact continuous output invariance before discrete rounding.
40+
- `awq.py`: Implemented Activation-aware Weight Quantization with mean activation channel profiling and grid-search over scale candidate $\alpha \in [0, 1]$ to minimize Frobenius reconstruction error $\| W X - \hat{W} X \|_F^2$.
41+
- `gptq.py`: Implemented Accurate Post-Training Quantization for Generative Pre-trained Transformers using empirical activation Hessian ($H = 2 X X^T$), diagonal damping regularization ($H_{\text{damp}} = H + \lambda \cdot \text{mean}(\text{diag}(H)) \cdot I$), Cholesky decomposition inversion ($H^{-1} = L^{-T} L^{-1}$), Optimal Brain Surgeon (OBS) coordinate updates, and vectorized block GEMM updates ($W_{:, j+B:} \mathrel{-}= E_{\text{block}} \cdot [H^{-1}]_{j:j+B, j+B:}$).
42+
- Added comprehensive unit tests in `tests/test_algorithms.py`:
43+
- Outlier profiling and continuous mathematical invariance testing.
44+
- AWQ reconstruction error reduction testing on synthetic salient channels.
45+
- Hessian symmetry, positive semi-definiteness, and GPTQ OBS error reduction testing.
46+
- 39/39 unit tests passing with 93% test coverage across the repository. All Ruff checks passing.
47+
3848

3949

‎README.md‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,28 @@ converted_model, stats = convert_model_to_quant(
119119
exclude_modules=["lm_head"],
120120
)
121121
print(f"Compressed {stats['converted_layers']} layers: {stats['orig_memory_mb']} MB -> {stats['quant_memory_mb']} MB ({stats['compression_ratio']}x)")
122+
123+
# 3. Advanced Calibration Algorithms (SmoothQuant, AWQ, GPTQ)
124+
from quantbench import (
125+
smooth_linear_weights,
126+
extract_activation_channel_scales,
127+
search_best_awq_scale,
128+
compute_activation_channel_means,
129+
gptq_quantize_weights,
130+
compute_activation_hessian,
131+
)
132+
133+
# SmoothQuant: Migrate activation outlier dynamic range to weights
134+
act_scales = extract_activation_channel_scales(linear, calibration_x)
135+
w_smoothed, scale = smooth_linear_weights(linear.weight, act_scales, alpha=0.5)
136+
137+
# AWQ: Search optimal per-channel protection scales
138+
act_means = compute_activation_channel_means(calibration_x)
139+
best_scale, best_alpha = search_best_awq_scale(linear.weight, act_means, calibration_x)
140+
141+
# GPTQ: Second-order Hessian error compensation
142+
H = compute_activation_hessian(calibration_x, in_features=4096)
143+
w_gptq = gptq_quantize_weights(linear.weight, H, bits=4, group_size=128)
122144
```
123145

124146
---
@@ -128,7 +150,7 @@ print(f"Compressed {stats['converted_layers']} layers: {stats['orig_memory_mb']}
128150
- [x] **Phase 1: Mathematical Primitives & Invariants**: Affine, AbsMax, Group-wise, and FP8 (E4M3/E5M2) simulation with rigorous error bound verification.
129151
- [x] **Phase 2: Integer Bit-Packing Runtimes**: Vectorized INT4 nibble packing (`uint8`), BitNet ternary packing, and 2:4 sparsity metadata.
130152
- [x] **Phase 3: Drop-in Neural Layers**: `QuantLinear` PyTorch module, in-place Hugging Face model converter, and buffer serialization.
131-
- [ ] **Phase 4: Advanced Optimization Algorithms**: SmoothQuant outlier migration, AWQ grid search, and GPTQ second-order Hessian updates.
153+
- [x] **Phase 4: Advanced Calibration Algorithms**: SmoothQuant outlier migration, AWQ grid search, and GPTQ second-order Hessian updates.
132154
- [ ] **Phase 5: Perplexity & Evaluation Engine**: Standardized sliding-window perplexity on WikiText-2 and C4.
133155
- [ ] **Phase 6: servebench Bridge & Pareto Visualizer**: Empirical throughput (tok/s) profiling and terminal ASCII Pareto curves.
134156
- [ ] **Phase 7: Public Learning Guide & Packaging**: Comprehensive educational walkthrough and PyPI release.

‎src/quantbench/__init__.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,16 @@
1010
quantize_absmax,
1111
quantize_affine,
1212
)
13+
from quantbench.quant.algorithms import (
14+
awq_quantize_weights,
15+
compute_activation_channel_means,
16+
compute_activation_hessian,
17+
compute_smoothquant_scale,
18+
extract_activation_channel_scales,
19+
gptq_quantize_weights,
20+
search_best_awq_scale,
21+
smooth_linear_weights,
22+
)
1323
from quantbench.quant.blockwise import dequantize_blockwise, quantize_blockwise
1424
from quantbench.quant.fp8 import FP8Format, dequantize_fp8, quantize_fp8
1525
from quantbench.quant.packing import (
@@ -44,4 +54,12 @@
4454
"unpack_2_4_indices",
4555
"prune_and_compress_2_4",
4656
"decompress_2_4",
57+
"compute_smoothquant_scale",
58+
"extract_activation_channel_scales",
59+
"smooth_linear_weights",
60+
"compute_activation_channel_means",
61+
"search_best_awq_scale",
62+
"awq_quantize_weights",
63+
"compute_activation_hessian",
64+
"gptq_quantize_weights",
4765
]

‎src/quantbench/quant/__init__.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,16 @@
66
quantize_absmax,
77
quantize_affine,
88
)
9+
from quantbench.quant.algorithms import (
10+
awq_quantize_weights,
11+
compute_activation_channel_means,
12+
compute_activation_hessian,
13+
compute_smoothquant_scale,
14+
extract_activation_channel_scales,
15+
gptq_quantize_weights,
16+
search_best_awq_scale,
17+
smooth_linear_weights,
18+
)
919
from quantbench.quant.blockwise import dequantize_blockwise, quantize_blockwise
1020
from quantbench.quant.fp8 import FP8Format, dequantize_fp8, quantize_fp8
1121
from quantbench.quant.packing import (
@@ -37,4 +47,12 @@
3747
"unpack_2_4_indices",
3848
"prune_and_compress_2_4",
3949
"decompress_2_4",
50+
"compute_smoothquant_scale",
51+
"extract_activation_channel_scales",
52+
"smooth_linear_weights",
53+
"compute_activation_channel_means",
54+
"search_best_awq_scale",
55+
"awq_quantize_weights",
56+
"compute_activation_hessian",
57+
"gptq_quantize_weights",
4058
]
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Copyright 2026 Prajwal7-2002
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Advanced calibration algorithms for post-training quantization."""
16+
17+
from quantbench.quant.algorithms.awq import (
18+
awq_quantize_weights,
19+
compute_activation_channel_means,
20+
search_best_awq_scale,
21+
)
22+
from quantbench.quant.algorithms.gptq import (
23+
compute_activation_hessian,
24+
gptq_quantize_weights,
25+
)
26+
from quantbench.quant.algorithms.smoothquant import (
27+
compute_smoothquant_scale,
28+
extract_activation_channel_scales,
29+
smooth_linear_weights,
30+
)
31+
32+
__all__ = [
33+
"compute_smoothquant_scale",
34+
"extract_activation_channel_scales",
35+
"smooth_linear_weights",
36+
"compute_activation_channel_means",
37+
"search_best_awq_scale",
38+
"awq_quantize_weights",
39+
"compute_activation_hessian",
40+
"gptq_quantize_weights",
41+
]
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
# Copyright 2026 Prajwal7-2002
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration.
16+
17+
Mathematical Foundation:
18+
Not all weights in a neural network are equally critical to perplexity.
19+
AWQ discovers that protecting the top ~1% of salient weights avoids perplexity
20+
degradation even at aggressive INT4/INT3 regimes. Crucially, salient weights
21+
directly correspond to channels that process activations with high magnitudes:
22+
s_X = (1 / N) * sum(|X|) (mean absolute activation per input channel)
23+
24+
Instead of maintaining mixed-precision floating-point formats (which incur runtime
25+
overhead and degrade hardware SIMD execution efficiency), AWQ applies a per-channel
26+
protection scale s:
27+
W' = W * diag(s)
28+
X' = diag(s)^-1 * X
29+
30+
When W' is quantized to sub-byte integers (e.g. INT4 blockwise), the relative quantization
31+
error on salient channels is inversely proportional to s_j:
32+
Delta W_j / W_j ~ 1 / s_j
33+
34+
AWQ searches for the optimal per-channel scale s_j = (s_{X, j})^alpha over a grid of
35+
alpha in [0.0, 1.0] by directly minimizing the Frobenius output reconstruction error:
36+
min_alpha || W * X - [Quantize(W * diag(s)) * diag(s)^-1] * X ||_F^2
37+
"""
38+
39+
from __future__ import annotations
40+
41+
from typing import Callable, Optional, Tuple
42+
43+
import torch
44+
45+
from quantbench.quant.blockwise import dequantize_blockwise, quantize_blockwise
46+
47+
48+
def compute_activation_channel_means(
49+
calibration_inputs: list[torch.Tensor] | torch.Tensor,
50+
) -> torch.Tensor:
51+
"""Calculate mean absolute activation magnitude per input channel.
52+
53+
Args:
54+
calibration_inputs: Tensor of shape (..., in_features) or list of tensors.
55+
56+
Returns:
57+
Tensor of shape (in_features,) containing per-channel mean absolute activation.
58+
"""
59+
if isinstance(calibration_inputs, torch.Tensor):
60+
calibration_inputs = [calibration_inputs]
61+
62+
total_sum: Optional[torch.Tensor] = None
63+
total_tokens = 0
64+
65+
for batch in calibration_inputs:
66+
flat = batch.detach().view(-1, batch.shape[-1]).abs()
67+
batch_sum = flat.sum(dim=0)
68+
n_tokens = flat.shape[0]
69+
70+
if total_sum is None:
71+
total_sum = batch_sum
72+
else:
73+
total_sum = total_sum + batch_sum
74+
total_tokens += n_tokens
75+
76+
if total_sum is None or total_tokens == 0:
77+
raise ValueError("calibration_inputs cannot be empty.")
78+
79+
return total_sum / total_tokens
80+
81+
82+
def search_best_awq_scale(
83+
weight: torch.Tensor,
84+
act_means: torch.Tensor,
85+
calibration_x: torch.Tensor,
86+
quant_fn: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
87+
n_grid: int = 20,
88+
max_alpha: float = 1.0,
89+
) -> Tuple[torch.Tensor, float]:
90+
"""Perform grid search for optimal AWQ protection scale alpha.
91+
92+
Args:
93+
weight: Float tensor of shape (out_features, in_features).
94+
act_means: Channel-wise activation mean of shape (in_features,).
95+
calibration_x: Sample calibration activations of shape (N_samples, in_features).
96+
quant_fn: Quantize-and-dequantize callable. Defaults to INT4 blockwise (group_size=128).
97+
n_grid: Number of search points in alpha grid [0, max_alpha].
98+
max_alpha: Maximum alpha value for search.
99+
100+
Returns:
101+
Tuple of (optimal_scale_vector, best_alpha):
102+
- optimal_scale_vector: Per-channel scale s in R^{in_features}.
103+
- best_alpha: Optimal alpha hyperparameter.
104+
"""
105+
if quant_fn is None:
106+
def default_quant(w: torch.Tensor) -> torch.Tensor:
107+
q_b, s_b, zp_b, meta = quantize_blockwise(
108+
w, group_size=min(128, w.shape[1]), num_bits=4
109+
)
110+
return dequantize_blockwise(q_b, s_b, zp_b, meta)
111+
quant_fn = default_quant
112+
113+
# Reference unquantized linear output
114+
# calibration_x: (N, in_features), weight: (out_features, in_features)
115+
# y_ref: (N, out_features)
116+
y_ref = calibration_x @ weight.t()
117+
118+
best_error = float("inf")
119+
best_scale = torch.ones(weight.shape[1], device=weight.device, dtype=weight.dtype)
120+
best_alpha = 0.0
121+
122+
act_means = act_means.clamp(min=1e-5)
123+
124+
alphas = torch.linspace(0.0, max_alpha, steps=n_grid)
125+
126+
for alpha_val in alphas:
127+
alpha = float(alpha_val.item())
128+
# Candidate scale s = act_means^alpha
129+
cand_scale = act_means.pow(alpha)
130+
# Normalize scale by geometric mean of min/max to maintain weight scale stability
131+
geom_mean = (cand_scale.max() * cand_scale.min()).sqrt().clamp(min=1e-5)
132+
cand_scale = (cand_scale / geom_mean).clamp(min=1e-4)
133+
134+
# Scale weights: W' = W * diag(s)
135+
# weight: (out, in), cand_scale: (in,) -> broadcast along rows
136+
w_scaled = weight * cand_scale.unsqueeze(0)
137+
138+
# Quantize and dequantize
139+
w_dequant = quant_fn(w_scaled)
140+
141+
# Inverse scale: W_cand = w_dequant * diag(s)^-1
142+
w_cand = w_dequant / cand_scale.unsqueeze(0)
143+
144+
# Output error || y_ref - x @ w_cand.t() ||_F^2
145+
y_cand = calibration_x @ w_cand.t()
146+
err = torch.norm(y_ref - y_cand, p="fro").item()
147+
148+
if err < best_error:
149+
best_error = err
150+
best_scale = cand_scale
151+
best_alpha = alpha
152+
153+
return best_scale, best_alpha
154+
155+
156+
def awq_quantize_weights(
157+
weight: torch.Tensor,
158+
scale: torch.Tensor,
159+
quant_fn: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
160+
) -> Tuple[torch.Tensor, torch.Tensor]:
161+
"""Apply optimal AWQ scale and quantize weight matrix.
162+
163+
Args:
164+
weight: Original weight of shape (out_features, in_features).
165+
scale: Optimal per-channel protection scale of shape (in_features,).
166+
quant_fn: Quantization-dequantization function.
167+
168+
Returns:
169+
Tuple of (dequantized_weight, scale).
170+
"""
171+
if quant_fn is None:
172+
def default_quant(w: torch.Tensor) -> torch.Tensor:
173+
q_b, s_b, zp_b, meta = quantize_blockwise(
174+
w, group_size=min(128, w.shape[1]), num_bits=4
175+
)
176+
return dequantize_blockwise(q_b, s_b, zp_b, meta)
177+
quant_fn = default_quant
178+
179+
w_scaled = weight * scale.unsqueeze(0)
180+
w_dequant = quant_fn(w_scaled)
181+
# Invert scale so layer can be run directly with unscaled input:
182+
# y = x @ (w_dequant / s).t()
183+
w_effective = w_dequant / scale.unsqueeze(0)
184+
return w_effective, scale

0 commit comments

Comments
 (0)