diff --git a/DEVLOG.md b/DEVLOG.md index dfe83f2..3ae308b 100644 --- a/DEVLOG.md +++ b/DEVLOG.md @@ -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. + diff --git a/README.md b/README.md index 20a5d83..b384cd7 100644 --- a/README.md +++ b/README.md @@ -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) ``` --- @@ -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. diff --git a/src/quantbench/__init__.py b/src/quantbench/__init__.py index ff626d7..bfa179b 100644 --- a/src/quantbench/__init__.py +++ b/src/quantbench/__init__.py @@ -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 ( @@ -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", ] diff --git a/src/quantbench/quant/__init__.py b/src/quantbench/quant/__init__.py index 33d8620..ecb8834 100644 --- a/src/quantbench/quant/__init__.py +++ b/src/quantbench/quant/__init__.py @@ -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 ( @@ -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", ] diff --git a/src/quantbench/quant/algorithms/__init__.py b/src/quantbench/quant/algorithms/__init__.py new file mode 100644 index 0000000..483cc26 --- /dev/null +++ b/src/quantbench/quant/algorithms/__init__.py @@ -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", +] diff --git a/src/quantbench/quant/algorithms/awq.py b/src/quantbench/quant/algorithms/awq.py new file mode 100644 index 0000000..03d51ab --- /dev/null +++ b/src/quantbench/quant/algorithms/awq.py @@ -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 diff --git a/src/quantbench/quant/algorithms/gptq.py b/src/quantbench/quant/algorithms/gptq.py new file mode 100644 index 0000000..caa6fc9 --- /dev/null +++ b/src/quantbench/quant/algorithms/gptq.py @@ -0,0 +1,181 @@ +# 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. + +"""GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers. + +Mathematical Foundation: + Post-training quantization aims to minimize the layer-wise Frobenius reconstruction error: + argmin_{W_hat} || W * X - W_hat * X ||_F^2 + + Using a second-order Taylor expansion around the continuous weights W, the loss + increase induced by quantizing weights is governed by the input activation Hessian: + H = 2 * X * X^T in R^{d_in x d_in} + + Optimal Brain Surgeon (OBS) establishes that rounding column j to W_hat_{:, j} produces + an error delta w_j = W_{:, j} - W_hat_{:, j}. The optimal linear compensation applied to + the remaining unquantized columns F = {j+1, ..., d_in - 1} is given by: + Delta W_{:, F} = - (W_{:, j} - W_hat_{:, j}) / [H^-1]_{j, j} * [H^-1]_{j, F} + + To prevent numerical divergence from zero/near-zero eigenvalues, the empirical Hessian + is regularized with diagonal damping before inversion: + H_damp = H + lambda * mean(diag(H)) * I (typically lambda = 0.01) + + GPTQ implements a vectorized block-wise update (block size B, e.g. 32 or 128) + converting column-by-column corrections into dense matrix multiplications (GEMM) + while avoiding O(d^3) naive Cholesky recomputations. +""" + +from __future__ import annotations + +from typing import Optional + +import torch + +from quantbench.quant.affine import dequantize_absmax, quantize_absmax +from quantbench.quant.blockwise import dequantize_blockwise, quantize_blockwise + + +def compute_activation_hessian( + calibration_inputs: list[torch.Tensor] | torch.Tensor, + in_features: int, + device: Optional[torch.device] = None, +) -> torch.Tensor: + """Compute empirical input activation Hessian H = 2 * X * X^T across calibration batches. + + Args: + calibration_inputs: Tensor of shape (..., in_features) or list of tensors. + in_features: Number of input features (columns of weight matrix). + device: Torch device for computation. + + Returns: + Tensor of shape (in_features, in_features) representing the accumulated Hessian. + """ + if isinstance(calibration_inputs, torch.Tensor): + calibration_inputs = [calibration_inputs] + + dev = device or calibration_inputs[0].device + H = torch.zeros((in_features, in_features), device=dev, dtype=torch.float32) + n_samples = 0 + + for batch in calibration_inputs: + # Reshape to (N_tokens, in_features) + x = batch.to(dev).float().view(-1, in_features) + # H += 2 * x^T * x + H += 2.0 * (x.t() @ x) + n_samples += x.shape[0] + + if n_samples == 0: + raise ValueError("calibration_inputs contains 0 tokens.") + + # Normalize by total sample count + return H / n_samples + + +def gptq_quantize_weights( + weight: torch.Tensor, + H: torch.Tensor, + bits: int = 4, + group_size: int = 128, + block_size: int = 32, + damping_factor: float = 0.01, +) -> torch.Tensor: + """Quantize weight matrix using GPTQ second-order Hessian error compensation. + + Args: + weight: Float tensor of shape (out_features, in_features). + H: Input Hessian matrix of shape (in_features, in_features). + bits: Target integer bit-width (e.g. 4 or 8). + group_size: Quantization block/group size for scales (-1 for per-channel). + block_size: GPTQ column block update size (e.g. 32). + damping_factor: Diagonal damping regularization factor lambda. + + Returns: + Quantized and dequantized weight tensor in continuous precision with + second-order error compensation applied. + """ + out_features, in_features = weight.shape + device = weight.device + dtype = weight.dtype + + # Work in float32 for numerical stability + W = weight.clone().float() + H = H.clone().float() + + # Damping regularization: H_reg = H + lambda * mean(diag(H)) * I + diag_mean = torch.mean(torch.diag(H)).item() + if diag_mean <= 0.0: + diag_mean = 1.0 + damp = damping_factor * diag_mean + H += damp * torch.eye(in_features, device=device) + + # Invert Hessian via Cholesky decomposition: H = L * L^T -> H^-1 = L^-T * L^-1 + try: + L = torch.linalg.cholesky(H) + L_inv = torch.linalg.inv(L) + H_inv = L_inv.t() @ L_inv + except RuntimeError: + # Fallback to pseudo-inverse if Cholesky fails due to singular sub-blocks + H_inv = torch.linalg.pinv(H) + + # Quantization helper for column vectors / sub-blocks + def quantize_dequantize_cols(col_w: torch.Tensor) -> torch.Tensor: + # col_w: (out_features, num_cols) + if group_size > 0: + q_b, s_b, zp_b, meta = quantize_blockwise( + col_w, group_size=group_size, num_bits=bits + ) + return dequantize_blockwise(q_b, s_b, zp_b, meta) + else: + q, scale = quantize_absmax(col_w, num_bits=bits, dim=0) + return dequantize_absmax(q, scale) + + Q = torch.zeros_like(W) + + # Iterate through column blocks + for col_start in range(0, in_features, block_size): + col_end = min(col_start + block_size, in_features) + count = col_end - col_start + + # Sub-block weights and sub-block Hessian inverse + W_block = W[:, col_start:col_end].clone() + Q_block = torch.zeros_like(W_block) + err_block = torch.zeros_like(W_block) + + H_inv_block = H_inv[col_start:col_end, col_start:col_end] + + # Column-by-column inside the block + for i in range(count): + w_col = W_block[:, i] + d = H_inv_block[i, i] + + # Quantize individual column + q_col = quantize_dequantize_cols(w_col.unsqueeze(1)).squeeze(1) + Q_block[:, i] = q_col + + # OBS column error + err = (w_col - q_col) / d.clamp(min=1e-7) + err_block[:, i] = err + + # Propagate error to remaining columns in the current block + if i + 1 < count: + W_block[:, i + 1 :] -= err.unsqueeze(1) * H_inv_block[i, i + 1 :].unsqueeze(0) + + Q[:, col_start:col_end] = Q_block + + # Propagate block error to all remaining columns outside the block (GEMM) + if col_end < in_features: + # W[:, col_end:] -= err_block @ H_inv[col_start:col_end, col_end:] + W[:, col_end:] -= err_block @ H_inv[col_start:col_end, col_end:] + + return Q.to(dtype=dtype) diff --git a/src/quantbench/quant/algorithms/smoothquant.py b/src/quantbench/quant/algorithms/smoothquant.py new file mode 100644 index 0000000..974d213 --- /dev/null +++ b/src/quantbench/quant/algorithms/smoothquant.py @@ -0,0 +1,132 @@ +# 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. + +"""SmoothQuant: Accurate and Efficient Post-Training Quantization for Large Language Models. + +Mathematical Foundation: + LLM activations exhibit severe outlier channels whose magnitudes can be 100x + larger than typical channels, making activation quantization to INT8 prone to + catastrophic precision loss under per-tensor or per-token absmax scaling. + Conversely, weights exhibit smooth channel distributions and are easy to quantize. + + SmoothQuant introduces a mathematically invariant per-channel migration scale s: + Y = X * W = (X * diag(s)^-1) * (diag(s) * W) = X_hat * W_hat + + The scale vector s in R^C is chosen to balance the maximum dynamic ranges: + s_j = (max(|X_j|)^alpha) / (max(|W_j|)^(1 - alpha)) + + where alpha in [0, 1] controls migration strength: + - alpha = 0.5: Symmetrically divides difficulty between activations and weights. + - alpha = 1.0: Migrates all difficulty to the weights (activations become easy to quantize). + - alpha = 0.0: Preserves weights completely (no difficulty migration). +""" + +from __future__ import annotations + +from typing import Optional, Tuple + +import torch +import torch.nn as nn + + +def compute_smoothquant_scale( + act_max: torch.Tensor, + weight_max: torch.Tensor, + alpha: float = 0.5, + eps: float = 1e-5, +) -> torch.Tensor: + """Compute the per-channel SmoothQuant migration scale vector. + + Args: + act_max: Tensor of shape (C,) representing the maximum absolute activation + magnitude per input channel across calibration tokens. + weight_max: Tensor of shape (C,) representing the maximum absolute weight + magnitude per input channel: max_i |W_{i, j}|. + alpha: Migration strength hyperparameter in [0.0, 1.0]. + eps: Small epsilon to prevent division by zero or degenerate scales. + + Returns: + Tensor of shape (C,) containing per-channel migration scales s_j. + """ + if not (0.0 <= alpha <= 1.0): + raise ValueError(f"alpha must be in [0.0, 1.0], got {alpha}") + + act_max = act_max.clamp(min=eps) + weight_max = weight_max.clamp(min=eps) + + # s_j = (s_X^alpha) / (s_W^(1 - alpha)) + numerator = act_max.pow(alpha) + denominator = weight_max.pow(1.0 - alpha) + scale = (numerator / denominator).clamp(min=eps) + return scale + + +def extract_activation_channel_scales( + module: nn.Module, + calibration_inputs: list[torch.Tensor] | torch.Tensor, +) -> torch.Tensor: + """Profile activation outlier channel scales across calibration data. + + Args: + module: Neural network module (e.g. nn.Linear). + calibration_inputs: A tensor or list of tensors of shape (B, S, C_in) or (N, C_in). + + Returns: + Tensor of shape (C_in,) containing per-channel max absolute activation values. + """ + if isinstance(calibration_inputs, torch.Tensor): + calibration_inputs = [calibration_inputs] + + channel_max: Optional[torch.Tensor] = None + + for batch in calibration_inputs: + # Reshape to (N_tokens, C_in) + flat = batch.detach().view(-1, batch.shape[-1]).abs() + batch_max = flat.max(dim=0).values + if channel_max is None: + channel_max = batch_max + else: + channel_max = torch.maximum(channel_max, batch_max) + + if channel_max is None: + raise ValueError("calibration_inputs cannot be empty.") + + return channel_max + + +def smooth_linear_weights( + weight: torch.Tensor, + act_scales: torch.Tensor, + alpha: float = 0.5, +) -> Tuple[torch.Tensor, torch.Tensor]: + """Apply SmoothQuant per-channel migration to weight tensor. + + Args: + weight: Float tensor of shape (out_features, in_features). + act_scales: Per-channel activation max tensor of shape (in_features,). + alpha: Migration factor in [0.0, 1.0]. + + Returns: + Tuple of (smoothed_weight, migration_scale): + - smoothed_weight: W * diag(s) of shape (out_features, in_features). + - migration_scale: s of shape (in_features,). + """ + # W shape: (out_features, in_features) + # Channel max across output rows: max_i |W_{i, j}| -> shape (in_features,) + weight_max = weight.abs().max(dim=0).values + scale = compute_smoothquant_scale(act_scales, weight_max, alpha=alpha) + + # W_hat = W * diag(s) -> broadcasting along dim 1 + smoothed_weight = weight * scale.unsqueeze(0) + return smoothed_weight, scale diff --git a/tests/test_algorithms.py b/tests/test_algorithms.py new file mode 100644 index 0000000..a4ec819 --- /dev/null +++ b/tests/test_algorithms.py @@ -0,0 +1,209 @@ +# 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. + +"""Comprehensive test suite for advanced calibration algorithms (SmoothQuant, AWQ, GPTQ).""" + +from __future__ import annotations + +import pytest +import torch +import torch.nn as nn + +from quantbench.quant.affine import dequantize_absmax, quantize_absmax +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, +) + + +class TestSmoothQuant: + """Mathematical verification and invariant tests for SmoothQuant.""" + + def test_outlier_extraction_and_scale_computation(self) -> None: + torch.manual_seed(42) + # 100 tokens, 16 features + x = torch.randn(100, 16) + # Create an intentional outlier at channel 5 + x[:, 5] *= 80.0 + + act_max = extract_activation_channel_scales(nn.Identity(), x) + assert act_max.shape == (16,) + assert act_max[5] > 70.0 + assert act_max[0] < 10.0 + + weight = torch.randn(32, 16) + w_max = weight.abs().max(dim=0).values + + # Test alpha=0.5 (balanced) + scale = compute_smoothquant_scale(act_max, w_max, alpha=0.5) + assert scale.shape == (16,) + # Channel 5 should have higher scale to migrate activation difficulty to weight + assert scale[5] > scale[0] + + def test_mathematical_continuous_invariance(self) -> None: + """Verify that before discrete rounding, (X * s^-1) @ (W * s)^T == X @ W^T.""" + torch.manual_seed(123) + b, s, c_in, c_out = 2, 8, 32, 64 + x = torch.randn(b, s, c_in) * 2.0 + x[:, :, 3] *= 50.0 # outlier channel + w = torch.randn(c_out, c_in) + + act_scales = extract_activation_channel_scales(nn.Identity(), x) + w_smoothed, scale = smooth_linear_weights(w, act_scales, alpha=0.5) + + # Scale activation: X_hat = X * diag(s)^-1 + x_smoothed = x / scale.unsqueeze(0).unsqueeze(0) + + # Reference output: X @ W^T + y_ref = x @ w.t() + # Smoothed output: X_hat @ W_hat^T + y_smooth = x_smoothed @ w_smoothed.t() + + # In continuous precision, the outputs must be mathematically identical + torch.testing.assert_close(y_smooth, y_ref, rtol=1e-4, atol=1e-4) + + def test_alpha_boundaries(self) -> None: + act = torch.tensor([10.0, 1.0]) + w = torch.tensor([1.0, 10.0]) + + # alpha = 0.0 -> s = 1.0 / w + s_0 = compute_smoothquant_scale(act, w, alpha=0.0) + torch.testing.assert_close(s_0, 1.0 / w) + + # alpha = 1.0 -> s = act + s_1 = compute_smoothquant_scale(act, w, alpha=1.0) + torch.testing.assert_close(s_1, act) + + with pytest.raises(ValueError, match="alpha must be in"): + compute_smoothquant_scale(act, w, alpha=1.5) + + +class TestAWQ: + """Verification for Activation-aware Weight Quantization.""" + + def test_activation_means_and_shape(self) -> None: + x1 = torch.ones(10, 8) * 2.0 + x2 = torch.ones(10, 8) * 4.0 + means = compute_activation_channel_means([x1, x2]) + assert means.shape == (8,) + torch.testing.assert_close(means, torch.ones(8) * 3.0) + + def test_awq_reconstruction_error_reduction(self) -> None: + """Verify that AWQ search produces equal or lower output MSE than unscaled quantization.""" + torch.manual_seed(99) + c_in, c_out = 64, 32 + n_samples = 128 + + # Create activation distribution with sharp salient channels + x = torch.randn(n_samples, c_in) + x[:, 4] *= 25.0 + x[:, 12] *= 30.0 + + w = torch.randn(c_out, c_in) * 0.1 + + act_means = compute_activation_channel_means(x) + + # Base uniform quantization (alpha = 0.0) + q_naive, scale_naive = quantize_absmax(w, num_bits=4, dim=1) + w_naive = dequantize_absmax(q_naive, scale_naive) + err_naive = torch.norm((x @ w.t()) - (x @ w_naive.t()), p="fro").item() + + # AWQ grid search + best_scale, best_alpha = search_best_awq_scale( + w, + act_means, + calibration_x=x, + n_grid=10, + ) + assert best_scale.shape == (c_in,) + assert 0.0 <= best_alpha <= 1.0 + + w_awq, _ = awq_quantize_weights(w, best_scale) + err_awq = torch.norm((x @ w.t()) - (x @ w_awq.t()), p="fro").item() + + # AWQ should achieve competitive or lower reconstruction error on calibration data + assert err_awq <= err_naive * 1.05 + + +class TestGPTQ: + """Mathematical verification and second-order Hessian error compensation tests.""" + + def test_hessian_properties(self) -> None: + torch.manual_seed(77) + in_dim = 16 + x = torch.randn(50, in_dim) + + H = compute_activation_hessian(x, in_features=in_dim) + assert H.shape == (in_dim, in_dim) + + # Hessian must be symmetric: H == H^T + torch.testing.assert_close(H, H.t(), atol=1e-5, rtol=1e-5) + + # Eigenvalues must be non-negative (positive semi-definite) + eigvals = torch.linalg.eigvalsh(H) + assert (eigvals >= -1e-5).all() + + def test_gptq_quantize_weights_error_reduction(self) -> None: + """Verify that GPTQ second-order compensation improves output reconstruction.""" + torch.manual_seed(42) + in_dim, out_dim = 64, 32 + n_tokens = 256 + + x = torch.randn(n_tokens, in_dim) + w = torch.randn(out_dim, in_dim) * 0.2 + + H = compute_activation_hessian(x, in_features=in_dim) + + # Naive INT4 quantization without OBS compensation + q_naive, scale_naive = quantize_absmax(w, num_bits=4, dim=1) + w_naive = dequantize_absmax(q_naive, scale_naive) + err_naive = torch.norm((x @ w.t()) - (x @ w_naive.t()), p="fro").item() + + # GPTQ quantization with Hessian compensation + w_gptq = gptq_quantize_weights( + w, + H=H, + bits=4, + group_size=32, + block_size=16, + damping_factor=0.01, + ) + assert w_gptq.shape == w.shape + err_gptq = torch.norm((x @ w.t()) - (x @ w_gptq.t()), p="fro").item() + + # GPTQ compensation must produce lower error than naive rounding + assert err_gptq < err_naive + + def test_gptq_non_divisible_block_size(self) -> None: + """Verify robust behavior when in_features is not evenly divisible by block_size.""" + torch.manual_seed(10) + in_dim, out_dim = 25, 15 + x = torch.randn(40, in_dim) + w = torch.randn(out_dim, in_dim) + + H = compute_activation_hessian(x, in_features=in_dim) + # block_size = 8 (25 is not divisible by 8) + w_gptq = gptq_quantize_weights(w, H, bits=4, group_size=-1, block_size=8) + assert w_gptq.shape == (out_dim, in_dim) + assert not torch.isnan(w_gptq).any()