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 Main KV E2M1 storage with group-16 E4M3 or BF16 scales.
16
17Rows contain packed E2M1 values followed by scales. BF16-scale rows are
18padded to the 32-byte cache ABI; decoding ignores that padding.
19"""
20
21from importlib import import_module
22
23import torch
24from torch import Tensor
25
26from hyper_parallel.components.quantization.config import (
27 FP8_E4M3_MAX,
28 MAIN_KV_GROUP_SIZE,
29 MXFP4_MAX_VALUE,
30 MXFP4_VALUES_PER_BYTE,
31)
32
33_MIN_E4M3_SCALE = 2.0 ** -9
34_E4M3_SCALE_BYTES = 1
35_BF16_SCALE_BYTES = 2
36_BF16_CACHE_ROW_ALIGNMENT = 32
37
38
39def _main_row_bytes(width: int, scale_format: str) -> int:
40 """Count data and scale bytes, including the BF16-scale cache ABI padding."""
41 scale_bytes = _BF16_SCALE_BYTES if scale_format == "e8m7" else _E4M3_SCALE_BYTES
42 payload = width // MXFP4_VALUES_PER_BYTE + width // MAIN_KV_GROUP_SIZE * scale_bytes
43 if scale_format == "e8m7":
44 return (payload + _BF16_CACHE_ROW_ALIGNMENT - 1) // _BF16_CACHE_ROW_ALIGNMENT * _BF16_CACHE_ROW_ALIGNMENT
45 return payload
46
47
48def quantize_main_kv(kv: Tensor, scale_format: str = "e4m3") -> Tensor:
49 """Encode Main KV using E2M1 values and group-16 E4M3 or BF16 scales."""
50 width = kv.shape[-1]
51 if width <= 0 or width % MAIN_KV_GROUP_SIZE:
52 raise ValueError(
53 f"Main KV last axis {width} is not divisible by group_size {MAIN_KV_GROUP_SIZE}; "
54 "no cross-row padding is allowed"
55 )
56 if kv.numel() == 0:
57 return torch.empty((*kv.shape[:-1], _main_row_bytes(width, scale_format)),
58 dtype=torch.uint8, device=kv.device)
59 npu = import_module("torch_npu")
60 grouped = kv.float().reshape(*kv.shape[:-1], width // MAIN_KV_GROUP_SIZE, MAIN_KV_GROUP_SIZE)
61 # Preserve nonfinite groups so quantization cannot hide an overflow.
62 amax = torch.nan_to_num(grouped.abs(), nan=float("inf"), posinf=float("inf")).amax(dim=-1)
63 scales = amax / MXFP4_MAX_VALUE
64 if scale_format == "e4m3":
65 scales = scales.clamp(min=_MIN_E4M3_SCALE, max=FP8_E4M3_MAX)
66 else:
67 scales = scales.clamp_min(torch.finfo(torch.bfloat16).tiny)
68 scale_values = torch.where(torch.isinf(amax), float("nan"), scales)
69 if scale_format == "e4m3":
70 scales = scale_values.to(torch.float8_e4m3fn)
71 else:
72 scales = scale_values.to(torch.bfloat16)
73 normalized = grouped / scales.float().unsqueeze(-1)
74 if scale_format == "e8m7":
75 normalized = normalized.clamp(-MXFP4_MAX_VALUE, MXFP4_MAX_VALUE)
76 data = npu.npu_dtype_cast(normalized, npu.float4_e2m1fn_x2)
77 packed = torch.cat((data.reshape(*kv.shape[:-1], width // MXFP4_VALUES_PER_BYTE),
78 scales.view(torch.uint8)), dim=-1)
79 padding = _main_row_bytes(width, scale_format) - packed.shape[-1]
80 return torch.nn.functional.pad(packed, (0, padding)) if padding else packed
81
82
83def dequantize_main_kv(packed: Tensor, logical_width: int, dtype: torch.dtype,
84 scale_format: str = "e4m3") -> Tensor:
85 """Decode Main KV bytes and apply their group scales in the requested dtype."""
86 if logical_width <= 0 or logical_width % MAIN_KV_GROUP_SIZE:
87 raise ValueError("Main KV logical width must be positive and divisible by 16.")
88 if packed.numel() == 0:
89 return torch.empty((*packed.shape[:-1], logical_width), dtype=dtype, device=packed.device)
90 npu = import_module("torch_npu")
91 data = packed[..., :logical_width // MXFP4_VALUES_PER_BYTE].contiguous()
92 scale_bytes = logical_width // MAIN_KV_GROUP_SIZE * (
93 _BF16_SCALE_BYTES if scale_format == "e8m7" else _E4M3_SCALE_BYTES
94 )
95 scale_dtype = torch.bfloat16 if scale_format == "e8m7" else torch.float8_e4m3fn
96 scale = packed[..., logical_width // MXFP4_VALUES_PER_BYTE:logical_width // MXFP4_VALUES_PER_BYTE + scale_bytes]
97 scale = scale.contiguous().view(scale_dtype)
98 values = npu.npu_dtype_cast(data, dtype, input_dtype=npu.float4_e2m1fn_x2)
99 grouped = values.reshape(*data.shape[:-1], logical_width // MAIN_KV_GROUP_SIZE, MAIN_KV_GROUP_SIZE)
100 if scale_format == "e8m7":
101 if dtype == torch.bfloat16:
102 # The cast owns this buffer; scaling cannot mutate packed storage.
103 grouped.mul_(scale.unsqueeze(-1))
104 return values
105 return (grouped.float() * scale.float().unsqueeze(-1)).reshape(*data.shape[:-1], logical_width).to(dtype)
106 if dtype == torch.bfloat16:
107 grouped.mul_(scale.to(dtype).unsqueeze(-1))
108 return values
109 return (grouped * scale.to(dtype).unsqueeze(-1)).reshape(*data.shape[:-1], logical_width)
110
111
112__all__ = ["quantize_main_kv", "dequantize_main_kv"]