已合并
[feat]add dsv4 kv cache fake-quantization support #881
caoshuyang创建于 9月20日
[feat]add dsv4 kv cache fake-quantization support #881
已合并
共 9 个文件变更+444-25
| @@ -33,6 +33,9 @@ QUANTIZATION_ARGS=( | |||
| 33 | --extension.quantization.recipe all_block_fp8 | 33 | --extension.quantization.recipe all_block_fp8 |
| 34 | --extension.quantization.fsdp-prequantize | 34 | --extension.quantization.fsdp-prequantize |
| 35 | --extension.quantization.li-quantization fp8 | 35 | --extension.quantization.li-quantization fp8 |
| 36 | + --extension.quantization.kv-norm-quantization.format mxfp8 | ||
| 37 | + --extension.quantization.kv-norm-quantization.fqns .attention.kv_norm,.attention.compressor.norm | ||
| 38 | + --extension.quantization.kv-norm-quantization.block-size 64 | ||
| 36 | ) | 39 | ) |
| 37 | 40 | ||
| 38 | # Disable swap optimizer for better performance | 41 | # Disable swap optimizer for better performance |
| @@ -41,6 +41,9 @@ QUANTIZATION_ARGS=( | |||
| 41 | --extension.quantization.recipe all_block_fp8 | 41 | --extension.quantization.recipe all_block_fp8 |
| 42 | --extension.quantization.fsdp-prequantize | 42 | --extension.quantization.fsdp-prequantize |
| 43 | --extension.quantization.li-quantization fp8 | 43 | --extension.quantization.li-quantization fp8 |
| 44 | + --extension.quantization.kv-norm-quantization.format mxfp8 | ||
| 45 | + --extension.quantization.kv-norm-quantization.fqns .attention.kv_norm,.attention.compressor.norm | ||
| 46 | + --extension.quantization.kv-norm-quantization.block-size 64 | ||
| 44 | ) | 47 | ) |
| 45 | 48 | ||
| 46 | # Disable swap optimizer for better performance | 49 | # Disable swap optimizer for better performance |
| @@ -403,3 +403,68 @@ def test_mx_fake_quantize_matches_quantize_then_dequantize_for_all_layouts(tenso | |||
| 403 | # Idempotency: quantize -> dequantize -> quantize -> dequantize is a no-op. | 403 | # Idempotency: quantize -> dequantize -> quantize -> dequantize is a no-op. |
| 404 | y2 = mx_fake_quantize(y, axis, config) | 404 | y2 = mx_fake_quantize(y, axis, config) |
| 405 | assert torch.equal(y, y2), "fake quantization is not idempotent" | 405 | assert torch.equal(y, y2), "fake quantization is not idempotent" |
| 406 | + | ||
| 407 | + | ||
| 408 | +@pytest.mark.parametrize("block_size", [32, 64, 96, 128]) | ||
| 409 | +@pytest.mark.parametrize("elem_dtype", [torch.float8_e4m3fn, torch.float8_e5m2, torch.float4_e2m1fn_x2]) | ||
| 410 | +def test_mx_fake_quantize_is_idempotent(elem_dtype, block_size): | ||
| 411 | + """Fake quantizing an already fake-quantized tensor reproduces it exactly. | ||
| 412 | + | ||
| 413 | + Reference-free by design: ``mxfp8_dequantize``/``mxfp4_dequantize`` only | ||
| 414 | + implement ``block_size=32``, so above 32 the round trip is checked against | ||
| 415 | + itself. ``scale_alg=0`` is the only algorithm that supports both FP4 and FP8 | ||
| 416 | + together with a ``block_size`` other than 32. | ||
| 417 | + """ | ||
| 418 | + from torchao_npu.quantization.quant_primitives.mx import mx_fake_quantize | ||
| 419 | + | ||
| 420 | + config = MXQuantizeConfig(elem_dtype=elem_dtype, block_size=block_size, scale_alg=0) | ||
| 421 | + x = torch.randn(4, 384, device="npu", dtype=torch.bfloat16) | ||
| 422 | + | ||
| 423 | + y = mx_fake_quantize(x, -1, config) | ||
| 424 | + y2 = mx_fake_quantize(y, -1, config) | ||
| 425 | + | ||
| 426 | + assert y.shape == x.shape, f"shape mismatch: {y.shape} vs {x.shape}" | ||
| 427 | + assert y.dtype == x.dtype, f"dtype mismatch: {y.dtype} vs {x.dtype}" | ||
| 428 | + assert not torch.equal(y, x), "the round trip must actually change values" | ||
| 429 | + assert torch.equal(y, y2), "fake quantization is not idempotent" | ||
| 430 | + | ||
| 431 | + | ||
| 432 | +def test_mx_fake_quantize_is_straight_through_differentiable(): | ||
| 433 | + """The fake-quantized span keeps identity gradients instead of detaching.""" | ||
| 434 | + from torchao_npu.quantization.quant_primitives.mx import mx_fake_quantize | ||
| 435 | + | ||
| 436 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 437 | + weight = torch.randn(4, 64, device="npu", dtype=torch.bfloat16) | ||
| 438 | + x = torch.randn(4, 64, device="npu", dtype=torch.bfloat16, requires_grad=True) | ||
| 439 | + | ||
| 440 | + y = mx_fake_quantize(x, -1, config) | ||
| 441 | + | ||
| 442 | + assert y.dtype == x.dtype | ||
| 443 | + assert not torch.equal(y, x), "the round trip must actually change values" | ||
| 444 | + | ||
| 445 | + (y * weight).sum().backward() | ||
| 446 | + | ||
| 447 | + # Identity through the quantized span: the gradient is the (unquantized) weight. | ||
| 448 | + assert x.grad is not None, "the fake-quantized span must not detach the graph" | ||
| 449 | + assert torch.equal(x.grad, weight) | ||
| 450 | + | ||
| 451 | + | ||
| 452 | +def test_mx_last_dim_fake_quantize_custom_op_passes_opcheck(): | ||
| 453 | + """Schema, mutation contract, autograd formula and fake metadata of the op.""" | ||
| 454 | + import torch.library | ||
| 455 | + from torchao_npu.quantization.quant_primitives.mx import mx_last_dim_fake_quantize | ||
| 456 | + | ||
| 457 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 458 | + x = torch.randn(4, 64, device="npu", dtype=torch.bfloat16) | ||
| 459 | + | ||
| 460 | + torch.library.opcheck( | ||
| 461 | + mx_last_dim_fake_quantize, | ||
| 462 | + ( | ||
| 463 | + x, | ||
| 464 | + config.npu_elem_dtype, | ||
| 465 | + config.block_size, | ||
| 466 | + config.round_mode, | ||
| 467 | + config.scale_alg, | ||
| 468 | + config.dst_type_max, | ||
| 469 | + ), | ||
| 470 | + ) | ||
| @@ -34,9 +34,19 @@ def test_mx_config_fp4_scale_alg_constraints(): | |||
| 34 | MXQuantizeConfig(elem_dtype=torch.float4_e2m1fn_x2, scale_alg=1) | 34 | MXQuantizeConfig(elem_dtype=torch.float4_e2m1fn_x2, scale_alg=1) |
| 35 | 35 | ||
| 36 | 36 | ||
| 37 | +def test_mx_config_accepts_positive_multiples_of_32(): | ||
| 38 | + """Any positive multiple of 32 is a valid MX block size.""" | ||
| 39 | + assert MXQuantizeConfig(block_size=32).block_size == 32 | ||
| 40 | + assert MXQuantizeConfig(block_size=64).block_size == 64 | ||
| 41 | + | ||
| 42 | + | ||
| 37 | def test_mx_config_rejects_unsupported_block_size_and_dtype(): | 43 | def test_mx_config_rejects_unsupported_block_size_and_dtype(): |
| 38 | - with pytest.raises(AssertionError, match="block_size must be 32"): | 44 | + with pytest.raises(AssertionError, match="positive multiple of 32"): |
| 39 | MXQuantizeConfig(block_size=16) | 45 | MXQuantizeConfig(block_size=16) |
| 46 | + with pytest.raises(AssertionError, match="positive multiple of 32"): | ||
| 47 | + MXQuantizeConfig(block_size=0) | ||
| 48 | + with pytest.raises(AssertionError, match="positive multiple of 32"): | ||
| 49 | + MXQuantizeConfig(block_size=-32) | ||
| 40 | with pytest.raises(AssertionError, match="elem_dtype must be one of"): | 50 | with pytest.raises(AssertionError, match="elem_dtype must be one of"): |
| 41 | MXQuantizeConfig(elem_dtype=torch.float32) | 51 | MXQuantizeConfig(elem_dtype=torch.float32) |
| 42 | 52 | ||
| @@ -74,7 +84,7 @@ def test_mx_config_npu_dtype_properties(elem_dtype, expected_elem_token, expecte | |||
| 74 | @pytest.mark.parametrize( | 84 | @pytest.mark.parametrize( |
| 75 | "kwargs, message", | 85 | "kwargs, message", |
| 76 | [ | 86 | [ |
| 77 | - ({"block_size": 16}, "block_size must be 32"), | 87 | + ({"block_size": 16}, "positive multiple of 32"), |
| 78 | ({"elem_dtype": torch.float32}, "elem_dtype must be"), | 88 | ({"elem_dtype": torch.float32}, "elem_dtype must be"), |
| 79 | ( | 89 | ( |
| 80 | { | 90 | { |
| @@ -70,7 +70,9 @@ class MXQuantizeConfig(FakeQuantizeConfigBase): | |||
| 70 | return _NPU_DTYPE_DICT[self.scale_dtype] | 70 | return _NPU_DTYPE_DICT[self.scale_dtype] |
| 71 | 71 | ||
| 72 | def __post_init__(self): | 72 | def __post_init__(self): |
| 73 | - assert self.block_size == 32, f"For MX formats, the block_size must be 32, block_size={self.block_size} passed." | 73 | + assert self.block_size > 0 and self.block_size % 32 == 0, ( |
| 74 | + f"For MX formats, the block_size must be a positive multiple of 32, block_size={self.block_size} passed." | ||
| 75 | + ) | ||
| 74 | 76 | ||
| 75 | assert self.elem_dtype in _SUPPORTED_MX_ELEM_DTYPES, ( | 77 | assert self.elem_dtype in _SUPPORTED_MX_ELEM_DTYPES, ( |
| 76 | f"elem_dtype must be one of {_SUPPORTED_MX_ELEM_DTYPES}, got {self.elem_dtype}" | 78 | f"elem_dtype must be one of {_SUPPORTED_MX_ELEM_DTYPES}, got {self.elem_dtype}" |
| @@ -5,12 +5,13 @@ | |||
| 5 | 5 | ||
| 6 | """MXFP4 low-level primitives for NPU. | 6 | """MXFP4 low-level primitives for NPU. |
| 7 | 7 | ||
| 8 | -These are pure tensor helpers (no autograd, no matmul) used by higher-level | 8 | +These are pure tensor helpers (no matmul) used by higher-level ops in |
| 9 | -ops in :mod:`torchao_npu.ops.mx_ops` | 9 | +:mod:`torchao_npu.ops.mx_ops` |
| 10 | (e.g., ``MXFP4FakeQuantize.forward`` calls :func:`mxfp4_dequantize`). | 10 | (e.g., ``MXFP4FakeQuantize.forward`` calls :func:`mxfp4_dequantize`). |
| 11 | """ | 11 | """ |
| 12 | 12 | ||
| 13 | import functools | 13 | import functools |
| 14 | +from math import ceil | ||
| 14 | 15 | ||
| 15 | import torch | 16 | import torch |
| 16 | import torch_npu | 17 | import torch_npu |
| @@ -125,12 +126,85 @@ def mx_quantize( | |||
| 125 | return y, scale | 126 | return y, scale |
| 126 | 127 | ||
| 127 | 128 | ||
| 129 | +@torch.library.custom_op("torchao_npu::mx_last_dim_fake_quantize", mutates_args=(), device_types="npu") | ||
| 130 | +def mx_last_dim_fake_quantize( | ||
| 131 | + x: torch.Tensor, | ||
| 132 | + quant_elem_dtype: int, | ||
| 133 | + block_size: int, | ||
| 134 | + round_mode: str, | ||
| 135 | + scale_alg: int, | ||
| 136 | + quant_elem_dtype_max: float, | ||
| 137 | +) -> torch.Tensor: | ||
| 138 | + """Quantize then immediately dequantize ``x`` along its trailing dimension. | ||
| 139 | + | ||
| 140 | + the result is differentiable via a straight-through estimator. | ||
| 141 | + | ||
| 142 | + Args: | ||
| 143 | + x: Tensor to fake-quantize. | ||
| 144 | + quant_elem_dtype: Element dtype of the quantized tensor, in the encoding | ||
| 145 | + ``npu_dynamic_mx_quant`` expects; ``npu_anti_mx_quant`` decodes the same | ||
| 146 | + dtype. | ||
| 147 | + block_size: MX block size for both ops. | ||
| 148 | + round_mode: Cast mode of the quantizer. | ||
| 149 | + scale_alg: Scale algorithm of the quantizer. | ||
| 150 | + quant_elem_dtype_max: Maximum of the target dtype; ``0.0`` infers it. | ||
| 151 | + | ||
| 152 | + Returns: | ||
| 153 | + The fake-quantized tensor: fresh, contiguous, with ``x``'s shape and dtype. | ||
| 154 | + | ||
| 155 | + Raises: | ||
| 156 | + AssertionError: If the dequantized values are not contiguous, which the NPU | ||
| 157 | + kernels otherwise guarantee. | ||
| 158 | + """ | ||
| 159 | + qdata, scale = torch_npu.npu_dynamic_mx_quant( | ||
| 160 | + x, | ||
| 161 | + axis=-1, | ||
| 162 | + dst_type=quant_elem_dtype, | ||
| 163 | + block_size=block_size, | ||
| 164 | + round_mode=round_mode, | ||
| 165 | + scale_alg=scale_alg, | ||
| 166 | + dst_type_max=quant_elem_dtype_max, | ||
| 167 | + ) | ||
| 168 | + | ||
| 169 | + # torch_npu.npu_anti_mx_quant only accepts scale of block_size==32. | ||
| 170 | + # Turn dynamic's per-``block`` scale into the 32-keyed layout | ||
| 171 | + # npu_anti_mx_quant expects. block_size is assumed to be multiples of 32, | ||
| 172 | + # which should be guaranteed by the caller. | ||
| 173 | + if block_size > 32: | ||
| 174 | + flat = scale.reshape(*scale.shape[:-2], -1) # merge pair dim | ||
| 175 | + flat = flat.repeat_interleave(block_size // 32, dim=-1) # duplicate scales | ||
| 176 | + | ||
| 177 | + # because block_size >= 32, there is always enough padding rows for us to reuse | ||
| 178 | + sdim_padded = ceil(ceil(x.shape[-1] / 32) / 2) * 2 | ||
| 179 | + flat = flat[..., :sdim_padded] # trim the padded tail | ||
| 180 | + scale = flat.reshape(*flat.shape[:-1], sdim_padded // 2, 2) # re-form pack dim | ||
| 181 | + | ||
| 182 | + dequant = torch_npu.npu_anti_mx_quant(qdata, scale, axis=-1, dst_type=x.dtype, src_type=quant_elem_dtype) | ||
| 183 | + assert dequant.is_contiguous(), "``dequant`` is expected to be contiguous." | ||
| 184 | + return dequant | ||
| 185 | + | ||
| 186 | + | ||
| 187 | +@mx_last_dim_fake_quantize.register_fake | ||
| 188 | +def _(x, quant_elem_dtype, block_size, round_mode, scale_alg, quant_elem_dtype_max): | ||
| 189 | + """Metadata only: dense output mirroring ``x``'s shape and dtype.""" | ||
| 190 | + del quant_elem_dtype, block_size, round_mode, scale_alg, quant_elem_dtype_max | ||
| 191 | + return torch.empty_like(x, memory_format=torch.contiguous_format) | ||
| 192 | + | ||
| 193 | + | ||
| 194 | +def mx_last_dim_fake_quantize_backward(ctx, grad_output): | ||
| 195 | + """Straight-through: the tensor arg keeps its gradient, the scalars get none.""" | ||
| 196 | + return grad_output, None, None, None, None, None | ||
| 197 | + | ||
| 198 | + | ||
| 199 | +torch.library.register_autograd(mx_last_dim_fake_quantize, mx_last_dim_fake_quantize_backward) | ||
| 200 | + | ||
| 201 | + | ||
| 128 | def mx_fake_quantize( | 202 | def mx_fake_quantize( |
| 129 | tensor: torch.Tensor, | 203 | tensor: torch.Tensor, |
| 130 | axis: int, | 204 | axis: int, |
| 131 | config: MXQuantizeConfig, | 205 | config: MXQuantizeConfig, |
| 132 | ) -> torch.Tensor: | 206 | ) -> torch.Tensor: |
| 133 | - """MX fake-quantize ``tensor`` along ``axis``. | 207 | + """MX fake-quantize ``tensor`` along ``axis`` (differentiable via a straight-through estimator). |
| 134 | 208 | ||
| 135 | Quantizes with ``npu_dynamic_mx_quant`` and immediately dequantizes the result | 209 | Quantizes with ``npu_dynamic_mx_quant`` and immediately dequantizes the result |
| 136 | with ``npu_anti_mx_quant``, so the values are those of a real MX | 210 | with ``npu_anti_mx_quant``, so the values are those of a real MX |
| @@ -162,22 +236,13 @@ def mx_fake_quantize( | |||
| 162 | perm_indices.append(axis) | 236 | perm_indices.append(axis) |
| 163 | tensor_p = tensor.permute(perm_indices) | 237 | tensor_p = tensor.permute(perm_indices) |
| 164 | 238 | ||
| 165 | - y_p, scale_p = torch_npu.npu_dynamic_mx_quant( | 239 | + y_fake_p = mx_last_dim_fake_quantize( |
| 166 | tensor_p, | 240 | tensor_p, |
| 167 | - axis=-1, | 241 | + config.npu_elem_dtype, |
| 168 | - dst_type=config.npu_elem_dtype, | 242 | + config.block_size, |
| 169 | - block_size=config.block_size, | 243 | + config.round_mode, |
| 170 | - round_mode=config.round_mode, | 244 | + config.scale_alg, |
| 171 | - scale_alg=config.scale_alg, | 245 | + config.dst_type_max, |
| 172 | - dst_type_max=config.dst_type_max, | ||
| 173 | - ) | ||
| 174 | - | ||
| 175 | - y_fake_p = torch_npu.npu_anti_mx_quant( | ||
| 176 | - y_p, | ||
| 177 | - scale_p, | ||
| 178 | - axis=-1, | ||
| 179 | - dst_type=tensor_p.dtype, | ||
| 180 | - src_type=config.npu_elem_dtype, | ||
| 181 | ) | 246 | ) |
| 182 | 247 | ||
| 183 | # Inverse permutation: y_p dim j corresponds to tensor dim perm_indices[j]. | 248 | # Inverse permutation: y_p dim j corresponds to tensor dim perm_indices[j]. |
| @@ -33,14 +33,15 @@ from torchao_npu.quantization.quant_configs import ( | |||
| 33 | HiF8QuantizeConfig, | 33 | HiF8QuantizeConfig, |
| 34 | MXQuantizeConfig, | 34 | MXQuantizeConfig, |
| 35 | ) | 35 | ) |
| 36 | +from torchao_npu.quantization.quant_primitives.mx import mx_fake_quantize | ||
| 36 | from torchtitan.components.quantization import QuantizationConverter | 37 | from torchtitan.components.quantization import QuantizationConverter |
| 37 | from torchtitan.config import derive | 38 | from torchtitan.config import derive |
| 38 | from torchtitan.models.common.linear import Linear | 39 | from torchtitan.models.common.linear import Linear |
| 39 | from torchtitan.models.common.moe import GroupedExperts | 40 | from torchtitan.models.common.moe import GroupedExperts |
| 40 | from torchtitan.models.utils import validate_converter_order | 41 | from torchtitan.models.utils import validate_converter_order |
| 42 | +from torchtitan.protocols.module import Module | ||
| 41 | from torchtitan.tools.logging import logger | 43 | from torchtitan.tools.logging import logger |
| 42 | 44 | ||
| 43 | -from torchtitan_npu.config.configs import LIQuantization # noqa: TC001 - Tyro resolves the converter Config at runtime. | ||
| 44 | from torchtitan_npu.models.common.metadata_extension import ( | 45 | from torchtitan_npu.models.common.metadata_extension import ( |
| 45 | LightningIndexerKernelConfig, | 46 | LightningIndexerKernelConfig, |
| 46 | LightningIndexerMetadata, | 47 | LightningIndexerMetadata, |
| @@ -53,9 +54,12 @@ from torchtitan_npu.patches.torchtitan.models.common.linear import BatchedLinear | |||
| 53 | if TYPE_CHECKING: | 54 | if TYPE_CHECKING: |
| 54 | from torchao_npu.configs import QuantLightningIndexerConfig | 55 | from torchao_npu.configs import QuantLightningIndexerConfig |
| 55 | from torchtitan.protocols.model_spec import ModelSpec | 56 | from torchtitan.protocols.model_spec import ModelSpec |
| 56 | - from torchtitan.protocols.module import Module | ||
| 57 | 57 | ||
| 58 | - from torchtitan_npu.config.configs import QuantizationExtensionConfig | 58 | + from torchtitan_npu.config.configs import ( |
| 59 | + KVNormQuantizationConfig, | ||
| 60 | + LIQuantization, | ||
| 61 | + QuantizationExtensionConfig, | ||
| 62 | + ) | ||
| 59 | 63 | ||
| 60 | 64 | ||
| 61 | class ConfigFilterFn(Protocol): | 65 | class ConfigFilterFn(Protocol): |
| @@ -253,6 +257,204 @@ class NpuQuantizeConverter(QuantizationConverter): | |||
| 253 | return model_config | 257 | return model_config |
| 254 | 258 | ||
| 255 | 259 | ||
| 260 | +class FakeQuantizedNormFactory(Module): | ||
| 261 | + """Config node that builds a fake-quantizing norm in place of a norm config. | ||
| 262 | + | ||
| 263 | + The converter installs this node where a target config used to be; the node | ||
| 264 | + keeps that config in ``norm`` so the override pass (e.g. ``rms_norm.asc``) | ||
| 265 | + still finds and rewrites it. ``build()`` then resolves the module class from | ||
| 266 | + the wrapped config's owner -- the fused replacement when such an override ran, | ||
| 267 | + the original module class otherwise -- and builds a generated subclass of it | ||
| 268 | + that fake-quantizes the nope prefix of its output. | ||
| 269 | + | ||
| 270 | + Consequences worth knowing: | ||
| 271 | + | ||
| 272 | + - the built module keeps the norm's parameter names (``...kv_norm.weight``), | ||
| 273 | + so checkpoints and state-dict adapters are unaffected; | ||
| 274 | + - the built module is *not* ``type(config)._owner``; | ||
| 275 | + - ``FakeQuantizedNormFactory`` itself is never instantiated. | ||
| 276 | + """ | ||
| 277 | + | ||
| 278 | + @dataclass(kw_only=True, slots=True) | ||
| 279 | + class Config(Module.Config): | ||
| 280 | + norm: Module.Config | ||
| 281 | + """The config this node replaced (selected by the converter's targets).""" | ||
| 282 | + _fake_quant_config: Annotated[MXQuantizeConfig | None, tyro.conf.Suppress] = None | ||
| 283 | + """How the nope prefix is fake-quantized.""" | ||
| 284 | + head_dim: int | ||
| 285 | + """Width of the norm's input and output; validated at run time.""" | ||
| 286 | + nope_head_dim: int | ||
| 287 | + """Width of the fake-quantized prefix (the channels RoPE does not rotate).""" | ||
| 288 | + | ||
| 289 | + def build(self, **kwargs): | ||
| 290 | + owner = type(self.norm)._owner | ||
| 291 | + if owner is None: | ||
| 292 | + raise TypeError( | ||
| 293 | + f"{type(self.norm).__qualname__} has no owning module class; " | ||
| 294 | + "FakeQuantizedNormFactory cannot build it" | ||
| 295 | + ) | ||
| 296 | + if self._fake_quant_config is None: | ||
| 297 | + raise ValueError("FakeQuantizedNormFactory.Config requires _fake_quant_config") | ||
| 298 | + # The generated Config's owner is the generated module class, so the | ||
| 299 | + # framework's Module.Config.build does the construction and attaches | ||
| 300 | + # ``_param_init``/``_sharding_config`` (the model writes the sharding | ||
| 301 | + # declaration at this node, not on the wrapped config). | ||
| 302 | + return derive( | ||
| 303 | + self.norm, | ||
| 304 | + _dynamic_norm_class(owner).Config, | ||
| 305 | + fake_quant_config=self._fake_quant_config, | ||
| 306 | + head_dim=self.head_dim, | ||
| 307 | + nope_head_dim=self.nope_head_dim, | ||
| 308 | + param_init=self.param_init, | ||
| 309 | + sharding_config=self.sharding_config, | ||
| 310 | + ).build(**kwargs) | ||
| 311 | + | ||
| 312 | + | ||
| 313 | +_DYNAMIC_NORM_CLASS_CACHE: dict[type[Module], type[Module]] = {} | ||
| 314 | + | ||
| 315 | + | ||
| 316 | +def _dynamic_norm_class(owner: type[Module]) -> type[Module]: | ||
| 317 | + """ | ||
| 318 | + Generates a FakeQuantizedNorm via subclassing ``owner``. | ||
| 319 | + | ||
| 320 | + The generated class is cached using owner as the key. So repeated | ||
| 321 | + builds neither re-create classes nor re-trigger ``torch.compile``. | ||
| 322 | + | ||
| 323 | + A FakeQuantizedNorm fake-quantizes the nope prefix of the output of | ||
| 324 | + the Norm class it subclasses. Each FakeQuantizedNorm carries its own | ||
| 325 | + widths and quantization config on the config, | ||
| 326 | + """ | ||
| 327 | + | ||
| 328 | + if owner in _DYNAMIC_NORM_CLASS_CACHE: | ||
| 329 | + return _DYNAMIC_NORM_CLASS_CACHE[owner] | ||
| 330 | + | ||
| 331 | + class FakeQuantizedNorm(owner): # type: ignore[valid-type, misc] | ||
| 332 | + """``owner`` followed by a fake-quantization of the nope prefix.""" | ||
| 333 | + | ||
| 334 | + @dataclass(kw_only=True, slots=True) | ||
| 335 | + class Config(owner.Config): # type: ignore[misc, valid-type] | ||
| 336 | + fake_quant_config: MXQuantizeConfig | ||
| 337 | + head_dim: int | ||
| 338 | + nope_head_dim: int | ||
| 339 | + | ||
| 340 | + def __init__(self, config: Config) -> None: | ||
| 341 | + super().__init__(config) | ||
| 342 | + self.fake_quant_config = config.fake_quant_config | ||
| 343 | + self.head_dim = config.head_dim | ||
| 344 | + self.nope_head_dim = config.nope_head_dim | ||
| 345 | + | ||
| 346 | + def forward(self, x: torch.Tensor) -> torch.Tensor: | ||
| 347 | + if x.shape[-1] != self.head_dim: | ||
| 348 | + raise ValueError(f"{type(self).__name__} expects a width-{self.head_dim} input, got {tuple(x.shape)}") | ||
| 349 | + # Compute the norm first, then fake-quantize the nope prefix only: the | ||
| 350 | + # trailing channels must reach RoPE untouched. The fake quantization | ||
| 351 | + # carries straight-through gradients and ``cat`` keeps the whole | ||
| 352 | + # path free of in-place writes. | ||
| 353 | + y = super().forward(x) | ||
| 354 | + return torch.cat( | ||
| 355 | + [ | ||
| 356 | + mx_fake_quantize(y[..., : self.nope_head_dim], -1, self.fake_quant_config), | ||
| 357 | + y[..., self.nope_head_dim :], | ||
| 358 | + ], | ||
| 359 | + dim=-1, | ||
| 360 | + ) | ||
| 361 | + | ||
| 362 | + FakeQuantizedNorm.__name__ = FakeQuantizedNorm.__qualname__ = f"FakeQuantized{owner.__name__}" | ||
| 363 | + _DYNAMIC_NORM_CLASS_CACHE[owner] = FakeQuantizedNorm | ||
| 364 | + return FakeQuantizedNorm | ||
| 365 | + | ||
| 366 | + | ||
| 367 | +class KVNormFakeQuantConverter(QuantizationConverter): | ||
可以统一使用NpuQuantizeConverter吗?量化Module 放到 experiments/torchao-npu/torchao_npu/quantized_modules下。这个文件过长了,一些责任应该分担到其他文件里 ![]() ![]() | |||
| 368 | + """Install :class:`FakeQuantizedNormFactory` in front of the selected norms. | ||
| 369 | + | ||
| 370 | + The nodes are selected by config-tree FQN suffix (``target_fqns``), so any | ||
| 371 | + norm node can be targeted. | ||
| 372 | + """ | ||
| 373 | + | ||
| 374 | + class _KVRopeGeometry(Protocol): | ||
| 375 | + """The parent-config surface the converter reads.""" | ||
| 376 | + | ||
| 377 | + head_dim: int | ||
| 378 | + rope_head_dim: int | ||
| 379 | + rope: Module.Config | ||
| 380 | + | ||
| 381 | + @dataclass(kw_only=True, slots=True) | ||
| 382 | + class Config(QuantizationConverter.Config): | ||
| 383 | + base_config: Annotated[MXQuantizeConfig | None, tyro.conf.Suppress] = None | ||
| 384 | + target_fqns: tuple[str, ...] = () | ||
| 385 | + require_match: bool = True | ||
| 386 | + | ||
| 387 | + def __post_init__(self) -> None: | ||
| 388 | + if self.base_config is None: | ||
| 389 | + raise ValueError("KVNormFakeQuantConverter.Config requires base_config") | ||
| 390 | + | ||
| 391 | + if len(self.target_fqns) == 0: | ||
| 392 | + raise ValueError("Must specify fqns of target Modules") | ||
| 393 | + | ||
| 394 | + def __init__(self, config: Config) -> None: | ||
| 395 | + self.config = config | ||
| 396 | + self.filter = match_config_fqn_suffix(*config.target_fqns) | ||
| 397 | + | ||
| 398 | + def convert(self, model_config): | ||
| 399 | + # Collect before mutating: traversal never re-visits a replaced node, and | ||
| 400 | + # the factory keeps the wrapped config one level down. There is no common | ||
| 401 | + # norm config base class, so the walk is generic and the selection is | ||
| 402 | + # entirely FQN-driven (``recurse=True`` walks the whole tree). | ||
| 403 | + matches = [ | ||
| 404 | + (fqn, config, parent, attr) | ||
| 405 | + for fqn, config, parent, attr in model_config.traverse(Module.Config, recurse=True) | ||
| 406 | + if self.filter(cast("Module.Config", config), fqn) | ||
| 407 | + ] | ||
| 408 | + | ||
| 409 | + converted = 0 | ||
| 410 | + for fqn, config, parent, attr in matches: | ||
| 411 | + if parent is None: | ||
| 412 | + raise ValueError(f"the norm fake quantization does not support the root config ({fqn!r})") | ||
| 413 | + # The parent carries the rope geometry: the nope span is exactly the | ||
| 414 | + # prefix RoPE leaves untouched, so it must agree with the rope split. | ||
| 415 | + parent_cfg = cast("KVNormFakeQuantConverter._KVRopeGeometry", parent) | ||
| 416 | + head_dim = getattr(parent_cfg, "head_dim", None) | ||
| 417 | + rope_head_dim = getattr(parent_cfg, "rope_head_dim", None) | ||
| 418 | + if head_dim is None or rope_head_dim is None: | ||
| 419 | + raise ValueError( | ||
| 420 | + f"target norm at {fqn!r} has no rope geometry on its parent; the nope span cannot be derived" | ||
| 421 | + ) | ||
| 422 | + nope_head_dim = head_dim - rope_head_dim | ||
| 423 | + split = getattr(getattr(parent_cfg, "rope", None), "split", nope_head_dim) | ||
| 424 | + if not 0 < nope_head_dim <= head_dim: | ||
| 425 | + raise ValueError( | ||
| 426 | + f"KV norm at {fqn!r} has an invalid nope span: head_dim={head_dim}, nope_head_dim={nope_head_dim}" | ||
| 427 | + ) | ||
| 428 | + if split != nope_head_dim: | ||
| 429 | + raise ValueError( | ||
| 430 | + f"KV norm at {fqn!r} disagrees with its rope split: " | ||
| 431 | + f"nope_head_dim={nope_head_dim}, rope split={split}" | ||
| 432 | + ) | ||
| 433 | + replacement = derive( | ||
| 434 | + config, | ||
| 435 | + FakeQuantizedNormFactory.Config, | ||
| 436 | + norm=config, | ||
| 437 | + _fake_quant_config=self.config.base_config, | ||
| 438 | + head_dim=head_dim, | ||
| 439 | + nope_head_dim=nope_head_dim, | ||
| 440 | + ) | ||
| 441 | + model_config = _replace_config(model_config, parent, attr, replacement) | ||
| 442 | + converted += 1 | ||
| 443 | + logger.info( | ||
| 444 | + "[Converter] %s.%s: model_spec.model.%s %s -> %s", | ||
| 445 | + type(self).__module__, | ||
| 446 | + type(self).__qualname__, | ||
| 447 | + fqn, | ||
| 448 | + type(config).__qualname__, | ||
| 449 | + type(replacement).__qualname__, | ||
| 450 | + ) | ||
| 451 | + | ||
| 452 | + if converted == 0 and self.config.require_match: | ||
| 453 | + raise ValueError("KVNormFakeQuantConverter did not match any config nodes") | ||
| 454 | + logger.info("Converted %d config node(s) for KV norm fake quantization", converted) | ||
| 455 | + return model_config | ||
| 456 | + | ||
| 457 | + | ||
| 256 | # DeepSeek-V4 config-tree filters for the current model hierarchy. | 458 | # DeepSeek-V4 config-tree filters for the current model hierarchy. |
| 257 | _DSV4_CONFIG_FILTERS = { | 459 | _DSV4_CONFIG_FILTERS = { |
| 258 | "dense": match_config_fqn_suffix( | 460 | "dense": match_config_fqn_suffix( |
| @@ -472,6 +674,7 @@ def _recipe_converters( | |||
| 472 | model_compile_enabled: bool, | 674 | model_compile_enabled: bool, |
| 473 | li_quantization: LIQuantization | None = None, | 675 | li_quantization: LIQuantization | None = None, |
| 474 | li_kernel_config: LightningIndexerKernelConfig | None = None, | 676 | li_kernel_config: LightningIndexerKernelConfig | None = None, |
| 677 | + kv_norm_quantization: KVNormQuantizationConfig | None = None, | ||
| 475 | ) -> list[QuantizationConverter.Config]: | 678 | ) -> list[QuantizationConverter.Config]: |
| 476 | converters: list[QuantizationConverter.Config] | 679 | converters: list[QuantizationConverter.Config] |
| 477 | try: | 680 | try: |
| @@ -554,6 +757,17 @@ def _recipe_converters( | |||
| 554 | "sparse_attention filter; skipping the sparse attention replacement.", | 757 | "sparse_attention filter; skipping the sparse attention replacement.", |
| 555 | model_type, | 758 | model_type, |
| 556 | ) | 759 | ) |
| 760 | + | ||
| 761 | + if kv_norm_quantization is not None and kv_norm_quantization.format is not None: | ||
| 762 | + converters.append( | ||
| 763 | + KVNormFakeQuantConverter.Config( | ||
| 764 | + base_config=MXQuantizeConfig( | ||
| 765 | + elem_dtype=torch.float8_e4m3fn, block_size=kv_norm_quantization.block_size | ||
| 766 | + ), | ||
| 767 | + target_fqns=tuple(kv_norm_quantization.fqns), | ||
| 768 | + model_compile_enabled=model_compile_enabled, | ||
| 769 | + ) | ||
| 770 | + ) | ||
| 557 | return converters | 771 | return converters |
| 558 | 772 | ||
| 559 | 773 | ||
| @@ -616,6 +830,7 @@ def apply_quantization_converter( | |||
| 616 | model_compile_enabled=model_compile_enabled, | 830 | model_compile_enabled=model_compile_enabled, |
| 617 | li_quantization=quantization_config.li_quantization, | 831 | li_quantization=quantization_config.li_quantization, |
| 618 | li_kernel_config=li_kernel_config, | 832 | li_kernel_config=li_kernel_config, |
| 833 | + kv_norm_quantization=quantization_config.kv_norm_quantization, | ||
| 619 | ) | 834 | ) |
| 620 | validate_converter_order(converters) | 835 | validate_converter_order(converters) |
| 621 | 836 | ||
| @@ -624,11 +839,14 @@ def apply_quantization_converter( | |||
| 624 | 839 | ||
| 625 | logger.info( | 840 | logger.info( |
| 626 | "Applied TorchAO-NPU recipe=%s, sparse_attention_quantization=%s, mxfp4_qat=%s, " | 841 | "Applied TorchAO-NPU recipe=%s, sparse_attention_quantization=%s, mxfp4_qat=%s, " |
| 627 | - "li_quantization=%s, dst_type_max=%s, fsdp_prequantize=%s", | 842 | + "li_quantization=%s, kv_norm_quantization=%s, kv_norm_block_size=%s, " |
| 843 | + "dst_type_max=%s, fsdp_prequantize=%s", | ||
| 628 | quantization_config.recipe, | 844 | quantization_config.recipe, |
| 629 | quantization_config.enable_sparse_attention_quantization, | 845 | quantization_config.enable_sparse_attention_quantization, |
| 630 | quantization_config.enable_mxfp4_qat, | 846 | quantization_config.enable_mxfp4_qat, |
| 631 | quantization_config.li_quantization, | 847 | quantization_config.li_quantization, |
| 848 | + quantization_config.kv_norm_quantization.format, | ||
| 849 | + quantization_config.kv_norm_quantization.block_size, | ||
| 632 | quantization_config.dst_type_max, | 850 | quantization_config.dst_type_max, |
| 633 | quantization_config.fsdp_prequantize, | 851 | quantization_config.fsdp_prequantize, |
| 634 | ) | 852 | ) |
| @@ -24,6 +24,7 @@ from torchtitan_npu.config import ( | |||
| 24 | ) | 24 | ) |
| 25 | from torchtitan_npu.config import TrainingConfig as NPUTrainingConfig | 25 | from torchtitan_npu.config import TrainingConfig as NPUTrainingConfig |
| 26 | from torchtitan_npu.config import manager as config_manager | 26 | from torchtitan_npu.config import manager as config_manager |
| 27 | +from torchtitan_npu.config.configs import KVNormQuantizationConfig | ||
| 27 | from torchtitan_npu.config.converters import TrainerConfigConverter | 28 | from torchtitan_npu.config.converters import TrainerConfigConverter |
| 28 | from torchtitan_npu.distributed import utils as distributed_utils | 29 | from torchtitan_npu.distributed import utils as distributed_utils |
| 29 | from torchtitan_npu.extensions.graph_trainer import GraphTrainerEx | 30 | from torchtitan_npu.extensions.graph_trainer import GraphTrainerEx |
| @@ -227,6 +228,12 @@ def test_config_manager_parses_quantization_extension( | |||
| 227 | "--extension.quantization.enable-mxfp4-qat", | 228 | "--extension.quantization.enable-mxfp4-qat", |
| 228 | "--extension.quantization.dst-type-max", | 229 | "--extension.quantization.dst-type-max", |
| 229 | "7.0", | 230 | "7.0", |
| 231 | + "--extension.quantization.kv-norm-quantization.format", | ||
| 232 | + "mxfp8", | ||
| 233 | + "--extension.quantization.kv-norm-quantization.fqns", | ||
| 234 | + ".attention.kv_norm,.attention.compressor.norm", | ||
| 235 | + "--extension.quantization.kv-norm-quantization.block-size", | ||
| 236 | + "64", | ||
| 230 | ] | 237 | ] |
| 231 | ) | 238 | ) |
| 232 | 239 | ||
| @@ -236,6 +243,21 @@ def test_config_manager_parses_quantization_extension( | |||
| 236 | assert quantization.enable_mxfp4_qat is True | 243 | assert quantization.enable_mxfp4_qat is True |
| 237 | assert quantization.dst_type_max == 7.0 | 244 | assert quantization.dst_type_max == 7.0 |
| 238 | assert quantization.fsdp_prequantize is False | 245 | assert quantization.fsdp_prequantize is False |
| 246 | + assert quantization.kv_norm_quantization.format == "mxfp8" | ||
| 247 | + assert quantization.kv_norm_quantization.fqns == [".attention.kv_norm", ".attention.compressor.norm"] | ||
| 248 | + assert quantization.kv_norm_quantization.block_size == 64 | ||
| 249 | + | ||
| 250 | + | ||
| 251 | +def test_kv_norm_quantization_config_validates_its_format(): | ||
| 252 | + """ | ||
| 253 | + Only the format is checked here; the block size is validated by the MX | ||
| 254 | + configs that consume it (``MXQuantizeConfig.__post_init__``). | ||
| 255 | + """ | ||
| 256 | + assert KVNormQuantizationConfig().format is None | ||
| 257 | + assert KVNormQuantizationConfig(format="mxfp8", block_size=64).block_size == 64 | ||
| 258 | + | ||
| 259 | + with pytest.raises(ValueError, match="format must be None or one of: mxfp8"): | ||
| 260 | + KVNormQuantizationConfig(format="fp8") # pyrefly: ignore [bad-argument-type] | ||
| 239 | 261 | ||
| 240 | 262 | ||
| 241 | def test_config_manager_materializes_muon_from_cli(monkeypatch, tmp_path): | 263 | def test_config_manager_materializes_muon_from_cli(monkeypatch, tmp_path): |
| @@ -16,6 +16,7 @@ from torchtitan.tools.profiler import Profiler as _BaseProfiler | |||
| 16 | 16 | ||
| 17 | QuantizationRecipe = Literal["all_mxfp8", "mix", "all_block_fp8"] | 17 | QuantizationRecipe = Literal["all_mxfp8", "mix", "all_block_fp8"] |
| 18 | LIQuantization = Literal["mxfp4", "mxfp8", "fp8", "hif8"] | 18 | LIQuantization = Literal["mxfp4", "mxfp8", "fp8", "hif8"] |
| 19 | +KVNormQuantization = Literal["mxfp8"] | ||
| 19 | 20 | ||
| 20 | 21 | ||
| 21 | @dataclass(frozen=True, slots=True) | 22 | @dataclass(frozen=True, slots=True) |
| @@ -99,6 +100,35 @@ class OptimizerConfig(OptimizersContainer.Config): | |||
| 99 | } | 100 | } |
| 100 | 101 | ||
| 101 | 102 | ||
| 103 | +@dataclass(kw_only=True, slots=True) | ||
| 104 | +class KVNormQuantizationConfig: | ||
这个 config 位置是不是调整一下。 ![]() ![]() | |||
| 105 | + """KV norm fake quantization: the format and the norm sites to wrap. | ||
| 106 | + | ||
| 107 | + Always present on the quantization config (so the CLI stays | ||
| 108 | + ``--extension.quantization.kv-norm-quantization.<field>``); ``format=None`` | ||
| 109 | + disables the transform. | ||
| 110 | + """ | ||
| 111 | + | ||
| 112 | + format: KVNormQuantization | None = None | ||
| 113 | + """``mxfp8`` fake-quantizes the nope prefix (the channels RoPE leaves untouched) | ||
| 114 | + with MX block scales. ``None`` disables it. | ||
| 115 | + """ | ||
| 116 | + fqns: list[str] = field(default_factory=list) | ||
| 117 | + """Config-tree FQN suffixes of the norm nodes to fake-quantize. | ||
| 118 | + | ||
| 119 | + A node is selected when its FQN is one of the suffixes or ends with | ||
| 120 | + ``"." + suffix``. Empty by default (nothing is selected): the | ||
| 121 | + launch scripts state the sites explicitly. | ||
| 122 | + """ | ||
| 123 | + block_size: int = 32 | ||
| 124 | + """MX block size of the fake quantization. | ||
| 125 | + """ | ||
| 126 | + | ||
| 127 | + def __post_init__(self) -> None: | ||
| 128 | + if self.format not in (None, "mxfp8"): | ||
| 129 | + raise ValueError("format must be None or one of: mxfp8") | ||
| 130 | + | ||
| 131 | + | ||
| 102 | @dataclass(kw_only=True, slots=True) | 132 | @dataclass(kw_only=True, slots=True) |
| 103 | class QuantizationExtensionConfig: | 133 | class QuantizationExtensionConfig: |
| 104 | """TorchAO-NPU quantized-training options. | 134 | """TorchAO-NPU quantized-training options. |
| @@ -120,6 +150,7 @@ class QuantizationExtensionConfig: | |||
| 120 | """ | 150 | """ |
| 121 | dst_type_max: float = 0.0 | 151 | dst_type_max: float = 0.0 |
| 122 | fsdp_prequantize: bool = False | 152 | fsdp_prequantize: bool = False |
| 153 | + kv_norm_quantization: KVNormQuantizationConfig = field(default_factory=KVNormQuantizationConfig) | ||
| 123 | 154 | ||
| 124 | def validate(self) -> None: | 155 | def validate(self) -> None: |
| 125 | if self.li_quantization not in (None, "mxfp4", "mxfp8", "fp8", "hif8"): | 156 | if self.li_quantization not in (None, "mxfp4", "mxfp8", "fp8", "hif8"): |


此条代码评论区间+44至+46
当前 deepseek v4 KV 的量化方式是否固定,固定的话可以使用一个传参控制 kv 量化,
fqns建议写到 torchao_converter.py 的_DSV4_CONFIG_FILTERS中