def _scale_slots(width: int) -> int:
"""Round group-32 E8M0 scale slots to the native two-slot ABI."""
groups = width // SWA_KV_GROUP_SIZE
return (groups + MX_SCALE_SLOTS - 1) // MX_SCALE_SLOTS * MX_SCALE_SLOTS
def _swa_row_bytes(width: int, scale_format: str) -> int:
"""Count SWA data and scale bytes, including BF16-scale row padding."""
if scale_format == "e8m0":
return width + _scale_slots(width)
payload = width + _BF16_SCALE_BYTES * width // SWA_KV_GROUP_SIZE
return (payload + _BF16_CACHE_ROW_ALIGNMENT - 1) // _BF16_CACHE_ROW_ALIGNMENT * _BF16_CACHE_ROW_ALIGNMENT
def quantize_swa_kv(kv: Tensor, scale_format: str = "e8m0") -> Tensor:
"""Encode SWA KV rows as E4M3 values with group-32 E8M0 or BF16 scales."""
width = kv.shape[-1]
if width <= 0 or width % SWA_KV_GROUP_SIZE:
raise ValueError("SWA KV last axis must be positive and divisible by 32.")
if kv.numel() == 0:
return torch.empty((*kv.shape[:-1], _swa_row_bytes(width, scale_format)),
dtype=torch.uint8, device=kv.device)
if scale_format == "e8m0":
flat = kv.reshape(-1, width).contiguous()
npu = import_module("torch_npu")
data, scale = npu.npu_dynamic_mx_quant(
flat, dst_type=torch.float8_e4m3fn, block_size=MX_BLOCK_SIZE_32,
scale_alg=MX_SCALE_ALG_CUBALS,
)
return torch.cat((data.view(torch.uint8).reshape(*kv.shape[:-1], width),
scale.reshape(*kv.shape[:-1], -1)), dim=-1)
grouped = kv.float().reshape(*kv.shape[:-1], width // SWA_KV_GROUP_SIZE, SWA_KV_GROUP_SIZE)
amax = torch.nan_to_num(grouped.abs(), nan=float("inf")).amax(dim=-1)
scale = (amax / FP8_E4M3_MAX).clamp_min(torch.finfo(torch.bfloat16).tiny).to(torch.bfloat16)
normalized = (grouped / scale.float().unsqueeze(-1)).clamp(-FP8_E4M3_MAX, FP8_E4M3_MAX)
data = normalized.to(torch.float8_e4m3fn)
packed = torch.cat((data.view(torch.uint8).reshape(*kv.shape[:-1], width), scale.view(torch.uint8)), dim=-1)
padding = _swa_row_bytes(width, scale_format) - packed.shape[-1]
return torch.nn.functional.pad(packed, (0, padding)) if padding else packed
def dequantize_swa_kv(packed: Tensor, logical_width: int, scale_format: str = "e8m0") -> Tensor:
"""Decode packed SWA rows to BF16 using the selected scale format."""
if logical_width <= 0 or logical_width % SWA_KV_GROUP_SIZE:
raise ValueError("SWA KV logical width must be positive and divisible by 32.")
if packed.numel() == 0:
return torch.empty((*packed.shape[:-1], logical_width), dtype=torch.bfloat16, device=packed.device)
data = packed[..., :logical_width].contiguous()
if scale_format == "e8m0":
slots = _scale_slots(logical_width)
scale = packed[..., logical_width:logical_width + slots]
scale = scale.reshape(*data.shape[:-1], slots // MX_SCALE_SLOTS, MX_SCALE_SLOTS)
npu = import_module("torch_npu")
values = npu.npu_anti_mx_quant(
data.reshape(-1, logical_width).view(torch.float8_e4m3fn),
scale.reshape(-1, slots // MX_SCALE_SLOTS, MX_SCALE_SLOTS).contiguous(),
src_type=torch.float8_e4m3fn, dst_type=15, # BF16 output
)
groups = logical_width // SWA_KV_GROUP_SIZE
invalid_scale = scale.reshape(*packed.shape[:-1], slots)[..., :groups] == _E8M0_NAN_SCALE
decoded = values.reshape(*packed.shape[:-1], groups, SWA_KV_GROUP_SIZE)
# Native E4M3 anti-MX maps NaN scales to zero; retain the overflow signal.
decoded.masked_fill_(invalid_scale.unsqueeze(-1), float("nan"))
return decoded.reshape(*packed.shape[:-1], logical_width)
scale_bytes = _BF16_SCALE_BYTES * logical_width // SWA_KV_GROUP_SIZE
scales = packed[..., logical_width:logical_width + scale_bytes].contiguous().view(torch.bfloat16)
values = data.view(torch.float8_e4m3fn).to(torch.bfloat16)
return (values.reshape(*data.shape[:-1], logical_width // SWA_KV_GROUP_SIZE, SWA_KV_GROUP_SIZE)
* scales.unsqueeze(-1)).reshape(*data.shape[:-1], logical_width)
__all__ = ["quantize_swa_kv", "dequantize_swa_kv"]