|
| 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