|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +"""NVFP4 fake-quantization primitives. |
| 8 | +
|
| 9 | +Note: these primitives are self-contained, can be moved to torchao if needed. |
| 10 | +
|
| 11 | +A minimal, self-contained implementation of NVFP4 fake quantization applied to a |
| 12 | +model's MoE experts and dense linear layers during training (e.g. for |
| 13 | +quantization-aware distillation or QAT), using a straight-through estimator. |
| 14 | +
|
| 15 | +NVFP4 numerics (two-level block-scale quantization): |
| 16 | +
|
| 17 | +* **Global scale (per tensor):** ``(448 * 6) / amax(x)`` -- 448 is the max |
| 18 | + FP8-E4M3 value, 6 is the max FP4-E2M1 value. |
| 19 | +* **Block scale (per 16 elements):** each block gets its own FP8-E4M3 scale |
| 20 | + ``block_amax / 6``, so precision adapts to local magnitude. |
| 21 | +
|
| 22 | +Every value is rounded to the nearest E2M1 grid point |
| 23 | +(0, 0.5, 1, 1.5, 2, 3, 4, 6) then dequantized. Training uses a straight-through |
| 24 | +estimator (STE): forward returns the dequantized value, backward is identity. |
| 25 | +
|
| 26 | +The single public entry point is :func:`apply_nvfp4_fake_quant`, which |
| 27 | +fake-quantizes BOTH the MoE experts and the dense linear layers (weight + input |
| 28 | +activation) -- the full set of layers an NVFP4 eval quantizes (everything |
| 29 | +except ``lm_head`` / ``router`` / ``gate``). |
| 30 | +""" |
| 31 | + |
| 32 | +import logging |
| 33 | + |
| 34 | +import torch |
| 35 | +import torch.nn as nn |
| 36 | +import torch.nn.functional as F |
| 37 | + |
| 38 | +logger = logging.getLogger(__name__) |
| 39 | + |
| 40 | + |
| 41 | +# Representable positive E2M1 values and the round-to-nearest midpoint |
| 42 | +# boundaries between consecutive values. |
| 43 | +_E2M1_VALUES = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0] |
| 44 | +_E2M1_BOUNDARIES = [0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0] |
| 45 | +_SF_BLOCK_SIZE = 16 |
| 46 | + |
| 47 | +# Module-name substrings the NVFP4 eval does NOT quantize, so QAD skips them too |
| 48 | +# to match the eval scope exactly: the LM head and the MoE router gate. |
| 49 | +_LINEAR_FQ_EXCLUDE = ("lm_head", "router", "gate") |
| 50 | + |
| 51 | + |
| 52 | +def _nvfp4_quant_dequant(x: torch.Tensor) -> torch.Tensor: |
| 53 | + """NVFP4 E2M1 block-scale quantize-dequantize roundtrip. |
| 54 | +
|
| 55 | + For 3D tensors (expert weights) each expert slice is quantized independently |
| 56 | + to avoid OOM from materializing the full tensor in float32. Returns the |
| 57 | + dequantized tensor in the same dtype as *x*. |
| 58 | + """ |
| 59 | + if x.ndim == 3: |
| 60 | + out = torch.empty_like(x) |
| 61 | + for i in range(x.shape[0]): |
| 62 | + out[i] = _nvfp4_quant_dequant(x[i]) |
| 63 | + return out |
| 64 | + |
| 65 | + device = x.device |
| 66 | + orig_dtype = x.dtype |
| 67 | + |
| 68 | + # Level 1: global scale factor maps tensor range into FP8*FP4 range |
| 69 | + gsf = (448 * 6) / x.float().abs().nan_to_num().max() |
| 70 | + x = x.float() * gsf |
| 71 | + |
| 72 | + # Level 2: per-block FP8 scale factor adapts to local magnitudes |
| 73 | + orig_shape = x.shape |
| 74 | + x_flat = x.reshape(-1, _SF_BLOCK_SIZE) |
| 75 | + block_amax = x_flat.abs().amax(dim=-1, keepdim=True) |
| 76 | + block_sf = (block_amax / 6.0).to(torch.float8_e4m3fn).float() |
| 77 | + |
| 78 | + # Round to nearest E2M1 value |
| 79 | + x_norm = x_flat / block_sf.clamp(min=torch.finfo(torch.float8_e4m3fn).tiny) |
| 80 | + sign = x_norm.sign() |
| 81 | + x_abs = x_norm.abs() |
| 82 | + boundaries = torch.tensor(_E2M1_BOUNDARIES, device=device) |
| 83 | + values = torch.tensor(_E2M1_VALUES, device=device) |
| 84 | + indices = torch.bucketize(x_abs, boundaries) |
| 85 | + x_quant = sign * values[indices] |
| 86 | + |
| 87 | + # Dequantize: reverse block scale, reshape, reverse global scale |
| 88 | + x_dq = (x_quant * block_sf).reshape(orig_shape) / gsf |
| 89 | + return x_dq.to(orig_dtype) |
| 90 | + |
| 91 | + |
| 92 | +def _nvfp4_fake_quantize_ste(x: torch.Tensor) -> torch.Tensor: |
| 93 | + """NVFP4 block-scale fake quantize with STE (straight-through estimator). |
| 94 | +
|
| 95 | + Forward returns the dequantized value; backward treats quantization as |
| 96 | + identity. Used for the MoE ``fake_quant_fn`` hook and for linear weights. |
| 97 | + """ |
| 98 | + dq = _nvfp4_quant_dequant(x.detach()) |
| 99 | + return x + (dq - x).detach() |
| 100 | + |
| 101 | + |
| 102 | +def _nvfp4_fake_quantize_act_ste(x: torch.Tensor) -> torch.Tensor: |
| 103 | + """STE NVFP4 fake-quant for a linear layer's INPUT activation of any rank. |
| 104 | +
|
| 105 | + ``_nvfp4_quant_dequant`` treats a 3D tensor as independent per-expert slices |
| 106 | + (looping dim 0), which is wrong for an activation shaped |
| 107 | + ``(batch, seq, features)``. Flatten to 2D ``(tokens, features)`` first so the |
| 108 | + per-tensor global scale spans all tokens and the FP8 block scales tile along |
| 109 | + the feature dim -- matching how the eval quantizes a linear's input -- then |
| 110 | + restore the original shape. STE preserved through the reshape. |
| 111 | + """ |
| 112 | + if x.ndim <= 2: |
| 113 | + return _nvfp4_fake_quantize_ste(x) |
| 114 | + orig_shape = x.shape |
| 115 | + flat = x.reshape(-1, orig_shape[-1]) |
| 116 | + return _nvfp4_fake_quantize_ste(flat).reshape(orig_shape) |
| 117 | + |
| 118 | + |
| 119 | +def _wrap_linear_nvfp4_fake_quant(module: nn.Linear) -> None: |
| 120 | + """Override a linear's forward so its WEIGHT and INPUT ACTIVATION are both |
| 121 | + NVFP4 fake-quantized (STE) before the matmul, matching the NVFP4 eval. |
| 122 | + Instance-level forward override (eager only).""" |
| 123 | + |
| 124 | + def fq_forward(x: torch.Tensor) -> torch.Tensor: |
| 125 | + w = _nvfp4_fake_quantize_ste(module.weight) |
| 126 | + x = _nvfp4_fake_quantize_act_ste(x) |
| 127 | + return F.linear(x, w, module.bias) |
| 128 | + |
| 129 | + module.forward = fq_forward |
| 130 | + module._nvfp4_fake_quant_linear = True |
| 131 | + |
| 132 | + |
| 133 | +def apply_nvfp4_fake_quant(model: nn.Module) -> nn.Module: |
| 134 | + """Enable NVFP4 fake quantization on BOTH the MoE experts AND the dense |
| 135 | + linear layers -- the full set of layers quantized by the NVFP4 eval. |
| 136 | +
|
| 137 | + * **MoE experts:** sets ``fake_quant_fn`` on every ``GroupedExperts`` module |
| 138 | + (identified by having both ``num_experts`` and ``fake_quant_fn``), which |
| 139 | + fake-quantizes the expert weights and activations inside |
| 140 | + ``_experts_forward`` (FSDP2/DTensor-compatible). |
| 141 | + * **Dense linears:** overrides the forward of every ``nn.Linear`` whose name |
| 142 | + does not match :data:`_LINEAR_FQ_EXCLUDE` (``lm_head``/``router``/``gate``) |
| 143 | + so its weight and input activation are fake-quantized. |
| 144 | +
|
| 145 | + Applied in-place; the same model is returned. Eager-only (linear forwards are |
| 146 | + overridden at the instance level). |
| 147 | + """ |
| 148 | + # Apply fake quant to the MoE experts (via the GroupedExperts hook). |
| 149 | + n_moe = 0 |
| 150 | + for module in model.modules(): |
| 151 | + if hasattr(module, "num_experts") and hasattr(module, "fake_quant_fn"): |
| 152 | + module.fake_quant_fn = _nvfp4_fake_quantize_ste |
| 153 | + n_moe += 1 |
| 154 | + |
| 155 | + # Apply fake quant to the dense linear layers (excl lm_head/router/gate). |
| 156 | + n_lin = 0 |
| 157 | + for name, module in model.named_modules(): |
| 158 | + if isinstance(module, nn.Linear) and not any( |
| 159 | + excl in name for excl in _LINEAR_FQ_EXCLUDE |
| 160 | + ): |
| 161 | + _wrap_linear_nvfp4_fake_quant(module) |
| 162 | + n_lin += 1 |
| 163 | + |
| 164 | + logger.info( |
| 165 | + "Applied NVFP4 fake quant to %d GroupedExperts modules and %d linear " |
| 166 | + "layers (excluded lm_head/router/gate)", |
| 167 | + n_moe, |
| 168 | + n_lin, |
| 169 | + ) |
| 170 | + return model |
0 commit comments