1# Copyright 2026 Huawei Technologies Co., Ltd
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"""NPU MXFP4 codecs for Indexer keys and the query QDQ boundary.
16
17Each 32-element block uses E2M1 values with an E8M0 scale. Scale slots are
18paired by the native ABI; groups never span token or head boundaries.
19Query QDQ injects the same rounding into TopK scoring and passes STE gradients.
20"""
21
22from importlib import import_module
23from typing import Any
24
25import torch
26from torch import Tensor
27
28from hyper_parallel.components.quantization.config import (
29 MX_BLOCK_SIZE_32,
30 MX_SCALE_ALG_OCP,
31 MX_SCALE_SLOTS,
32 MXFP4_VALUES_PER_BYTE,
33)
34
35_ANTI_QUANT_DST_TYPES = {torch.float16: 5, torch.float32: 6, torch.bfloat16: 15}
36
37
38def _indexer_row_bytes(width: int) -> int:
39 """Count E2M1 data bytes and pair-padded E8M0 scale bytes."""
40 scale_slots = MX_SCALE_SLOTS * ((width // MX_BLOCK_SIZE_32 + 1) // 2)
41 return width // MXFP4_VALUES_PER_BYTE + scale_slots
42
43
44def quantize_indexer_k(key: Tensor) -> Tensor:
45 """Encode Indexer K rows as E2M1 data followed by paired E8M0 scales."""
46 width = key.shape[-1]
47 if width <= 0 or width % MX_BLOCK_SIZE_32:
48 raise ValueError("Indexer K width must be positive and divisible by 32.")
49 if key.numel() == 0:
50 return torch.empty((*key.shape[:-1], _indexer_row_bytes(width)),
51 dtype=torch.uint8, device=key.device)
52 npu = import_module("torch_npu")
53 data, scale = npu.npu_dynamic_mx_quant(
54 key.reshape(-1, width).contiguous(), dst_type=npu.float4_e2m1fn_x2,
55 block_size=MX_BLOCK_SIZE_32, round_mode="rint", scale_alg=MX_SCALE_ALG_OCP,
56 )
57 return torch.cat((data.reshape(*key.shape[:-1], width // MXFP4_VALUES_PER_BYTE),
58 scale.reshape(*key.shape[:-1], -1)), dim=-1)
59
60
61def dequantize_indexer_k(packed: Tensor, logical_width: int, dtype: torch.dtype) -> Tensor:
62 """Decode packed Indexer K rows to the requested floating dtype."""
63 if logical_width <= 0 or logical_width % MX_BLOCK_SIZE_32:
64 raise ValueError("Indexer K width must be positive and divisible by 32.")
65 if packed.numel() == 0:
66 return torch.empty((*packed.shape[:-1], logical_width), dtype=dtype, device=packed.device)
67 npu = import_module("torch_npu")
68 scale_pairs = (logical_width // MX_BLOCK_SIZE_32 + 1) // 2
69 data = packed[..., :logical_width // MXFP4_VALUES_PER_BYTE].contiguous()
70 scale = packed[..., logical_width // MXFP4_VALUES_PER_BYTE:].reshape(
71 *packed.shape[:-1], scale_pairs, MX_SCALE_SLOTS
72 ).contiguous()
73 values = npu.npu_anti_mx_quant(
74 data.reshape(-1, logical_width // MXFP4_VALUES_PER_BYTE),
75 scale.reshape(-1, scale_pairs, MX_SCALE_SLOTS),
76 axis=-1, dst_type=_ANTI_QUANT_DST_TYPES[dtype],
77 src_type=npu.float4_e2m1fn_x2,
78 )
79 return values.reshape(*packed.shape[:-1], logical_width)
80
81
82class _MXFP4QDQFunction(torch.autograd.Function):
83 """Quantize and decode each Indexer query head, using an identity STE."""
84
85 @staticmethod
86 def forward(ctx: Any, x: Tensor) -> Tensor:
87 """Apply native block-32 OCP MXFP4 quantization and decode to the input dtype."""
88 del ctx
89 width = x.shape[-1]
90 if width <= 0 or width % MX_BLOCK_SIZE_32:
91 raise ValueError(
92 f"Indexer Q/K last axis {width} is not divisible by "
93 f"block_size {MX_BLOCK_SIZE_32}; no cross-row padding is allowed"
94 )
95 if x.numel() == 0:
96 return x
97 npu = import_module("torch_npu")
98 packed, scale = npu.npu_dynamic_mx_quant(
99 x.reshape(-1, width), dst_type=npu.float4_e2m1fn_x2,
100 block_size=MX_BLOCK_SIZE_32, round_mode="rint", scale_alg=MX_SCALE_ALG_OCP,
101 )
102 values = npu.npu_anti_mx_quant(
103 packed, scale, axis=-1, dst_type=_ANTI_QUANT_DST_TYPES[x.dtype],
104 src_type=npu.float4_e2m1fn_x2,
105 )
106 return values.reshape(x.shape)
107
108 @staticmethod
109 def backward(ctx: Any, grad_output: Tensor) -> Tensor:
110 """Pass gradients through the quantization error with an identity STE."""
111 del ctx
112 return grad_output
113
114
115def indexer_qk_quantize_dequantize(query: Tensor) -> Tensor:
116 """Apply MXFP4 QDQ per query head with identity STE gradients."""
117 return _MXFP4QDQFunction.apply(query)
118
119
120__all__ = ["indexer_qk_quantize_dequantize", "quantize_indexer_k", "dequantize_indexer_k"]