Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions DEVLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,17 @@
- In-place recursive model converter traversing PyTorch module trees.
- 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`).
- Reports layer conversion counts, memory reduction statistics, and elapsed conversion duration.
- Added comprehensive unit tests in `tests/test_quant_linear.py`:
- 31/31 unit tests passing across entire repo with 93% coverage in 2.27s. All Ruff checks passing.
## 2026-10-26: Phase 4 — Advanced Calibration Algorithms (SmoothQuant, AWQ, GPTQ)

- Created `quantbench.quant.algorithms`:
- `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.
- `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$.
- `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:}$).
- Added comprehensive unit tests in `tests/test_algorithms.py`:
- Outlier profiling and continuous mathematical invariance testing.
- AWQ reconstruction error reduction testing on synthetic salient channels.
- Hessian symmetry, positive semi-definiteness, and GPTQ OBS error reduction testing.
- 39/39 unit tests passing with 93% test coverage across the repository. All Ruff checks passing.



24 changes: 23 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,28 @@ converted_model, stats = convert_model_to_quant(
exclude_modules=["lm_head"],
)
print(f"Compressed {stats['converted_layers']} layers: {stats['orig_memory_mb']} MB -> {stats['quant_memory_mb']} MB ({stats['compression_ratio']}x)")

# 3. Advanced Calibration Algorithms (SmoothQuant, AWQ, GPTQ)
from quantbench import (
smooth_linear_weights,
extract_activation_channel_scales,
search_best_awq_scale,
compute_activation_channel_means,
gptq_quantize_weights,
compute_activation_hessian,
)

# SmoothQuant: Migrate activation outlier dynamic range to weights
act_scales = extract_activation_channel_scales(linear, calibration_x)
w_smoothed, scale = smooth_linear_weights(linear.weight, act_scales, alpha=0.5)

# AWQ: Search optimal per-channel protection scales
act_means = compute_activation_channel_means(calibration_x)
best_scale, best_alpha = search_best_awq_scale(linear.weight, act_means, calibration_x)

# GPTQ: Second-order Hessian error compensation
H = compute_activation_hessian(calibration_x, in_features=4096)
w_gptq = gptq_quantize_weights(linear.weight, H, bits=4, group_size=128)
```

---
Expand All @@ -128,7 +150,7 @@ print(f"Compressed {stats['converted_layers']} layers: {stats['orig_memory_mb']}
- [x] **Phase 1: Mathematical Primitives & Invariants**: Affine, AbsMax, Group-wise, and FP8 (E4M3/E5M2) simulation with rigorous error bound verification.
- [x] **Phase 2: Integer Bit-Packing Runtimes**: Vectorized INT4 nibble packing (`uint8`), BitNet ternary packing, and 2:4 sparsity metadata.
- [x] **Phase 3: Drop-in Neural Layers**: `QuantLinear` PyTorch module, in-place Hugging Face model converter, and buffer serialization.
- [ ] **Phase 4: Advanced Optimization Algorithms**: SmoothQuant outlier migration, AWQ grid search, and GPTQ second-order Hessian updates.
- [x] **Phase 4: Advanced Calibration Algorithms**: SmoothQuant outlier migration, AWQ grid search, and GPTQ second-order Hessian updates.
- [ ] **Phase 5: Perplexity & Evaluation Engine**: Standardized sliding-window perplexity on WikiText-2 and C4.
- [ ] **Phase 6: servebench Bridge & Pareto Visualizer**: Empirical throughput (tok/s) profiling and terminal ASCII Pareto curves.
- [ ] **Phase 7: Public Learning Guide & Packaging**: Comprehensive educational walkthrough and PyPI release.
Expand Down
18 changes: 18 additions & 0 deletions src/quantbench/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@
quantize_absmax,
quantize_affine,
)
from quantbench.quant.algorithms import (
awq_quantize_weights,
compute_activation_channel_means,
compute_activation_hessian,
compute_smoothquant_scale,
extract_activation_channel_scales,
gptq_quantize_weights,
search_best_awq_scale,
smooth_linear_weights,
)
from quantbench.quant.blockwise import dequantize_blockwise, quantize_blockwise
from quantbench.quant.fp8 import FP8Format, dequantize_fp8, quantize_fp8
from quantbench.quant.packing import (
Expand Down Expand Up @@ -44,4 +54,12 @@
"unpack_2_4_indices",
"prune_and_compress_2_4",
"decompress_2_4",
"compute_smoothquant_scale",
"extract_activation_channel_scales",
"smooth_linear_weights",
"compute_activation_channel_means",
"search_best_awq_scale",
"awq_quantize_weights",
"compute_activation_hessian",
"gptq_quantize_weights",
]
18 changes: 18 additions & 0 deletions src/quantbench/quant/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,16 @@
quantize_absmax,
quantize_affine,
)
from quantbench.quant.algorithms import (
awq_quantize_weights,
compute_activation_channel_means,
compute_activation_hessian,
compute_smoothquant_scale,
extract_activation_channel_scales,
gptq_quantize_weights,
search_best_awq_scale,
smooth_linear_weights,
)
from quantbench.quant.blockwise import dequantize_blockwise, quantize_blockwise
from quantbench.quant.fp8 import FP8Format, dequantize_fp8, quantize_fp8
from quantbench.quant.packing import (
Expand Down Expand Up @@ -37,4 +47,12 @@
"unpack_2_4_indices",
"prune_and_compress_2_4",
"decompress_2_4",
"compute_smoothquant_scale",
"extract_activation_channel_scales",
"smooth_linear_weights",
"compute_activation_channel_means",
"search_best_awq_scale",
"awq_quantize_weights",
"compute_activation_hessian",
"gptq_quantize_weights",
]
41 changes: 41 additions & 0 deletions src/quantbench/quant/algorithms/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Copyright 2026 Prajwal7-2002
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Advanced calibration algorithms for post-training quantization."""

from quantbench.quant.algorithms.awq import (
awq_quantize_weights,
compute_activation_channel_means,
search_best_awq_scale,
)
from quantbench.quant.algorithms.gptq import (
compute_activation_hessian,
gptq_quantize_weights,
)
from quantbench.quant.algorithms.smoothquant import (
compute_smoothquant_scale,
extract_activation_channel_scales,
smooth_linear_weights,
)

__all__ = [
"compute_smoothquant_scale",
"extract_activation_channel_scales",
"smooth_linear_weights",
"compute_activation_channel_means",
"search_best_awq_scale",
"awq_quantize_weights",
"compute_activation_hessian",
"gptq_quantize_weights",
]
184 changes: 184 additions & 0 deletions src/quantbench/quant/algorithms/awq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
# Copyright 2026 Prajwal7-2002
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration.

Mathematical Foundation:
Not all weights in a neural network are equally critical to perplexity.
AWQ discovers that protecting the top ~1% of salient weights avoids perplexity
degradation even at aggressive INT4/INT3 regimes. Crucially, salient weights
directly correspond to channels that process activations with high magnitudes:
s_X = (1 / N) * sum(|X|) (mean absolute activation per input channel)

Instead of maintaining mixed-precision floating-point formats (which incur runtime
overhead and degrade hardware SIMD execution efficiency), AWQ applies a per-channel
protection scale s:
W' = W * diag(s)
X' = diag(s)^-1 * X

When W' is quantized to sub-byte integers (e.g. INT4 blockwise), the relative quantization
error on salient channels is inversely proportional to s_j:
Delta W_j / W_j ~ 1 / s_j

AWQ searches for the optimal per-channel scale s_j = (s_{X, j})^alpha over a grid of
alpha in [0.0, 1.0] by directly minimizing the Frobenius output reconstruction error:
min_alpha || W * X - [Quantize(W * diag(s)) * diag(s)^-1] * X ||_F^2
"""

from __future__ import annotations

from typing import Callable, Optional, Tuple

import torch

from quantbench.quant.blockwise import dequantize_blockwise, quantize_blockwise


def compute_activation_channel_means(
calibration_inputs: list[torch.Tensor] | torch.Tensor,
) -> torch.Tensor:
"""Calculate mean absolute activation magnitude per input channel.

Args:
calibration_inputs: Tensor of shape (..., in_features) or list of tensors.

Returns:
Tensor of shape (in_features,) containing per-channel mean absolute activation.
"""
if isinstance(calibration_inputs, torch.Tensor):
calibration_inputs = [calibration_inputs]

total_sum: Optional[torch.Tensor] = None
total_tokens = 0

for batch in calibration_inputs:
flat = batch.detach().view(-1, batch.shape[-1]).abs()
batch_sum = flat.sum(dim=0)
n_tokens = flat.shape[0]

if total_sum is None:
total_sum = batch_sum
else:
total_sum = total_sum + batch_sum
total_tokens += n_tokens

if total_sum is None or total_tokens == 0:
raise ValueError("calibration_inputs cannot be empty.")

return total_sum / total_tokens


def search_best_awq_scale(
weight: torch.Tensor,
act_means: torch.Tensor,
calibration_x: torch.Tensor,
quant_fn: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
n_grid: int = 20,
max_alpha: float = 1.0,
) -> Tuple[torch.Tensor, float]:
"""Perform grid search for optimal AWQ protection scale alpha.

Args:
weight: Float tensor of shape (out_features, in_features).
act_means: Channel-wise activation mean of shape (in_features,).
calibration_x: Sample calibration activations of shape (N_samples, in_features).
quant_fn: Quantize-and-dequantize callable. Defaults to INT4 blockwise (group_size=128).
n_grid: Number of search points in alpha grid [0, max_alpha].
max_alpha: Maximum alpha value for search.

Returns:
Tuple of (optimal_scale_vector, best_alpha):
- optimal_scale_vector: Per-channel scale s in R^{in_features}.
- best_alpha: Optimal alpha hyperparameter.
"""
if quant_fn is None:
def default_quant(w: torch.Tensor) -> torch.Tensor:
q_b, s_b, zp_b, meta = quantize_blockwise(
w, group_size=min(128, w.shape[1]), num_bits=4
)
return dequantize_blockwise(q_b, s_b, zp_b, meta)
quant_fn = default_quant

# Reference unquantized linear output
# calibration_x: (N, in_features), weight: (out_features, in_features)
# y_ref: (N, out_features)
y_ref = calibration_x @ weight.t()

best_error = float("inf")
best_scale = torch.ones(weight.shape[1], device=weight.device, dtype=weight.dtype)
best_alpha = 0.0

act_means = act_means.clamp(min=1e-5)

alphas = torch.linspace(0.0, max_alpha, steps=n_grid)

for alpha_val in alphas:
alpha = float(alpha_val.item())
# Candidate scale s = act_means^alpha
cand_scale = act_means.pow(alpha)
# Normalize scale by geometric mean of min/max to maintain weight scale stability
geom_mean = (cand_scale.max() * cand_scale.min()).sqrt().clamp(min=1e-5)
cand_scale = (cand_scale / geom_mean).clamp(min=1e-4)

# Scale weights: W' = W * diag(s)
# weight: (out, in), cand_scale: (in,) -> broadcast along rows
w_scaled = weight * cand_scale.unsqueeze(0)

# Quantize and dequantize
w_dequant = quant_fn(w_scaled)

# Inverse scale: W_cand = w_dequant * diag(s)^-1
w_cand = w_dequant / cand_scale.unsqueeze(0)

# Output error || y_ref - x @ w_cand.t() ||_F^2
y_cand = calibration_x @ w_cand.t()
err = torch.norm(y_ref - y_cand, p="fro").item()

if err < best_error:
best_error = err
best_scale = cand_scale
best_alpha = alpha

return best_scale, best_alpha


def awq_quantize_weights(
weight: torch.Tensor,
scale: torch.Tensor,
quant_fn: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Apply optimal AWQ scale and quantize weight matrix.

Args:
weight: Original weight of shape (out_features, in_features).
scale: Optimal per-channel protection scale of shape (in_features,).
quant_fn: Quantization-dequantization function.

Returns:
Tuple of (dequantized_weight, scale).
"""
if quant_fn is None:
def default_quant(w: torch.Tensor) -> torch.Tensor:
q_b, s_b, zp_b, meta = quantize_blockwise(
w, group_size=min(128, w.shape[1]), num_bits=4
)
return dequantize_blockwise(q_b, s_b, zp_b, meta)
quant_fn = default_quant

w_scaled = weight * scale.unsqueeze(0)
w_dequant = quant_fn(w_scaled)
# Invert scale so layer can be run directly with unscaled input:
# y = x @ (w_dequant / s).t()
w_effective = w_dequant / scale.unsqueeze(0)
return w_effective, scale
Loading
Loading