Merged
feat(w4a16): 支持 Qwen3 Dense 和 MoE 权重量化推理 #145
feat(w4a16): 支持 Qwen3 Dense 和 MoE 权重量化推理 #145
Merged
chen_pengyuAdd on 7 days ago
Total: 21 files changed+1735-45
@@ -7,6 +7,7 @@
7- [Lightning Indexer](Lightning_Indexer_usage.md)7- [Lightning Indexer](Lightning_Indexer_usage.md)
8- [MXFP8 QAT (W8A16 / W8A8)](MXFP8_QAT_usage.md)8- [MXFP8 QAT (W8A16 / W8A8)](MXFP8_QAT_usage.md)
9- [W4A16 QAT](W4A16_QAT_usage.md)9- [W4A16 QAT](W4A16_QAT_usage.md)
10+- [W4A16 推理](W4A16_inference_usage.md)
10- [W4A8 QAT](W4A8_QAT_usage.md)11- [W4A8 QAT](W4A8_QAT_usage.md)
11 12 
12## EP 独立计算接口13## EP 独立计算接口
@@ -0,0 +1,92 @@
1+# W4A16 推理使用说明
2+ 
3+W4A16 推理使用 MXFP4 权重和 BF16 激活。按 [W4A16 QAT 使用说明](W4A16_QAT_usage.md) 完成训练后,将选定的 BF16 master 权重打包并保存。推理时从 checkpoint 还原已打包的权重,交给原模型结构执行前向。
4+ 
5+## 架构与使用约束
6+ 
7+- **Dense Linear** 使用 `W4A16DenseTensor`。权重沿输入维 K 打包,推理由 `nn.Linear` 分发到 NPU 融合权重量化矩阵乘。输入和 packed 权重需要位于同一张 NPU,激活使用 BF16。
8+- **融合 MoE 专家** 使用 `W4A16GMMTensor`。权重沿输出维打包,首次计算时反量化并在设备上缓存 BF16 权重,再执行 grouped matmul。部署时需为缓存预留显存。模型框架负责路由,以及输入 token 的分组和输出还原。
9+- 目标硬件为 **Ascend 950**,运行环境需要相应的 CANN 和 torch_npu 算子。Dense 要求 `K % 64 == 0`、`N % 8 == 0`,其中 K 为输入维、N 为输出维。两类权重的 block size 均为 32。
10+- MoE 导出要求成对提供融合的三维 `gate_up_proj` 和 `down_proj`。每组专家维度可为 `[E, N, K]` 或 `[E, K, N]`,由两组投影的形状共同确定布局。归一化后各投影的输出维需能被 32 整除,输入维需为偶数。
11+ 
12+## 接口与参数
13+ 
14+| 接口 | 用途 | 关键参数 |
15+| --- | --- | --- |
16+| `pack_checkpoint_weights(state, dense_names, expert_names, device)` | 在待导出的 CPU state dict 中,以 packed Tensor 替换选定的 BF16 权重 | `dense_names` 为 Linear 模块名列表;`expert_names` 为专家模块名到 hidden size 的映射;`device` 为打包用 NPU |
17+| `save_safetensors(state, output_dir, max_shard_size="5GB")` | 保存普通参数和 packed Tensor,必要时生成分片及索引 | 传入 checkpoint 目录,packed Tensor 的 state dict 键需要带模块前缀,例如 `linear.weight` |
18+| `load_safetensors(directory)` | 从单文件或分片 checkpoint 恢复 CPU state dict,使用 header 中的元数据重建 Tensor 子类 | 加载前导入 `torchao_ascend.features.inference.w4a16` 以完成 Tensor 类型注册 |
19+| `w4a16_grouped_matmul(x, weight, group_list, group_list_type=...)` | 执行一次专家 grouped matmul | `x` 是按专家排好的二维 BF16 token;每个专家对应一个分组值。类型 0 用累计结束位置,类型 1 用 token 数 |
20+ 
21+## 导出和推理示例
22+ 
23+以下示例用随机 BF16 权重演示接口。接入实际模型时,用训练完成后的 BF16 state dict 和对应的模块全名替换示例。FSDP2 训练需要先收集完整 CPU state dict,再由 rank 0 打包和保存。为每次导出使用新的输出目录。
24+ 
25+```python
26+from pathlib import Path
27+ 
28+import torch
29+from torch import nn
30+from torch.nn import functional as F
31+ 
32+from torchao_ascend.features.inference.w4a16 import (
33+ W4A16DenseTensor,
34+ W4A16GMMTensor,
35+ w4a16_grouped_matmul,
36+)
37+from torchao_ascend.features.qat.w4a16.weight_conversion import pack_checkpoint_weights
38+from torchao_ascend.serialization import load_safetensors, save_safetensors
39+ 
40+ 
41+class ExampleModel(nn.Module):
42+ def __init__(self, device):
43+ super().__init__()
44+ self.linear = nn.Linear(128, 128, dtype=torch.bfloat16, device=device)
45+ self.experts = nn.Module()
46+ self.experts.gate_up_proj = nn.Parameter(
47+ torch.empty(4, 128, 128, dtype=torch.bfloat16, device=device)
48+ )
49+ self.experts.down_proj = nn.Parameter(
50+ torch.empty(4, 128, 64, dtype=torch.bfloat16, device=device)
51+ )
52+ 
53+ 
54+device = torch.device("npu:0")
55+checkpoint = Path("w4a16-example")
56+if checkpoint.exists():
57+ raise FileExistsError(checkpoint)
58+ 
59+master = ExampleModel(device="cpu")
60+with torch.no_grad():
61+ master.experts.gate_up_proj.normal_(std=0.05)
62+ master.experts.down_proj.normal_(std=0.05)
63+state = master.state_dict()
64+pack_checkpoint_weights(state, ["linear"], {"experts": 128}, device)
65+save_safetensors(state, checkpoint)
66+ 
67+model = ExampleModel(device="meta")
68+model.load_state_dict(load_safetensors(checkpoint), strict=True, assign=True)
69+model.eval().requires_grad_(False)
70+model.to(device)
71+assert isinstance(model.linear.weight, W4A16DenseTensor)
72+assert isinstance(model.experts.gate_up_proj, W4A16GMMTensor)
73+assert isinstance(model.experts.down_proj, W4A16GMMTensor)
74+ 
75+with torch.inference_mode():
76+ tokens = torch.randn(10, 128, dtype=torch.bfloat16, device=device)
77+ dense_output = model.linear(tokens)
78+ 
79+ # 示例 token 已按专家排列。第二个专家没有收到 token。
80+ counts = [3, 0, 5, 2]
81+ gate_up = w4a16_grouped_matmul(
82+ tokens, model.experts.gate_up_proj, counts, group_list_type=1
83+ )
84+ gate, up = gate_up.chunk(2, dim=-1)
85+ moe_output = w4a16_grouped_matmul(
86+ F.silu(gate) * up, model.experts.down_proj, counts, group_list_type=1
87+ )
88+ 
89+assert dense_output.shape == moe_output.shape == (10, 128)
90+```
91+ 
92+接入框架模型时,用与训练一致的模型配置和参数名创建推理模型。加载 packed state dict 时使用 `assign=True`,以保留 Tensor 子类。完整模型的配置、tokenizer 和 MoE 路由由模型框架管理。推理使用加载后的 packed 权重,可以直接进入 `torch.inference_mode()`。
@@ -0,0 +1,118 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd.
wanglijun55
wanglijun55wanglijun553 days ago

资料应该也得同步改,是打算在后续PR合入吗

likedislike
2+ 
3+"""Compare real NPU W4A16 inference against the corresponding QAT math."""
4+ 
5+from functools import partial
6+ 
7+import pytest
8+import torch
9+ 
10+from torchao_ascend.features.inference.w4a16 import (
11+ W4A16DenseTensor,
12+ W4A16GMMTensor,
13+ w4a16_grouped_matmul,
14+)
15+from torchao_ascend.features.qat.w4a16 import (
16+ W4A16GMM,
17+ W4A16Linear,
18+)
19+from torchao_ascend.features.qat.w4a16.fakequant_rebuild import rebuild_weight_fakequant
20+from torchao_ascend.features.qat.w4a16.weight_conversion import pack_checkpoint_weights
21+from torchao_ascend.ops.npu import dynamic_mx_quant, swiglu
22+from torchao_ascend.serialization import load_safetensors, save_safetensors
23+ 
24+ 
25+@pytest.fixture
26+def npu_device():
27+ if not torch.npu.is_available() or not hasattr(torch, "float4_e2m1fn_x2"):
28+ pytest.skip("Requires an Ascend NPU with MXFP4 support")
29+ torch.manual_seed(2026)
30+ return torch.device("npu")
31+ 
32+ 
33+def assert_bf16_forward_close(actual, expected):
34+ assert actual.shape == expected.shape
35+ assert actual.dtype == expected.dtype == torch.bfloat16
36+ assert torch.isfinite(actual).all()
37+ relative_l2 = (actual.float() - expected.float()).norm() / expected.float().norm()
38+ # Native inference and QAT can use different BF16 rounding paths.
39+ assert relative_l2.item() < 0.01
40+ 
41+ 
42+@pytest.mark.parametrize("bias", [False, True])
43+def test_dense_inference_matches_qat(npu_device, bias, tmp_path):
44+ linear = torch.nn.Linear(
45+ 256, 128, bias=bias, dtype=torch.bfloat16, device=npu_device
46+ ).eval()
47+ x = torch.randn(2, 16, 256, dtype=torch.bfloat16, device=npu_device)
48+ master = linear.weight.detach()
49+ data, scale = dynamic_mx_quant(
50+ master, axis=-1, dst_type=torch.float4_e2m1fn_x2, block_size=32,
51+ )
52+ W4A16Linear.from_float(linear)
53+ expected = linear(x).detach()
54+ 
55+ state = {f"linear.{key}": weight.cpu() for key, weight in linear.state_dict().items()}
56+ pack_checkpoint_weights(state, ["linear"], {}, npu_device)
57+ save_safetensors(state, tmp_path)
58+ state = load_safetensors(tmp_path)
59+ linear = torch.nn.Linear(256, 128, bias=bias, dtype=torch.bfloat16, device="meta")
60+ linear.load_state_dict({key.split(".", 1)[1]: value for key, value in state.items()}, assign=True)
61+ linear = linear.to(npu_device).eval()
62+ assert isinstance(linear.weight, W4A16DenseTensor)
63+ assert type(linear) is torch.nn.Linear
64+ torch.testing.assert_close(
65+ linear.weight.packed_k, data.contiguous().view(torch.uint8).reshape(128, 128),
66+ atol=0, rtol=0, check_stride=True,
67+ )
68+ torch.testing.assert_close(
69+ linear.weight.scale.view(torch.uint8),
70+ scale.view(torch.uint8).reshape(128, -1),
71+ atol=0,
72+ rtol=0,
73+ )
74+ with torch.inference_mode():
75+ actual = linear(x)
76+ assert_bf16_forward_close(actual, expected)
77+ torch.testing.assert_close(linear(x.flatten(0, 1)), actual.flatten(0, 1), atol=0, rtol=0)
78+ 
79+ 
80+class Experts(torch.nn.Module):
81+ def __init__(self, gate_up, down):
82+ super().__init__()
83+ self.num_experts = 4
84+ self.hidden_size = 128
85+ self.gate_up_proj = torch.nn.Parameter(gate_up)
86+ self.down_proj = torch.nn.Parameter(down)
87+ 
88+ 
89+def test_moe_inference_matches_qat_with_empty_expert(npu_device, tmp_path):
90+ gate_up = torch.randn(4, 128, 128, dtype=torch.bfloat16, device=npu_device) * 0.05
91+ down = torch.randn(4, 128, 64, dtype=torch.bfloat16, device=npu_device) * 0.05
92+ experts = Experts(gate_up, down).eval()
93+ counts = torch.tensor([3, 0, 5, 2], dtype=torch.int64, device=npu_device)
94+ offsets = counts.cumsum(0)
95+ x = torch.randn(10, 128, dtype=torch.bfloat16, device=npu_device)
96+ W4A16GMM.from_float(experts)
97+ expected = experts.ep_forward(x, counts).detach()
98+ 
99+ state = {"experts.gate_up_proj": gate_up.cpu(), "experts.down_proj": down.cpu()}
100+ pack_checkpoint_weights(state, [], {"experts": experts.hidden_size}, npu_device)
101+ save_safetensors(state, tmp_path)
102+ state = load_safetensors(tmp_path)
103+ gate_weight = state["experts.gate_up_proj"].to(npu_device)
104+ down_weight = state["experts.down_proj"].to(npu_device)
105+ quantizer = partial(
106+ dynamic_mx_quant, round_mode="rint", scale_alg=0, dst_type=torch.float4_e2m1fn_x2,
107+ )
108+ for converted, master in ((gate_weight, gate_up), (down_weight, down)):
109+ assert isinstance(converted, W4A16GMMTensor)
110+ reference = rebuild_weight_fakequant(master, quantizer=quantizer, block_size=32)
111+ torch.testing.assert_close(converted.dequantize(), reference, atol=0, rtol=0)
112+ 
113+ with torch.inference_mode():
114+ fc1 = w4a16_grouped_matmul(x, gate_weight, offsets, group_list_type=0)
115+ actual = w4a16_grouped_matmul(
116+ swiglu(fc1, dim=-1), down_weight, offsets, group_list_type=0,
117+ )
118+ assert_bf16_forward_close(actual, expected)
@@ -8,11 +8,12 @@ dtypes are translated to the torch_npu codes.
8"""8"""
9import torch9import torch
10 10 
11+from torchao_ascend.ops import dispatch_op
11from torchao_ascend.ops.npu import mx_ops12from torchao_ascend.ops.npu import mx_ops
12 13 
13 14 
14class _Recorder:15class _Recorder:
15- """Capture the arguments the wrapper forwards to ``npu_quant_matmul``."""16+ """Capture the arguments forwarded to an NPU kernel."""
16 17 
17 def __init__(self):18 def __init__(self):
18 self.calls = []19 self.calls = []
@@ -22,6 +23,24 @@ class _Recorder:
22 return torch.zeros(1)23 return torch.zeros(1)
23 24 
24 25 
26+def test_weight_quant_batchmatmul_forwards_npu_abi(monkeypatch):
27+ recorder = _Recorder()
28+ monkeypatch.setattr(mx_ops.torch_npu, "npu_weight_quant_batchmatmul", recorder, raising=False)
29+ x = torch.zeros((4, 64), dtype=torch.bfloat16)
30+ weight = torch.zeros((32, 8), dtype=torch.uint8)
31+ scale = torch.full((2, 8), 127, dtype=torch.uint8).view(torch.float8_e8m0fnu)
32+ bias = torch.zeros(8, dtype=torch.bfloat16)
33+ 
34+ dispatch_op("weight_quant_batchmatmul", x, weight, scale, bias, 32, backend="npu", weight_dtype=7)
35+ 
36+ [(args, kwargs)] = recorder.calls
37+ assert args[0] is x and args[1] is weight and args[2] is scale
38+ assert args[3:6] == (None, None, None)
39+ assert args[6] is bias
40+ assert args[7:] == (32, 0)
41+ assert kwargs == {"weight_dtype": 7}
42+ 
43+ 
25def test_fp8_form_matches_pre_merge_arguments(monkeypatch):44def test_fp8_form_matches_pre_merge_arguments(monkeypatch):
26 """The FP8 form sends exactly the argument set it sent before the merge."""45 """The FP8 form sends exactly the argument set it sent before the merge."""
27 recorder = _Recorder()46 recorder = _Recorder()
@@ -94,9 +94,10 @@ def test_fp8_save_and_reload_round_trip():
94 assert f8.dtype == original.dtype94 assert f8.dtype == original.dtype
95 95 
96 96 
97-def test_plain_tensor_passes_through():97+@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
98- param = torch.nn.Parameter(torch.randn(8, 8))98+def test_plain_tensor_passes_through(dtype):
99- tensors = {"model.head.bias": torch.randn(8), "model.head.weight": param}99+ param = torch.nn.Parameter(torch.randn(8, 8, dtype=dtype))
100+ tensors = {"model.head.bias": torch.randn(8, dtype=dtype), "model.head.weight": param}
100 state_dict, shard_names, _ = _save_and_reload(tensors)101 state_dict, shard_names, _ = _save_and_reload(tensors)
101 assert shard_names == ["model.safetensors"]102 assert shard_names == ["model.safetensors"]
102 torch.testing.assert_close(state_dict["model.head.weight"], param.detach())103 torch.testing.assert_close(state_dict["model.head.weight"], param.detach())
@@ -26,14 +26,16 @@ from functools import partial
26 26 
27import pytest27import pytest
28import torch28import torch
29- 
30from torchao.quantization import quantize_29from torchao.quantization import quantize_
31 30 
32import torchao_ascend.features.qat.w4a16.w4a16_gmm as w4a16_gmm_module31import torchao_ascend.features.qat.w4a16.w4a16_gmm as w4a16_gmm_module
33import torchao_ascend.features.qat.w4a16.w4a16_linear as w4a16_linear_module32import torchao_ascend.features.qat.w4a16.w4a16_linear as w4a16_linear_module
34from torchao_ascend.features.qat import w4a1633from torchao_ascend.features.qat import w4a16
35from torchao_ascend.features.qat.w4a16 import fakequant_rebuild as w4a16_fakequant_rebuild34from torchao_ascend.features.qat.w4a16 import fakequant_rebuild as w4a16_fakequant_rebuild
36-from torchao_ascend.features.qat.w4a16.config import _w4a16_gmm_transform, _w4a16_linear_transform35+from torchao_ascend.features.qat.w4a16.config import (
36+ _w4a16_gmm_transform,
37+ _w4a16_linear_transform,
38+)
37from torchao_ascend.ops.npu import get_float4_dtype39from torchao_ascend.ops.npu import get_float4_dtype
38 40 
39 41 
@@ -505,7 +507,7 @@ class TestW4A16InjectionContract:
505 def test_reference_shell_clears_on_optimizer_step(self):507 def test_reference_shell_clears_on_optimizer_step(self):
506 ref = _ReferenceCachedFakeQuant()508 ref = _ReferenceCachedFakeQuant()
507 param = torch.nn.Parameter(torch.randn(4, 4))509 param = torch.nn.Parameter(torch.randn(4, 4))
508- optimizer = torch.optim.SGD([param], lr=1e-3)510+ optimizer = torch.optim.SGD([param], lr=1e-3, foreach=False)
509 511 
510 weight = torch.randn(16, 32, dtype=torch.bfloat16)512 weight = torch.randn(16, 32, dtype=torch.bfloat16)
511 ref(weight, _fake_weight_rebuild, bias=None, block_size=32)513 ref(weight, _fake_weight_rebuild, bias=None, block_size=32)
@@ -544,9 +546,39 @@ class TestW4A16GMMForwardLayout:
544 after the internal .T), never as the raw framework layout.546 after the internal .T), never as the raw framework layout.
545 """547 """
546 548 
549+ def test_prepares_staged_down_weight_after_activation(self, monkeypatch):
550+ e, k, n = 4, 128, 64
551+ gmm = w4a16.W4A16GMM.from_float(_LayoutExperts(e, k, n, in_first=False))
552+ staged_down = gmm.down_proj.reshape(k, e * n)
553+ events = []
554+ 
555+ def grouped(x, weight, **kwargs):
556+ events.append(tuple(weight.shape))
557+ return x @ weight[0].t()
558+ 
559+ def activate(fc1):
560+ events.append("activation")
561+ return fc1[:, :n]
562+ 
563+ def prepare_down(weight):
564+ events.append("prepare_down")
565+ assert weight is staged_down
566+ return weight.reshape(e, k, n)
567+ 
568+ monkeypatch.setattr(w4a16_gmm_module, "mx_quant_group_gemm", grouped)
569+ x = torch.randn(4, k, dtype=torch.bfloat16)
570+ actual = gmm.experts_forward(
571+ x, torch.tensor([4, 0, 0, 0]), activation_fn=activate,
572+ down_weight=staged_down, prepare_down_fn=prepare_down,
573+ )
574+ expected = (x @ gmm.gate_up_proj[0].t())[:, :n] @ gmm.down_proj[0].t()
575+ torch.testing.assert_close(actual, expected, atol=0, rtol=0)
576+ assert events == [(e, 2 * n, k), "activation", "prepare_down", (e, k, n)]
577+ 
547 @pytest.mark.parametrize("in_first", [True, False])578 @pytest.mark.parametrize("in_first", [True, False])
548- def test_forward_normalizes_both_layouts(self, monkeypatch, in_first):579+ @pytest.mark.parametrize("n", [8, 16])
549- e, k, n = 2, 32, 8580+ def test_forward_normalizes_both_layouts(self, monkeypatch, in_first, n):
581+ e, k = 2, 32
550 config = w4a16.W4A16GMMConfig(weight_fakequant_fn=_passthrough_fakequant)582 config = w4a16.W4A16GMMConfig(weight_fakequant_fn=_passthrough_fakequant)
551 gmm = w4a16.W4A16GMM.from_float(_LayoutExperts(e, k, n, in_first), config=config)583 gmm = w4a16.W4A16GMM.from_float(_LayoutExperts(e, k, n, in_first), config=config)
552 584 
@@ -717,3 +749,109 @@ class TestW4A16QuantizeWorkflow:
717 assert callable(block.experts.experts_forward)749 assert callable(block.experts.experts_forward)
718 assert model.layers[0].mlp.weight is mlp_weight750 assert model.layers[0].mlp.weight is mlp_weight
719 assert model.layers[0].experts.gate_up_proj is gate_up751 assert model.layers[0].experts.gate_up_proj is gate_up
752+ 
753+ 
754+class TestW4A16StepField:
755+ """Check the default step and its propagation through ``from_linear``."""
756+ 
757+ def test_default_step_is_prepare(self):
758+ assert w4a16.W4A16LinearConfig().step == "prepare"
759+ assert w4a16.W4A16GMMConfig().step == "prepare"
760+ 
761+ def test_preserves_legacy_positional_arguments(self):
762+ legacy_args = ("W4A16", 32, _passthrough_fakequant, ["ignored"], ["applied"])
763+ linear = w4a16.W4A16LinearConfig(*legacy_args)
764+ gmm = w4a16.W4A16GMMConfig(*legacy_args, "in_first", step="prepare")
765+ 
766+ for config in (linear, gmm):
767+ assert config.weight_fakequant_fn is _passthrough_fakequant
768+ assert config.w4a16_ignored_modules == ["ignored"]
769+ assert config.w4a16_apply_modules == ["applied"]
770+ assert linear.step == "prepare"
771+ assert gmm.weight_layout == "in_first"
772+ assert gmm.step == "prepare"
773+ 
774+ def test_invalid_step_rejected(self):
775+ with pytest.raises(ValueError, match="step must be"):
776+ w4a16.W4A16LinearConfig(step="convert")
777+ 
778+ def test_from_linear_copies_step(self):
779+ base = w4a16.W4A16LinearConfig(step="prepare")
780+ assert w4a16.W4A16GMMConfig.from_linear(base).step == "prepare"
781+ 
782+ 
783+class TestW4A16PrepareRegression:
784+ """Check exact agreement between implicit and explicit prepare steps."""
785+ 
786+ @staticmethod
787+ def _linear_pair():
788+ torch.manual_seed(0)
789+ first = torch.nn.Linear(16, 8, bias=True, dtype=torch.bfloat16)
790+ torch.manual_seed(0)
791+ second = torch.nn.Linear(16, 8, bias=True, dtype=torch.bfloat16)
792+ return first, second
793+ 
794+ @staticmethod
795+ def _assert_same_module(actual, expected):
796+ assert type(actual) is type(expected)
797+ assert list(actual.state_dict()) == list(expected.state_dict())
798+ for (name_a, ten_a), (name_b, ten_b) in zip(
799+ actual.state_dict().items(), expected.state_dict().items()
800+ ):
801+ assert name_a == name_b
802+ assert torch.equal(ten_a, ten_b), name_a
803+ 
804+ def test_linear_prepare_default_equals_explicit(self):
805+ first, second = self._linear_pair()
806+ kwargs = {"weight_fakequant_fn": _passthrough_fakequant}
807+ default_mod = _w4a16_linear_transform(
808+ first, config=w4a16.W4A16LinearConfig(**kwargs)
809+ )
810+ prepare_mod = _w4a16_linear_transform(
811+ second, config=w4a16.W4A16LinearConfig(step="prepare", **kwargs)
812+ )
813+ 
814+ self._assert_same_module(default_mod, prepare_mod)
815+ x = torch.randn(4, 16, dtype=torch.bfloat16)
816+ assert torch.equal(default_mod(x), prepare_mod(x))
817+ 
818+ def test_gmm_prepare_default_equals_explicit(self, monkeypatch):
819+ def fake_grouped_matmul(xs, weights, **kwargs):
820+ x = xs[0]
821+ bounds = [0, *kwargs["group_list"].tolist()]
822+ return [
823+ torch.cat(
824+ [
825+ x[bounds[i] : bounds[i + 1]] @ weights[i]
826+ for i in range(len(bounds) - 1)
827+ ]
828+ )
829+ ]
830+ 
831+ monkeypatch.setattr(w4a16_gmm_module, "mx_grouped_matmul", fake_grouped_matmul)
832+ monkeypatch.setattr(w4a16_gmm_module, "permute", lambda x, idx: (x, None))
833+ monkeypatch.setattr(
834+ w4a16_gmm_module, "swiglu", lambda x, dim=-1: x.chunk(2, dim=dim)[0]
835+ )
836+ monkeypatch.setattr(w4a16_gmm_module, "unpermute", lambda x, m, probs=None: x)
837+ 
838+ torch.manual_seed(0)
839+ first = _LayoutExperts(2, 32, 8, in_first=False)
840+ torch.manual_seed(0)
841+ second = _LayoutExperts(2, 32, 8, in_first=False)
842+ kwargs = {"weight_fakequant_fn": _passthrough_fakequant}
843+ default_mod = _w4a16_gmm_transform(
844+ first, config=w4a16.W4A16GMMConfig(**kwargs)
845+ )
846+ prepare_mod = _w4a16_gmm_transform(
847+ second, config=w4a16.W4A16GMMConfig(step="prepare", **kwargs)
848+ )
849+ 
850+ self._assert_same_module(default_mod, prepare_mod)
851+ t = 4
852+ x = torch.randn(t, 32, dtype=torch.bfloat16)
853+ topk_idx = torch.zeros(t, 1, dtype=torch.int64)
854+ probs = torch.ones(t, 1)
855+ assert torch.equal(
856+ default_mod(x, topk_idx, probs), prepare_mod(x, topk_idx, probs)
857+ )
@@ -0,0 +1,384 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd. All rights reserved.
2+"""CPU tests for AO-style W4A16 dense and grouped Tensor subclasses."""
3+import io
4+import json
5+ 
6+import pytest
7+import torch
8+from safetensors import safe_open
9+ 
10+import torchao_ascend.features.inference.w4a16.w4a16_gmm as gmm_module
11+from torchao_ascend.features.inference.w4a16 import (
12+ W4A16DenseTensor,
13+ W4A16GMMTensor,
14+ w4a16_grouped_matmul,
15+)
16+from torchao_ascend.features.qat.w4a16 import W4A16Linear
17+from torchao_ascend.features.qat.w4a16.w4a16_gmm import resolve_expert_layout
18+from torchao_ascend.ops import registry
19+from torchao_ascend.serialization import load_safetensors, safetensors_checkpoint_size, save_safetensors
20+ 
21+ 
22+def _dense_tensor(n=8, k=64):
23+ return W4A16DenseTensor.from_packed(
24+ torch.zeros((n, k // 2), dtype=torch.uint8),
25+ torch.full((n, k // 32), 127, dtype=torch.uint8).view(torch.float8_e8m0fnu),
26+ torch.Size((n, k)),
27+ torch.bfloat16,
28+ weight_dtype=7,
29+ )
30+ 
31+ 
32+def _gmm_tensor(e=2, n=32, k=64, layout="out_first", fill=0):
33+ orig_shape = (e, k, n) if layout == "in_first" else (e, n, k)
34+ return W4A16GMMTensor.from_packed(
35+ torch.full((e, k, n // 2), fill, dtype=torch.uint8),
36+ torch.full((e, n // 32, k), 127, dtype=torch.uint8),
37+ torch.Size((e, n, k)),
38+ torch.Size(orig_shape),
39+ torch.bfloat16,
40+ layout,
41+ )
42+ 
43+ 
44+def _fake_grouped_matmul(xs, weights, **kwargs):
45+ x = xs[0]
46+ group_list = kwargs["group_list"].tolist()
47+ if kwargs["group_list_type"] == 0:
48+ counts = [group_list[0], *torch.diff(torch.tensor(group_list)).tolist()]
49+ else:
50+ counts = group_list
51+ outputs = []
52+ start = 0
53+ for count, weight in zip(counts, weights):
54+ end = start + count
55+ outputs.append(x[start:end] @ weight)
56+ start = end
57+ assert start == x.shape[0]
58+ return [torch.cat(outputs, dim=0)]
59+ 
60+ 
61+class TestW4A16DenseTensor:
62+ def test_linear_dispatch_preserves_packed_layout_and_shape(self, monkeypatch):
63+ weight = _dense_tensor(n=8, k=64)
64+ linear = torch.nn.Linear(64, 8, bias=True, dtype=torch.bfloat16)
65+ linear.weight = torch.nn.Parameter(weight, requires_grad=False)
66+ calls = []
67+ 
68+ def fake_npu(x, qdata, scale, bias, block_size, *, weight_dtype):
69+ calls.append((x, qdata, scale, bias, block_size, weight_dtype))
70+ return torch.zeros((x.shape[0], 8), dtype=x.dtype)
71+ 
72+ monkeypatch.setitem(registry._OPERATOR_REGISTRY["weight_quant_batchmatmul"], "npu", fake_npu)
73+ x = torch.randn(2, 3, 64, dtype=torch.bfloat16)
74+ out = linear(x)
75+ 
76+ assert out.shape == (2, 3, 8)
77+ assert len(calls) == 1
78+ call = calls[0]
79+ assert call[0].shape == (6, 64)
80+ assert weight.packed_k.is_contiguous() and weight.scale.is_contiguous()
81+ assert call[1].data_ptr() == weight.packed_k.data_ptr()
82+ assert call[2].data_ptr() == weight.scale.data_ptr()
83+ assert call[1].shape == (32, 8) and call[1].stride() == (1, 32)
84+ assert call[2].shape == (2, 8) and call[2].stride() == (1, 2)
85+ assert call[3] is linear.bias
86+ assert call[4:] == (32, 7)
87+ 
88+ def test_linear_dispatch_supports_keyword_arguments(self, monkeypatch):
89+ weight = _dense_tensor(n=8, k=64)
90+ calls = []
91+ 
92+ def fake_npu(x, qdata, scale, bias, block_size, *, weight_dtype):
93+ calls.append(weight_dtype)
94+ return torch.zeros((x.shape[0], 8), dtype=x.dtype)
95+ 
96+ monkeypatch.setitem(registry._OPERATOR_REGISTRY["weight_quant_batchmatmul"], "npu", fake_npu)
97+ x = torch.randn(4, 64, dtype=torch.bfloat16)
98+ out = torch.ops.aten.linear.default(input=x, weight=weight)
99+ assert out.shape == (4, 8)
100+ assert calls == [7]
101+ 
102+ def test_weights_only_serialization_roundtrip(self):
103+ weight = _dense_tensor()
104+ buffer = io.BytesIO()
105+ torch.save(weight, buffer)
106+ buffer.seek(0)
107+ loaded = torch.load(buffer, weights_only=True)
108+ assert isinstance(loaded, W4A16DenseTensor)
109+ assert loaded.orig_shape == weight.orig_shape
110+ assert loaded.orig_dtype == torch.bfloat16
111+ assert loaded.weight_dtype == 7
112+ assert torch.equal(loaded.packed_k, weight.packed_k)
113+ assert torch.equal(loaded.scale.view(torch.uint8), weight.scale.view(torch.uint8))
114+ 
115+ def test_state_dict_assign_and_prepare_with_packed_weights_rejected(self):
116+ source = torch.nn.Linear(64, 8, bias=True, dtype=torch.bfloat16)
117+ source.weight = torch.nn.Parameter(_dense_tensor(), requires_grad=False)
118+ state = source.state_dict()
119+ 
120+ target = torch.nn.Linear(64, 8, bias=True, dtype=torch.bfloat16)
121+ target.load_state_dict(state, strict=True, assign=True)
122+ assert isinstance(target.weight, W4A16DenseTensor)
123+ assert torch.equal(target.weight.packed_k, source.weight.packed_k)
124+ 
125+ converted = torch.nn.Linear(64, 8, bias=True, dtype=torch.bfloat16)
126+ converted.weight = torch.nn.Parameter(_dense_tensor(), requires_grad=False)
127+ converted.load_state_dict(state, strict=True, assign=False)
128+ assert isinstance(converted.weight, W4A16DenseTensor)
129+ assert torch.equal(converted.weight.packed_k, source.weight.packed_k)
130+ with pytest.raises(RuntimeError, match="Cannot prepare packed W4A16 weights for QAT"):
131+ W4A16Linear.from_float(converted)
132+ 
133+ 
134+class TestW4A16GMMTensor:
135+ @pytest.mark.parametrize(
136+ ("gate_up", "down", "explicit", "expected"),
137+ [
138+ ((2, 64, 128), (2, 128, 32), None, 128),
139+ ((2, 128, 64), (2, 32, 128), None, 128),
140+ ((2, 64, 64), (2, 32, 64), None, 64),
141+ ((2, 64, 128), (2, 128, 32), 128, 128),
142+ ],
143+ ids=("out_first", "in_first", "square_gate_up", "explicit_hidden_size"),
144+ )
145+ def test_infer_hidden_size_from_paired_shapes(self, gate_up, down, explicit, expected):
146+ assert resolve_expert_layout(gate_up, down, hidden_size=explicit)[0] == expected
147+ 
148+ def test_infer_hidden_size_rejects_incompatible_shapes(self):
149+ with pytest.raises(ValueError):
150+ resolve_expert_layout((2, 64, 128), (2, 64, 128))
151+ 
152+ @pytest.mark.parametrize("layout", ["out_first", "in_first"])
153+ def test_dequantize_layout_and_shared_cache(self, monkeypatch, layout):
154+ calls = []
155+ real_dequant = gmm_module.dequant_out_axis
156+ 
157+ def counting_dequant(qdata, scale):
158+ calls.append(1)
159+ return real_dequant(qdata, scale)
160+ 
161+ monkeypatch.setattr(gmm_module, "dequant_out_axis", counting_dequant)
162+ weight = _gmm_tensor(layout=layout)
163+ expected_shape = (2, 64, 32) if layout == "in_first" else (2, 32, 64)
164+ 
165+ first = weight.dequantize()
166+ second = weight.dequantize()
167+ assert first.shape == expected_shape
168+ assert first.dtype == torch.bfloat16
169+ assert len(calls) == 1
170+ assert first.data_ptr() == second.data_ptr()
171+ 
172+ def test_grouped_adapter_and_aten_entry(self, monkeypatch):
173+ monkeypatch.setitem(registry._OPERATOR_REGISTRY["mx_grouped_matmul"], "npu", _fake_grouped_matmul)
174+ weight = _gmm_tensor(layout="in_first")
175+ x = torch.randn(5, 64, dtype=torch.bfloat16)
176+ counts = torch.tensor([2, 3], dtype=torch.int64)
177+ offsets = counts.cumsum(0)
178+ 
179+ by_counts = w4a16_grouped_matmul(x, weight, counts, group_list_type=1)
180+ by_offsets = w4a16_grouped_matmul(x, weight, offsets, group_list_type=0)
181+ by_aten = torch.ops.aten._grouped_mm.default(x, weight, offsets)
182+ by_aten_kwargs = torch.ops.aten._grouped_mm.default(
183+ self=x, mat2=weight, offs=offsets
184+ )
185+ 
186+ assert by_counts.shape == (5, 32)
187+ assert torch.equal(by_counts, by_offsets)
188+ assert torch.equal(by_counts, by_aten)
189+ assert torch.equal(by_counts, by_aten_kwargs)
190+ empty = w4a16_grouped_matmul(
191+ x.new_empty((0, 64)), weight, torch.zeros(2, dtype=torch.int64),
192+ group_list_type=1,
193+ )
194+ assert empty.shape == (0, 32)
195+ 
196+ def test_copy_invalidates_cache_and_serialization_omits_it(self):
197+ target = _gmm_tensor()
198+ target._grouped_weight()
199+ assert target._grouped_weight_cache is not None
200+ 
201+ source = _gmm_tensor(fill=1)
202+ target.copy_(source)
203+ assert target._grouped_weight_cache is None
204+ assert torch.equal(target.qdata, source.qdata)
205+ 
206+ target._grouped_weight()
207+ buffer = io.BytesIO()
208+ torch.save(target, buffer)
209+ buffer.seek(0)
210+ loaded = torch.load(buffer, weights_only=True)
211+ assert isinstance(loaded, W4A16GMMTensor)
212+ assert loaded._grouped_weight_cache is None
213+ assert torch.equal(loaded.qdata, target.qdata)
214+ assert torch.equal(loaded.scale, target.scale)
215+ 
216+ @pytest.mark.parametrize("wrapped", [False, True])
217+ def test_qwen3_routed_forward_uses_two_grouped_projections(self, monkeypatch, wrapped):
218+ class Qwen3MoeExperts(torch.nn.Module):
219+ def __init__(self):
220+ super().__init__()
221+ self.num_experts = 3
222+ self.hidden_dim = 64
223+ self.gate_up_proj = torch.nn.Parameter(torch.zeros(3, 64, 64, dtype=torch.bfloat16))
224+ self.down_proj = torch.nn.Parameter(torch.zeros(3, 32, 64, dtype=torch.bfloat16))
225+ 
226+ def forward(self, hidden_states, top_k_index, top_k_weights):
227+ raise AssertionError("Qwen3 eager expert loop was called")
228+ 
229+ monkeypatch.setattr(
230+ Qwen3MoeExperts, "__module__", "transformers.models.qwen3_moe.modeling_qwen3_moe"
231+ )
232+ 
233+ offsets = []
234+ 
235+ def grouped(xs, weights, **kwargs):
236+ offsets.append(kwargs["group_list"].tolist())
237+ return _fake_grouped_matmul(xs, weights, **kwargs)
238+ 
239+ def permute(x, selected):
240+ order = selected.flatten().argsort(stable=True)
241+ return x[order // selected.shape[1]], order
242+ 
243+ def unpermute(y, order, probs):
244+ return (y[order.argsort()].reshape(*probs.shape, -1) * probs[..., None]).sum(1)
245+ 
246+ def swiglu(x, dim):
247+ gate, up = x.chunk(2, dim=dim)
248+ return torch.nn.functional.silu(gate) * up
249+ 
250+ monkeypatch.setitem(registry._OPERATOR_REGISTRY["mx_grouped_matmul"], "npu", grouped)
251+ monkeypatch.setitem(registry._OPERATOR_REGISTRY["permute"], "npu", permute)
252+ monkeypatch.setitem(registry._OPERATOR_REGISTRY["unpermute"], "npu", unpermute)
253+ monkeypatch.setitem(registry._OPERATOR_REGISTRY["swiglu"], "npu", swiglu)
254+ 
255+ experts = Qwen3MoeExperts().eval()
256+ if wrapped:
257+ experts._hf_hook = object()
258+ experts._old_forward = experts.forward
259+ experts.forward = lambda *args: experts._old_forward(*args)
260+ wrapped_forward = experts.forward
261+ gate = _gmm_tensor(e=3, n=64, k=64, layout="in_first")
262+ down = _gmm_tensor(e=3, n=64, k=32, layout="in_first")
263+ for weight in (gate, down):
264+ for index, codes in enumerate(weight.qdata):
265+ codes.fill_(0x22 + index * 0x11)
266+ experts.load_state_dict({"gate_up_proj": gate, "down_proj": down}, assign=True)
267+ gmm_module._install_qwen3_grouped_forward(experts)
268+ assert type(experts) is Qwen3MoeExperts
269+ if wrapped:
270+ assert experts.forward is wrapped_forward
271+ assert experts.gate_up_proj.weight_layout == "in_first"
272+ 
273+ x = torch.full((2, 64), 0.25, dtype=torch.bfloat16)
274+ selected = torch.tensor([[2, 0], [0, 2]])
275+ probs = torch.tensor([[0.25, 0.75], [0.5, 0.5]], dtype=torch.bfloat16)
276+ actual = experts(x, selected, probs)
277+ gate_up = experts.gate_up_proj.dequantize()
278+ down = experts.down_proj.dequantize()
279+ expected = torch.stack([
280+ torch.stack([
281+ (swiglu(x[token] @ gate_up[expert], -1) @ down[expert]) * prob
282+ for expert, prob in zip(selected[token], probs[token])
283+ ]).sum(0)
284+ for token in range(x.shape[0])
285+ ])
286+ assert offsets == [[2, 2, 4], [2, 2, 4]]
287+ torch.testing.assert_close(actual, expected, rtol=0, atol=0)
288+ 
289+ def test_hf_fallback_and_group_list_validation(self):
290+ weight = _gmm_tensor()
291+ assert weight[0].shape == (32, 64)
292+ assert weight[0].dtype == torch.bfloat16
293+ assert weight.sum().shape == ()
294+ assert weight.transpose(1, 2).shape == (2, 64, 32)
295+ 
296+ x = torch.randn(5, 64, dtype=torch.bfloat16)
297+ with pytest.raises(ValueError, match="nonnegative groups totaling"):
298+ w4a16_grouped_matmul(
299+ x, weight, torch.tensor([2, 2]), group_list_type=1
300+ )
301+ with pytest.raises(ValueError, match="group_list_type"):
302+ w4a16_grouped_matmul(
303+ x, weight, torch.tensor([2, 3]), group_list_type=2
304+ )
305+ 
306+ def test_gmm_state_dict_weights_only_roundtrip(self):
307+ source = torch.nn.Module()
308+ source.gate_up_proj = torch.nn.Parameter(_gmm_tensor(), requires_grad=False)
309+ source.down_proj = torch.nn.Parameter(_gmm_tensor(), requires_grad=False)
310+ state = source.state_dict()
311+ buffer = io.BytesIO()
312+ torch.save(state, buffer)
313+ buffer.seek(0)
314+ loaded_state = torch.load(buffer, weights_only=True)
315+ 
316+ target = torch.nn.Module()
317+ target.gate_up_proj = torch.nn.Parameter(
318+ torch.empty(2, 32, 64, dtype=torch.bfloat16)
319+ )
320+ target.down_proj = torch.nn.Parameter(
321+ torch.empty(2, 32, 64, dtype=torch.bfloat16)
322+ )
323+ target.load_state_dict(loaded_state, strict=True, assign=True)
324+ assert isinstance(target.gate_up_proj, W4A16GMMTensor)
325+ assert isinstance(target.down_proj, W4A16GMMTensor)
326+ assert target.gate_up_proj._grouped_weight_cache is None
327+ 
328+ 
329+@pytest.mark.parametrize("max_shard_size", [1024, 16384])
330+@pytest.mark.parametrize("scale_dtype", [torch.uint8, torch.float8_e8m0fnu])
331+@pytest.mark.parametrize("layout", ["out_first", "in_first"])
332+def test_w4a16_save_and_reload_round_trip(tmp_path, max_shard_size, scale_dtype, layout):
333+ dense = W4A16DenseTensor.from_packed(
334+ torch.full((32, 32), 0x21, dtype=torch.uint8),
335+ torch.arange(64, dtype=torch.uint8).reshape(32, 2).view(torch.float8_e8m0fnu),
336+ torch.Size((32, 64)), torch.bfloat16, 7,
337+ )
338+ experts = W4A16GMMTensor.from_packed(
339+ torch.full((2, 64, 16), 0x43, dtype=torch.uint8),
340+ torch.arange(128, dtype=torch.uint8).reshape(2, 1, 64).view(scale_dtype),
341+ quantized_shape=(2, 32, 64),
342+ orig_shape=(2, 64, 32) if layout == "in_first" else (2, 32, 64),
343+ orig_dtype=torch.bfloat16,
344+ weight_layout=layout,
345+ )
346+ state = {
347+ "model.linear.weight": torch.nn.Parameter(dense, requires_grad=False),
348+ "model.experts.gate_up_proj": experts,
349+ "model.experts.down_proj": experts,
350+ "model.norm.weight": torch.ones(64, dtype=torch.bfloat16),
351+ }
352+ shards = save_safetensors(state, tmp_path, max_shard_size=max_shard_size)
353+ index_name = "model.safetensors.index.json"
354+ assert (len(shards) > 1) == (max_shard_size == 1024)
355+ assert {path.name for path in tmp_path.iterdir()} == (
356+ set(shards) | ({index_name} if len(shards) > 1 else set())
357+ )
358+ if len(shards) > 1:
359+ weight_map = json.loads((tmp_path / index_name).read_text())["weight_map"]
360+ assert weight_map["model.linear._weight_packed_k"] != weight_map["model.linear._weight_scale"]
361+ assert weight_map["model.experts._gate_up_proj_qdata"] != weight_map["model.experts._gate_up_proj_scale"]
362+ assert safetensors_checkpoint_size(tmp_path) == sum(
363+ (tmp_path / name).stat().st_size for name in shards
364+ )
365+ with safe_open(tmp_path / shards[0], framework="pt") as shard:
366+ header = shard.metadata()
367+ assert json.loads(header["model.linear.weight"])["_type"] == "W4A16DenseTensor"
368+ assert json.loads(header["model.experts.gate_up_proj"])["_type"] == "W4A16GMMTensor"
369+ 
370+ restored = load_safetensors(tmp_path)
371+ assert restored.keys() == state.keys()
372+ for name, original in state.items():
373+ loaded = restored[name]
374+ assert type(loaded) is type(original)
375+ assert loaded.shape == original.shape and loaded.dtype == original.dtype
376+ if isinstance(original, (W4A16DenseTensor, W4A16GMMTensor)):
377+ for attr in original.tensor_attribute_names:
378+ assert getattr(loaded, attr) == getattr(original, attr)
379+ for attr in original.tensor_data_names:
380+ before, after = getattr(original, attr), getattr(loaded, attr)
381+ assert before.dtype == after.dtype and before.shape == after.shape
382+ assert torch.equal(before.view(torch.uint8), after.view(torch.uint8))
383+ else:
384+ assert torch.equal(loaded, original)
@@ -13,9 +13,9 @@ registers its ``quantize_`` handlers, and ``torchao_ascend/__init__.py`` mounts
13everything listed here under the torchao_ascend and torchao namespaces — new13everything listed here under the torchao_ascend and torchao namespaces — new
14features need no edits anywhere else.14features need no edits anywhere else.
15"""15"""
16-from . import distributed16+from . import distributed, inference
17from .inference import lightning_indexer as _lightning_indexer_inference # noqa: F40117from .inference import lightning_indexer as _lightning_indexer_inference # noqa: F401
18from .qat import lightning_indexer as _lightning_indexer_qat # noqa: F40118from .qat import lightning_indexer as _lightning_indexer_qat # noqa: F401
19from .training import hifloat8, mxfp8 # noqa: F40119from .training import hifloat8, mxfp8 # noqa: F401
20from .qat import mxfp8_qat, w4a16, w4a8 # noqa: F40120from .qat import mxfp8_qat, w4a16, w4a8 # noqa: F401
21-__all__ = ["distributed", "hifloat8", "mxfp8", "mxfp8_qat", "w4a16", "w4a8"]21+__all__ = ["distributed", "hifloat8", "inference", "mxfp8", "mxfp8_qat", "w4a16", "w4a8"]
@@ -0,0 +1,10 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""Inference features for torchao_ascend.
4+ 
5+The W4A16 conversion uses a native W4A16 operator for dense layers and
6+dequantizes MoE expert weights for BF16 computation.
7+"""
8+from . import w4a16
9+ 
10+__all__ = ["w4a16"]
@@ -0,0 +1,23 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""TorchAO tensor subclasses and grouped matmul for packed W4A16 inference."""
4+from torchao_ascend.serialization import register_safetensors_tensor_subclass
5+ 
6+from .fp4_packing import unpack_nibbles
7+from .w4a16_gmm import (
8+ W4A16GMMTensor,
9+ dequant_out_axis,
10+ w4a16_grouped_matmul,
11+)
12+from .w4a16_linear import W4A16DenseTensor
13+ 
14+register_safetensors_tensor_subclass(W4A16DenseTensor)
15+register_safetensors_tensor_subclass(W4A16GMMTensor)
16+ 
17+__all__ = [
18+ "W4A16DenseTensor",
19+ "W4A16GMMTensor",
20+ "w4a16_grouped_matmul",
21+ "dequant_out_axis",
22+ "unpack_nibbles",
23+]
@@ -0,0 +1,34 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""Shared FP4 storage helpers for W4A16 weights."""
4+ 
5+import torch
6+ 
7+ 
8+BLOCK_SIZE = 32
9+FP4_PER_BYTE = 2
10+ 
11+ 
12+class PackError(RuntimeError):
13+ """Invalid input for weight packing or dequantization."""
14+ 
15+ 
16+def unpack_nibbles(packed: torch.Tensor) -> torch.Tensor:
17+ """Unpack uint8 [..., N/2] to [..., N], with the low nibble first."""
18+ lo = packed & 0x0F
19+ hi = (packed >> 4) & 0x0F
20+ out = torch.empty(
21+ packed.shape[:-1] + (packed.shape[-1] * FP4_PER_BYTE,),
22+ dtype=torch.uint8,
23+ device=packed.device,
24+ )
25+ out[..., 0::2] = lo
26+ out[..., 1::2] = hi
27+ return out
28+ 
29+ 
30+def pack_nibbles(codes: torch.Tensor) -> torch.Tensor:
31+ """Pack uint8 [..., N] to [..., N/2], the inverse of ``unpack_nibbles``."""
32+ if codes.shape[-1] % FP4_PER_BYTE:
33+ raise PackError(f"The last dimension must be even, got {codes.shape[-1]}")
34+ return (codes[..., 0::2] & 0x0F) | ((codes[..., 1::2] & 0x0F) << 4)
@@ -0,0 +1,412 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""W4A16 tensor subclass and conversion for grouped expert weights.
4+ 
5+Expert weights are quantized along the output axis N and stored as packed FP4
6+with E8M0 scales. This scale layout requires dequantization to a cached
7+``[E, K, N]`` BF16 tensor for grouped GEMM. The cache is transient.
8+"""
9+from types import MethodType
10+from typing import Optional, Tuple
11+ 
12+import torch
13+from torchao.utils import TorchAOBaseTensor
14+ 
15+from torchao_ascend.ops import dispatch_op
16+ 
17+from .fp4_packing import BLOCK_SIZE, PackError, unpack_nibbles
18+ 
19+__all__ = [
20+ "EXECUTION_MODE_DEQUANT_BF16",
21+ "W4A16GMMTensor",
22+ "w4a16_grouped_matmul",
23+]
24+ 
25+EXECUTION_MODE_DEQUANT_BF16 = "dequant_bf16"
26+_WEIGHT_LAYOUTS = ("in_first", "out_first")
27+ 
28+ 
29+# The low nibble holds the earlier E2M1 value.
30+FP4_E2M1_LUT = (
31+ 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0,
32+ -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0,
33+)
34+ 
35+ 
36+def _to_uint8(tensor: torch.Tensor) -> torch.Tensor:
37+ return tensor if tensor.dtype == torch.uint8 else tensor.view(torch.uint8)
38+ 
39+ 
40+def dequant_out_axis(packed: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
41+ """Decode output-axis FP4 weights and E8M0 scales for BF16 inference and testing."""
42+ if packed.dim() < 2 or packed.dtype != torch.uint8:
43+ raise PackError(
44+ f"Expected packed uint8 [..., K, N/2], got {packed.dtype} {tuple(packed.shape)}"
45+ )
46+ codes = unpack_nibbles(packed).transpose(-2, -1).contiguous()
47+ n, k = codes.shape[-2:]
48+ if n % BLOCK_SIZE:
49+ raise PackError(f"Output-axis dequantization requires N divisible by 32, got N={n}")
50+ expected = codes.shape[:-2] + (n // BLOCK_SIZE, k)
51+ if tuple(scale.shape) != expected:
52+ raise PackError(f"Expected output-axis scale shape {expected}, got {tuple(scale.shape)}")
53+ 
54+ scale_u8 = _to_uint8(scale.contiguous())
55+ lut = torch.tensor(FP4_E2M1_LUT, dtype=torch.float32, device=codes.device)
56+ values = lut[codes.to(torch.int64)]
57+ scale_int = scale_u8.to(torch.int32)
58+ scale_float = torch.pow(2.0, (scale_int - 127).float())
59+ scale_float = torch.where(scale_int >= 255, torch.zeros_like(scale_float), scale_float)
60+ scale_float = scale_float.repeat_interleave(BLOCK_SIZE, dim=-2)
61+ return (values * scale_float).to(torch.bfloat16)
62+ 
63+ 
64+def _contiguous_strides(shape) -> Tuple[int, ...]:
65+ strides = [1] * len(shape)
66+ running = 1
67+ for dim in range(len(shape) - 1, -1, -1):
68+ strides[dim] = running
69+ running *= shape[dim]
70+ return tuple(strides)
71+ 
72+ 
73+class W4A16GMMTensor(TorchAOBaseTensor):
74+ """Packed W4A16 expert weights exposing the original shape and dtype.
75+ 
76+ ``qdata`` has shape ``[E, K, N/2]``, ``scale`` has shape
77+ ``[E, N/32, K]``, and ``quantized_shape`` records the normalized
78+ out-first shape ``[E, N, K]``.
79+ """
80+ 
81+ tensor_data_names = ["qdata", "scale"]
82+ tensor_attribute_names = [
83+ "quantized_shape",
84+ "orig_shape",
85+ "orig_dtype",
86+ "weight_layout",
87+ "block_size",
88+ ]
89+ 
90+ def __new__(
91+ cls,
92+ qdata: torch.Tensor,
93+ scale: torch.Tensor,
94+ quantized_shape,
95+ orig_shape,
96+ orig_dtype: torch.dtype,
97+ weight_layout: str,
98+ block_size: int = BLOCK_SIZE,
99+ ) -> "W4A16GMMTensor":
100+ quantized_shape = torch.Size(quantized_shape)
101+ orig_shape = torch.Size(orig_shape)
102+ block_size = int(block_size)
103+ if len(quantized_shape) != 3 or len(orig_shape) != 3:
104+ raise ValueError(
105+ "GMM weights must be 3D: "
106+ f"quantized_shape={tuple(quantized_shape)}, orig_shape={tuple(orig_shape)}"
107+ )
108+ if orig_dtype != torch.bfloat16:
109+ raise ValueError(f"W4A16 GMM requires BF16 source weights, got {orig_dtype}")
110+ if weight_layout not in _WEIGHT_LAYOUTS:
111+ raise ValueError(
112+ f"weight_layout must resolve to in_first or out_first, got {weight_layout!r}"
113+ )
114+ if block_size != BLOCK_SIZE:
115+ raise ValueError(f"W4A16 GMM requires block_size=32, got {block_size}")
116+ 
117+ experts, out_features, in_features = quantized_shape
118+ expected_orig_shape = (
119+ torch.Size((experts, in_features, out_features))
120+ if weight_layout == "in_first"
121+ else quantized_shape
122+ )
123+ if orig_shape != expected_orig_shape:
124+ raise ValueError(
125+ f"Expected {weight_layout} source weight shape {tuple(expected_orig_shape)}, "
126+ f"got {tuple(orig_shape)}"
127+ )
128+ if qdata.dtype != torch.uint8:
129+ raise TypeError(f"qdata must be uint8, got {qdata.dtype}")
130+ e8m0 = getattr(torch, "float8_e8m0fnu", None)
131+ if scale.dtype != torch.uint8 and scale.dtype != e8m0:
132+ raise TypeError(f"scale must be uint8 or float8_e8m0fnu, got {scale.dtype}")
133+ if qdata.device != scale.device:
134+ raise ValueError(
135+ f"qdata and scale must be on the same device, got {qdata.device} and {scale.device}"
136+ )
137+ expected_qdata = (experts, in_features, out_features // 2)
138+ expected_scale = (experts, out_features // block_size, in_features)
139+ if out_features % block_size or in_features % 2:
140+ raise ValueError(
141+ f"Packed weights require N divisible by 32 and even K, "
142+ f"got N={out_features}, K={in_features}"
143+ )
144+ if tuple(qdata.shape) != expected_qdata:
145+ raise ValueError(
146+ f"Expected qdata shape {expected_qdata}, got {tuple(qdata.shape)}"
147+ )
148+ if tuple(scale.shape) != expected_scale:
149+ raise ValueError(
150+ f"Expected scale shape {expected_scale}, got {tuple(scale.shape)}"
151+ )
152+ 
153+ self = torch.Tensor._make_wrapper_subclass(
154+ cls,
155+ orig_shape,
156+ strides=_contiguous_strides(orig_shape),
157+ storage_offset=0,
158+ layout=torch.strided,
159+ dtype=orig_dtype,
160+ device=qdata.device,
161+ requires_grad=False,
162+ )
163+ self.qdata = qdata
164+ self.scale = scale
165+ self.quantized_shape = quantized_shape
166+ self.orig_shape = orig_shape
167+ self.orig_dtype = orig_dtype
168+ self.weight_layout = weight_layout
169+ self.block_size = block_size
170+ # Keep the derived BF16 cache out of the flattened tensor data.
171+ self._grouped_weight_cache = None
172+ return self
173+ 
174+ def __reduce_ex__(self, protocol):
175+ reduced = super().__reduce_ex__(protocol)
176+ # Legacy torch.Tensor pickle state includes __dict__. Clear the
177+ # cache in that state so checkpoints retain only the packed weights.
178+ if (
179+ len(reduced) == 2
180+ and isinstance(reduced[1], tuple)
181+ and reduced[1]
182+ and isinstance(reduced[1][-1], dict)
183+ ):
184+ reduce_args = list(reduced[1])
185+ state = reduce_args[-1]
186+ if state.get("_grouped_weight_cache") is not None:
187+ state = state.copy()
188+ state["_grouped_weight_cache"] = None
189+ reduce_args[-1] = state
190+ reduced = (reduced[0], tuple(reduce_args))
191+ return reduced
192+ 
193+ @classmethod
194+ def from_packed(
195+ cls,
196+ qdata: torch.Tensor,
197+ scale: torch.Tensor,
198+ quantized_shape,
199+ orig_shape,
200+ orig_dtype: torch.dtype,
201+ weight_layout: str,
202+ block_size: int = BLOCK_SIZE,
203+ ) -> "W4A16GMMTensor":
204+ """Wrap existing v3 packed data without requantizing or copying the weights."""
205+ return cls(
206+ qdata,
207+ scale,
208+ quantized_shape,
209+ orig_shape,
210+ orig_dtype,
211+ weight_layout,
212+ block_size,
213+ )
214+ 
215+ def _grouped_weight(self) -> torch.Tensor:
216+ """Return the cached contiguous BF16 ``[E, K, N]`` weights for GMM."""
217+ cache = getattr(self, "_grouped_weight_cache", None)
218+ if not isinstance(cache, torch.Tensor) or cache.device != self.qdata.device:
219+ out_first = dequant_out_axis(self.qdata, self.scale)
220+ cache = out_first.transpose(1, 2).contiguous()
221+ self._grouped_weight_cache = cache
222+ return cache
223+ 
224+ def dequantize(self) -> torch.Tensor:
225+ """Return BF16 weights in the original layout using the grouped cache."""
226+ grouped = self._grouped_weight()
227+ if self.weight_layout == "in_first":
228+ return grouped
229+ return grouped.transpose(1, 2)
230+ 
231+ 
232+aten = torch.ops.aten
233+implements = W4A16GMMTensor.implements
234+ 
235+ 
236+def w4a16_grouped_matmul(
237+ x: torch.Tensor,
238+ weight: W4A16GMMTensor,
239+ group_list,
240+ *,
241+ group_list_type: int,
242+ bias: Optional[torch.Tensor] = None,
243+) -> torch.Tensor:
244+ """Run BF16 grouped GEMM on weights stored in W4 format.
245+ 
246+ Supply one group entry per local expert in the kernel's format.
247+ Type 0 takes cumulative end offsets and type 1 takes token counts.
248+ """
249+ if not isinstance(weight, W4A16GMMTensor):
250+ raise TypeError(f"weight must be a W4A16GMMTensor, got {type(weight).__name__}")
251+ if x.dim() != 2:
252+ raise ValueError(f"Grouped GEMM input must be [M, K], got {tuple(x.shape)}")
253+ if x.dtype != torch.bfloat16:
254+ raise ValueError(f"W4A16 GMM requires BF16 activations, got {x.dtype}")
255+ if x.device != weight.qdata.device:
256+ raise ValueError(f"Input and weights must be on the same device, got {x.device} and {weight.qdata.device}")
257+ 
258+ experts, out_features, in_features = weight.quantized_shape
259+ if x.shape[-1] != in_features:
260+ raise ValueError(
261+ f"Input K={x.shape[-1]} does not match weight K={in_features}"
262+ )
263+ if not isinstance(group_list, torch.Tensor):
264+ group_list = torch.as_tensor(group_list, dtype=torch.int64, device=x.device)
265+ elif group_list.dtype != torch.int64 or group_list.device != x.device:
266+ group_list = group_list.to(device=x.device, dtype=torch.int64)
267+ if group_list.dim() != 1 or group_list.numel() != experts:
268+ raise ValueError(
269+ f"group_list must be a 1D tensor with {experts} entries, one per local expert, "
270+ f"got shape {tuple(group_list.shape)}"
271+ )
272+ group_list_type = int(group_list_type)
273+ if group_list_type not in (0, 1):
274+ raise ValueError(f"group_list_type must be 0 or 1, got {group_list_type}")
275+ values = group_list.tolist()
276+ counts = values if group_list_type == 1 else [
277+ values[0], *[values[i] - values[i - 1] for i in range(1, len(values))]
278+ ]
279+ if any(count < 0 for count in counts) or sum(counts) != x.shape[0]:
280+ raise ValueError(
281+ f"group_list must describe nonnegative groups totaling {x.shape[0]} tokens"
282+ )
283+ 
284+ # Skip the kernel and cache allocation when all expert groups are empty.
285+ if x.shape[0] == 0:
286+ return x.new_empty((0, out_features))
287+ 
288+ grouped_weight = weight._grouped_weight()
289+ return dispatch_op(
290+ "mx_grouped_matmul",
291+ [x],
292+ list(grouped_weight.unbind(0)),
293+ backend="npu",
294+ bias=bias,
295+ group_list=group_list,
296+ group_type=0,
297+ output_dtype=x.dtype,
298+ group_list_type=group_list_type,
299+ split_item=2,
300+ )[0]
301+ 
302+ 
303+if hasattr(aten, "_grouped_mm"):
304+ 
305+ @implements(aten._grouped_mm.default)
306+ def _w4a16_grouped_mm(func, types, args, kwargs):
307+ x = args[0] if len(args) > 0 else kwargs["self"]
308+ weight = args[1] if len(args) > 1 else kwargs["mat2"]
309+ offs = args[2] if len(args) > 2 else kwargs.get("offs")
310+ bias = args[3] if len(args) > 3 else kwargs.get("bias")
311+ out_dtype = args[4] if len(args) > 4 else kwargs.get("out_dtype")
312+ if offs is None:
313+ raise ValueError("W4A16 aten._grouped_mm requires cumulative offsets in offs")
314+ if not isinstance(weight, W4A16GMMTensor):
315+ return NotImplemented
316+ if weight.weight_layout != "in_first":
317+ raise ValueError(
318+ "aten._grouped_mm requires mat-B in [E, K, N] layout. "
319+ "Use w4a16_grouped_matmul for out-first weights."
320+ )
321+ if out_dtype is not None and out_dtype != x.dtype:
322+ raise NotImplementedError(
323+ f"W4A16 GMM requires out_dtype={x.dtype}, got {out_dtype}"
324+ )
325+ return w4a16_grouped_matmul(
326+ x,
327+ weight,
328+ offs,
329+ group_list_type=0,
330+ bias=bias,
331+ )
332+ 
333+ 
334+@implements(aten.copy_.default)
335+def _w4a16_copy(func, types, args, kwargs):
336+ self, src = args[0], args[1]
337+ metadata_matches = (
338+ isinstance(src, W4A16GMMTensor)
339+ and self.quantized_shape == src.quantized_shape
340+ and self.orig_shape == src.orig_shape
341+ and self.orig_dtype == src.orig_dtype
342+ and self.weight_layout == src.weight_layout
343+ and self.block_size == src.block_size
344+ and self.qdata.shape == src.qdata.shape
345+ and self.scale.shape == src.scale.shape
346+ and self.qdata.dtype == src.qdata.dtype
347+ and self.scale.dtype == src.scale.dtype
348+ )
349+ if not metadata_matches:
350+ raise ValueError("W4A16GMMTensor.copy_ requires matching packed storage and metadata")
351+ non_blocking = args[2] if len(args) > 2 else kwargs.get("non_blocking", False)
352+ # Invalidate the BF16 cache before updating the packed data.
353+ self._grouped_weight_cache = None
354+ self.qdata.copy_(src.qdata, non_blocking=non_blocking)
355+ self.scale.copy_(src.scale, non_blocking=non_blocking)
356+ return self
357+ 
358+ 
359+@implements(
360+ [
361+ aten.select.int,
362+ aten.index.Tensor,
363+ aten.sum.default,
364+ aten.sum.dim_IntList,
365+ aten.t.default,
366+ aten.transpose.int,
367+ aten.permute.default,
368+ ]
369+)
370+def _w4a16_bf16_fallback(func, types, args, kwargs):
371+ """Use the shared BF16 cache for HF eager and zero-token fallback operations."""
372+ return func(args[0].dequantize(), *args[1:], **kwargs)
373+ 
374+ 
375+def _qwen3_grouped_forward(self, hidden_states, top_k_index, top_k_weights):
376+ """Bridge the HF Qwen3-MoE router output to W4A16 grouped projections."""
377+ if hidden_states.shape[0] == 0:
378+ return torch.empty_like(hidden_states)
379+ sorted_tokens, row_ids = dispatch_op(
380+ "permute", hidden_states, top_k_index.to(torch.int32), backend="npu"
381+ )
382+ counts = torch.histc(
383+ top_k_index.float(), bins=self.num_experts, min=0, max=self.num_experts
384+ )
385+ offsets = counts.cumsum(0, dtype=torch.int64)
386+ gate_up = w4a16_grouped_matmul(
387+ sorted_tokens, self.gate_up_proj, offsets, group_list_type=0
388+ )
389+ activated = dispatch_op("swiglu", gate_up, dim=-1, backend="npu")
390+ output = w4a16_grouped_matmul(
391+ activated, self.down_proj, offsets, group_list_type=0
392+ )
393+ return dispatch_op(
394+ "unpermute", output, row_ids, probs=top_k_weights.to(torch.bfloat16), backend="npu"
395+ )
396+ 
397+ 
398+def _install_qwen3_grouped_forward(module):
399+ if not any(
400+ cls.__name__ == "Qwen3MoeExperts"
401+ and cls.__module__ == "transformers.models.qwen3_moe.modeling_qwen3_moe"
402+ for cls in type(module).__mro__
403+ ):
404+ return
405+ grouped_forward = MethodType(_qwen3_grouped_forward, module)
406+ if hasattr(module, "_hf_hook") and hasattr(module, "_old_forward"):
407+ module._old_forward = grouped_forward
408+ else:
409+ module.forward = grouped_forward
410+ 
411+ 
412+torch.serialization.add_safe_globals([W4A16GMMTensor])
@@ -0,0 +1,175 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""W4A16 dense tensor subclass and in-place module conversion.
4+ 
5+The original module runs forward with a tensor that exposes the original
6+weight shape and dtype while storing packed FP4 codes and E8M0 scales.
7+Linear dispatch calls ``npu_weight_quant_batchmatmul`` for fused dequantization.
8+"""
9+from typing import Optional
10+ 
11+import torch
12+from torchao.utils import TorchAOBaseTensor
13+ 
14+from torchao_ascend.ops import dispatch_op
15+from torchao_ascend.ops.npu import get_float4_dtype
16+ 
17+from .fp4_packing import BLOCK_SIZE, FP4_PER_BYTE
18+ 
19+__all__ = ["W4A16DenseTensor"]
20+ 
21+ 
22+class W4A16DenseTensor(TorchAOBaseTensor):
23+ """Logical ``[N, K]`` weight stored in contiguous K-packed rows."""
24+ 
25+ tensor_data_names = ["packed_k", "scale"]
26+ tensor_attribute_names = [
27+ "orig_shape",
28+ "orig_dtype",
29+ "weight_dtype",
30+ "block_size",
31+ ]
32+ 
33+ def __new__(
34+ cls,
35+ packed_k: torch.Tensor,
36+ scale: torch.Tensor,
37+ orig_shape: torch.Size,
38+ orig_dtype: torch.dtype,
39+ weight_dtype: int,
40+ block_size: int = BLOCK_SIZE,
41+ ) -> "W4A16DenseTensor":
42+ return torch.Tensor._make_wrapper_subclass(
43+ cls,
44+ torch.Size(orig_shape),
45+ dtype=orig_dtype,
46+ device=packed_k.device,
47+ requires_grad=False,
48+ )
49+ 
50+ def __init__(
51+ self,
52+ packed_k: torch.Tensor,
53+ scale: torch.Tensor,
54+ orig_shape: torch.Size,
55+ orig_dtype: torch.dtype,
56+ weight_dtype: int,
57+ block_size: int = BLOCK_SIZE,
58+ ):
59+ super().__init__()
60+ orig_shape = torch.Size(orig_shape)
61+ block_size = int(block_size)
62+ self._validate_packed(packed_k, scale, orig_shape, block_size)
63+ self.packed_k = packed_k
64+ self.scale = scale
65+ # Only contiguous storage is serialized and transferred between devices.
66+ self._matmul_weight = packed_k.T
67+ self._matmul_scale = scale.view(torch.uint8).T.view(scale.dtype)
68+ self.orig_shape = orig_shape
69+ self.orig_dtype = orig_dtype
70+ self.weight_dtype = int(weight_dtype)
71+ self.block_size = block_size
72+ 
73+ @staticmethod
74+ def _validate_packed(
75+ packed_k: torch.Tensor,
76+ scale: torch.Tensor,
77+ orig_shape: torch.Size,
78+ block_size: int,
79+ ) -> None:
80+ if block_size != BLOCK_SIZE:
81+ raise ValueError(f"W4A16 dense requires block_size=32, got {block_size}")
82+ if len(orig_shape) != 2:
83+ raise ValueError(f"Expected orig_shape to be [N, K], got {tuple(orig_shape)}")
84+ n, k = orig_shape
85+ if n % 8 or k % (block_size * 2):
86+ raise ValueError(
87+ f"Dense packing requires K divisible by {block_size * 2} and N by 8, "
88+ f"got N={n}, K={k}"
89+ )
90+ expected_packed = (n, k // FP4_PER_BYTE)
91+ expected_scale = (n, k // block_size)
92+ if tuple(packed_k.shape) != expected_packed:
93+ raise ValueError(
94+ f"Expected K-packed shape {expected_packed}, got {tuple(packed_k.shape)}"
95+ )
96+ if tuple(scale.shape) != expected_scale:
97+ raise ValueError(
98+ f"Expected scale shape {expected_scale}, got {tuple(scale.shape)}"
99+ )
100+ if packed_k.dtype != torch.uint8:
101+ raise TypeError(f"packed_k must be uint8, got {packed_k.dtype}")
102+ if scale.dtype != torch.float8_e8m0fnu:
103+ raise TypeError(f"scale must be float8_e8m0fnu, got {scale.dtype}")
104+ if not packed_k.is_contiguous() or not scale.is_contiguous():
105+ raise ValueError("K-packed data and scales must be contiguous")
106+ if packed_k.device != scale.device:
107+ raise ValueError(
108+ f"packed_k and scale must be on the same device, got {packed_k.device} and {scale.device}"
109+ )
110+ 
111+ @staticmethod
112+ def _resolve_weight_dtype(weight_dtype: Optional[int]) -> int:
113+ code = get_float4_dtype() if weight_dtype is None else weight_dtype
114+ return int(code)
115+ 
116+ @classmethod
117+ def from_packed(
118+ cls,
119+ packed_k: torch.Tensor,
120+ scale: torch.Tensor,
121+ orig_shape: torch.Size,
122+ orig_dtype: torch.dtype,
123+ weight_dtype: Optional[int],
124+ block_size: int = BLOCK_SIZE,
125+ ) -> "W4A16DenseTensor":
126+ """Validate and wrap existing packed data without requantizing it."""
127+ return cls(
128+ packed_k,
129+ scale,
130+ orig_shape,
131+ orig_dtype,
132+ cls._resolve_weight_dtype(weight_dtype),
133+ block_size,
134+ )
135+ 
136+ 
137+def _w4a16_dense_linear(func, types, args, kwargs):
138+ input_tensor = args[0] if len(args) > 0 else kwargs["input"]
139+ weight_tensor = args[1] if len(args) > 1 else kwargs["weight"]
140+ bias = args[2] if len(args) > 2 else kwargs.get("bias")
141+ if not isinstance(weight_tensor, W4A16DenseTensor):
142+ raise TypeError(
143+ "W4A16 linear expects a W4A16DenseTensor weight, got "
144+ f"{type(weight_tensor).__name__}"
145+ )
146+ return _run_w4a16_dense_linear(input_tensor, weight_tensor, bias)
147+ 
148+ 
149+def _run_w4a16_dense_linear(input_tensor, weight_tensor, bias):
150+ ndim = input_tensor.dim()
151+ if ndim == 0 or input_tensor.shape[-1] != weight_tensor.orig_shape[1]:
152+ raise ValueError(
153+ "The last input dimension must match the W4A16 dense weight's K: "
154+ f"input={tuple(input_tensor.shape)}, weight={tuple(weight_tensor.orig_shape)}"
155+ )
156+ 
157+ flat_input = input_tensor if ndim == 2 else input_tensor.reshape(-1, input_tensor.shape[-1])
158+ out = dispatch_op(
159+ "weight_quant_batchmatmul",
160+ flat_input,
161+ weight_tensor._matmul_weight,
162+ weight_tensor._matmul_scale,
163+ bias,
164+ weight_tensor.block_size,
165+ backend="npu",
166+ weight_dtype=weight_tensor.weight_dtype,
167+ )
168+ return out if ndim == 2 else out.reshape(input_tensor.shape[:-1] + (out.shape[-1],))
169+ 
170+ 
171+W4A16DenseTensor.implements(torch.ops.aten.linear.default)(_w4a16_dense_linear)
172+W4A16DenseTensor.implements_torch_function(
173+ [torch.ops.aten.linear.default, torch.nn.functional.linear]
174+)(_w4a16_dense_linear)
175+torch.serialization.add_safe_globals([W4A16DenseTensor])
@@ -7,7 +7,7 @@ provides a static rebuild partial as quantizer; cache_source is the local master
7The callback calls quantizer(weight, **kwargs) on a miss. Reconstruction is7The callback calls quantizer(weight, **kwargs) on a miss. Reconstruction is
8stateless. Converted experts expose experts_forward for external EP dispatch.8stateless. Converted experts expose experts_forward for external EP dispatch.
9"""9"""
10-from .fakequant_rebuild import rebuild_weight_fakequant10+ 
11from .config import (11from .config import (
12 Format,12 Format,
13 FormatEnum,13 FormatEnum,
@@ -16,6 +16,7 @@ from .config import (
16 W4A16GMMConfig,16 W4A16GMMConfig,
17 W4A16LinearConfig,17 W4A16LinearConfig,
18)18)
19+from .fakequant_rebuild import rebuild_weight_fakequant
19from .filters import w4a16_moe_filter_fn, w4a16_module_filter_fn20from .filters import w4a16_moe_filter_fn, w4a16_module_filter_fn
20from .w4a16_gmm import W4A16GMM, mx_quant_group_gemm21from .w4a16_gmm import W4A16GMM, mx_quant_group_gemm
21from .w4a16_linear import W4A16Linear, mx_quant_linear22from .w4a16_linear import W4A16Linear, mx_quant_linear
@@ -19,7 +19,6 @@ from enum import Enum
19from typing import Callable, Optional19from typing import Callable, Optional
20 20 
21import torch21import torch
22- 
23from torchao.core.config import AOBaseConfig22from torchao.core.config import AOBaseConfig
24from torchao.quantization.transform_module import register_quantize_module_handler23from torchao.quantization.transform_module import register_quantize_module_handler
25 24 
@@ -93,6 +92,7 @@ class QuantBaseConfig(AOBaseConfig):
93 92 
94 quant_format: str = "W4A16"93 quant_format: str = "W4A16"
95 block_size: int = 3294 block_size: int = 32
95+ step: str = field(default="prepare", kw_only=True)
96 weight_fakequant_fn: Optional[Callable] = None96 weight_fakequant_fn: Optional[Callable] = None
97 """Optional external cache: fn(weight, quantizer=..., cache_source=..., **kwargs).97 """Optional external cache: fn(weight, quantizer=..., cache_source=..., **kwargs).
98 98 
@@ -106,6 +106,8 @@ class QuantBaseConfig(AOBaseConfig):
106 def __post_init__(self):106 def __post_init__(self):
107 if self.block_size != 32:107 if self.block_size != 32:
108 raise ValueError("W4A16 fake quantization supports block_size=32 only.")108 raise ValueError("W4A16 fake quantization supports block_size=32 only.")
109+ if self.step != "prepare":
110+ raise ValueError(f"step must be 'prepare', got {self.step!r}.")
109 111 
110 def get_key_dtype(self, key):112 def get_key_dtype(self, key):
111 config = Format.from_config(self.quant_format)113 config = Format.from_config(self.quant_format)
@@ -149,15 +151,12 @@ class W4A16GMMConfig(W4A16LinearConfig):
149@torch.no_grad()151@torch.no_grad()
150def _w4a16_linear_transform(module: torch.nn.Module, config: W4A16LinearConfig):152def _w4a16_linear_transform(module: torch.nn.Module, config: W4A16LinearConfig):
151 from .w4a16_linear import W4A16Linear153 from .w4a16_linear import W4A16Linear
154+ 
152 return W4A16Linear.from_float(module, config=config)155 return W4A16Linear.from_float(module, config=config)
153 156 
154 157 
155@register_quantize_module_handler(W4A16GMMConfig)158@register_quantize_module_handler(W4A16GMMConfig)
156def _w4a16_gmm_transform(module: torch.nn.Module, config: W4A16GMMConfig):159def _w4a16_gmm_transform(module: torch.nn.Module, config: W4A16GMMConfig):
157- """Handler to convert an expert module to W4A16GMM.
158- 
159- ``W4A16GMM.from_float`` is decorated with ``@torch.no_grad()`` already, so
160- no extra decorator is needed here.
161- """
162 from .w4a16_gmm import W4A16GMM160 from .w4a16_gmm import W4A16GMM
161+ 
163 return W4A16GMM.from_float(module, config=config)162 return W4A16GMM.from_float(module, config=config)
@@ -24,14 +24,36 @@ from typing import Callable, List, Optional, Union
24import torch24import torch
25from torch.distributed.tensor import DTensor25from torch.distributed.tensor import DTensor
26 26 
27+from torchao_ascend.features.inference.w4a16 import W4A16GMMTensor
27from torchao_ascend.ops.npu import dynamic_mx_quant, mx_grouped_matmul, permute, swiglu, unpermute28from torchao_ascend.ops.npu import dynamic_mx_quant, mx_grouped_matmul, permute, swiglu, unpermute
28 29 
29-from .fakequant_rebuild import rebuild_weight_fakequant
30from .config import W4A16GMMConfig30from .config import W4A16GMMConfig
31+from .fakequant_rebuild import rebuild_weight_fakequant
31 32 
32__all__ = ["W4A16GMM", "mx_quant_group_gemm"]33__all__ = ["W4A16GMM", "mx_quant_group_gemm"]
33 34 
34 35 
36+def resolve_expert_layout(gate_up_shape, down_shape, hidden_size=None, layout="auto"):
37+ """Return (hidden_size, layout) for the gate/up and down projections."""
38+ gu_m, gu_n = gate_up_shape[-2:]
39+ dw_m, dw_n = down_shape[-2:]
40+ candidates = (
41+ ("out_first", gu_n, dw_m == gu_n and gu_m == 2 * dw_n),
42+ ("in_first", gu_m, dw_n == gu_m and gu_n == 2 * dw_m),
43+ )
44+ for candidate, hidden, matches in candidates:
45+ if (
46+ matches
47+ and layout in ("auto", candidate)
48+ and (hidden_size is None or hidden == hidden_size)
49+ ):
50+ return hidden, candidate
51+ raise ValueError(
52+ f"Cannot determine the MoE hidden size or weight layout: gate_up={tuple(gate_up_shape)}, "
53+ f"down={tuple(down_shape)}, hidden_size={hidden_size}, weight_layout={layout!r}"
54+ )
55+ 
56+ 
35class _EmptyProjection(torch.autograd.Function):57class _EmptyProjection(torch.autograd.Function):
36 @staticmethod58 @staticmethod
37 def forward(ctx, tokens, weight, output_size):59 def forward(ctx, tokens, weight, output_size):
@@ -58,13 +80,17 @@ class gmm_with_hp_or_lp_weight(torch.autograd.Function):
58 ))80 ))
59 81 
60 @classmethod82 @classmethod
61- def gmm_apply(cls, x, weight, bias, tokens_per_expert, config, grad_enabled, to_shape, ori_weight=None):83+ def gmm_apply(cls, x, weight, bias, tokens_per_expert, config, grad_enabled, to_shape,
84+ ori_weight=None, weight_layout=None):
62 if isinstance(tokens_per_expert, list):85 if isinstance(tokens_per_expert, list):
63 tokens_per_expert = torch.tensor(86 tokens_per_expert = torch.tensor(
64 tokens_per_expert, device=x.device, dtype=torch.int6487 tokens_per_expert, device=x.device, dtype=torch.int64
65 )88 )
66 group_list = torch.cumsum(tokens_per_expert, dim=0).to(torch.int64)89 group_list = torch.cumsum(tokens_per_expert, dim=0).to(torch.int64)
67- return cls.apply(x, weight, bias, group_list, grad_enabled, config, to_shape, tokens_per_expert, ori_weight, 0)90+ return cls.apply(
91+ x, weight, bias, group_list, grad_enabled, config, to_shape,
92+ tokens_per_expert, ori_weight, 0, weight_layout,
93+ )
68 94 
69 @classmethod95 @classmethod
70 def forward(96 def forward(
@@ -80,6 +106,7 @@ class gmm_with_hp_or_lp_weight(torch.autograd.Function):
80 tokens_per_expert,106 tokens_per_expert,
81 ori_weight=None,107 ori_weight=None,
82 group_list_type=0,108 group_list_type=0,
109+ weight_layout=None,
83 ):110 ):
84 if not grad_enabled:111 if not grad_enabled:
85 raise RuntimeError('Forward-only is currently not supported by QAT W4A16 recipe.')112 raise RuntimeError('Forward-only is currently not supported by QAT W4A16 recipe.')
@@ -90,7 +117,7 @@ class gmm_with_hp_or_lp_weight(torch.autograd.Function):
90 ctx.weight_shape = weight.shape117 ctx.weight_shape = weight.shape
91 ctx.weight_dtype = weight.dtype118 ctx.weight_dtype = weight.dtype
92 weight = weight.reshape(len(tokens_per_expert), -1, weight.shape[-1])119 weight = weight.reshape(len(tokens_per_expert), -1, weight.shape[-1])
93- layout = getattr(config, "weight_layout", "auto")120+ layout = weight_layout or getattr(config, "weight_layout", "auto")
94 ctx.transposed = layout == "in_first" or (121 ctx.transposed = layout == "in_first" or (
95 layout == "auto" and weight.shape[-1] != x.shape[-1]122 layout == "auto" and weight.shape[-1] != x.shape[-1]
96 )123 )
@@ -165,7 +192,7 @@ class gmm_with_hp_or_lp_weight(torch.autograd.Function):
165 grad_weights = grad_weights.transpose(1, 2)192 grad_weights = grad_weights.transpose(1, 2)
166 grad_weights = grad_weights.reshape(ctx.weight_shape).to(ctx.weight_dtype)193 grad_weights = grad_weights.reshape(ctx.weight_shape).to(ctx.weight_dtype)
167 gradients = (194 gradients = (
168- grad_x, grad_weights, grad_bias, None, None, None, None, None, None, None195+ grad_x, grad_weights, grad_bias, None, None, None, None, None, None, None, None
169 )196 )
170 return gradients197 return gradients
171 198 
@@ -179,6 +206,8 @@ def mx_quant_group_gemm(
179 config: W4A16GMMConfig = None,206 config: W4A16GMMConfig = None,
180 to_shape: list = None,207 to_shape: list = None,
181 ori_weight: torch.Tensor = None,208 ori_weight: torch.Tensor = None,
209+ *,
210+ weight_layout: Optional[str] = None,
182) -> torch.Tensor:211) -> torch.Tensor:
183 return gmm_with_hp_or_lp_weight.gmm_apply(212 return gmm_with_hp_or_lp_weight.gmm_apply(
184 x=x,213 x=x,
@@ -189,6 +218,7 @@ def mx_quant_group_gemm(
189 grad_enabled=grad_enabled,218 grad_enabled=grad_enabled,
190 to_shape=to_shape,219 to_shape=to_shape,
191 ori_weight=ori_weight,220 ori_weight=ori_weight,
221+ weight_layout=weight_layout,
192 )222 )
193 223 
194 224 
@@ -241,11 +271,18 @@ class W4A16GMM(torch.nn.Module):
241 ) -> torch.Tensor:271 ) -> torch.Tensor:
242 """Compute routed tokens; prepare_down_fn optionally completes balanced weights after activation."""272 """Compute routed tokens; prepare_down_fn optionally completes balanced weights after activation."""
243 weights = []273 weights = []
274+ shapes = []
275+ num_experts = len(tokens_per_expert)
244 for name, override in (("gate_up_proj", gate_up_weight), ("down_proj", down_weight)):276 for name, override in (("gate_up_proj", gate_up_weight), ("down_proj", down_weight)):
245 weight = getattr(self, name) if override is None else override277 weight = getattr(self, name) if override is None else override
246 if isinstance(weight, torch.nn.Module):278 if isinstance(weight, torch.nn.Module):
247 weight = weight.weight279 weight = weight.weight
248- weights.append(weight.to_local() if hasattr(weight, "to_local") else weight)280+ weight = weight.to_local() if hasattr(weight, "to_local") else weight
281+ weights.append(weight)
282+ if weight.ndim == 2:
283+ shapes.append((weight.shape[0] // num_experts, weight.shape[1]))
284+ else:
285+ shapes.append(weight.shape)
249 gate_up, down = weights286 gate_up, down = weights
250 empty = hidden_states.shape[0] == 0287 empty = hidden_states.shape[0] == 0
251 if empty:288 if empty:
@@ -253,10 +290,21 @@ class W4A16GMM(torch.nn.Module):
253 output_size = gate_up.numel() // (len(tokens_per_expert) * hidden_states.shape[-1])290 output_size = gate_up.numel() // (len(tokens_per_expert) * hidden_states.shape[-1])
254 fc1 = _EmptyProjection.apply(hidden_states, gate_up, output_size)291 fc1 = _EmptyProjection.apply(hidden_states, gate_up, output_size)
255 else:292 else:
293+ layout = None
294+ try:
295+ _, layout = resolve_expert_layout(
296+ *shapes, hidden_states.shape[-1],
297+ getattr(self._quant_config, "weight_layout", "auto"),
298+ )
299+ except ValueError:
300+ if prepare_down_fn is None:
301+ raise
302+ # The callback can replace a staging shape after activation.
303+ # Use the existing per-projection inference in that case.
256 fc1 = mx_quant_group_gemm(304 fc1 = mx_quant_group_gemm(
257 hidden_states, gate_up, tokens_per_expert=tokens_per_expert,305 hidden_states, gate_up, tokens_per_expert=tokens_per_expert,
258 config=self._quant_config, grad_enabled=torch.is_grad_enabled(),306 config=self._quant_config, grad_enabled=torch.is_grad_enabled(),
259- ori_weight=gate_up,307+ ori_weight=gate_up, weight_layout=layout,
260 )308 )
261 if activation_fn is None:309 if activation_fn is None:
262 gate, up = fc1.chunk(2, dim=-1)310 gate, up = fc1.chunk(2, dim=-1)
@@ -275,7 +323,7 @@ class W4A16GMM(torch.nn.Module):
275 return mx_quant_group_gemm(323 return mx_quant_group_gemm(
276 act, down, tokens_per_expert=tokens_per_expert,324 act, down, tokens_per_expert=tokens_per_expert,
277 config=self._quant_config, grad_enabled=torch.is_grad_enabled(),325 config=self._quant_config, grad_enabled=torch.is_grad_enabled(),
278- ori_weight=down,326+ ori_weight=down, weight_layout=layout,
279 )327 )
280 328 
281 @classmethod329 @classmethod
@@ -283,6 +331,14 @@ class W4A16GMM(torch.nn.Module):
283 def from_float(cls, mod: torch.nn.Linear, config: Optional[W4A16GMMConfig] = None, name: Optional[str] = None):331 def from_float(cls, mod: torch.nn.Linear, config: Optional[W4A16GMMConfig] = None, name: Optional[str] = None):
284 if config is None:332 if config is None:
285 config = W4A16GMMConfig()333 config = W4A16GMMConfig()
334+ for projection in ("gate_up_proj", "down_proj"):
335+ weight = getattr(mod, projection, None)
336+ if isinstance(weight, torch.nn.Module):
337+ weight = weight.weight
338+ if isinstance(weight, W4A16GMMTensor):
339+ raise RuntimeError(
340+ "W4A16 prepare requires BF16 master weights. Cannot prepare packed W4A16 weights for QAT."
341+ )
286 342 
287 hidden_size = getattr(mod, 'hidden_dim', getattr(mod, 'hidden_size', None))343 hidden_size = getattr(mod, 'hidden_dim', getattr(mod, 'hidden_size', None))
288 num_experts = getattr(mod, 'num_experts', None)344 num_experts = getattr(mod, 'num_experts', None)
@@ -20,10 +20,11 @@ from typing import Optional
20import torch20import torch
21from torch.distributed.tensor import DTensor21from torch.distributed.tensor import DTensor
22 22 
23+from torchao_ascend.features.inference.w4a16 import W4A16DenseTensor
23from torchao_ascend.ops.npu import dynamic_mx_quant24from torchao_ascend.ops.npu import dynamic_mx_quant
24 25 
25-from .fakequant_rebuild import rebuild_weight_fakequant
26from .config import W4A16LinearConfig26from .config import W4A16LinearConfig
27+from .fakequant_rebuild import rebuild_weight_fakequant
27 28 
28__all__ = ["W4A16Linear", "mx_quant_linear"]29__all__ = ["W4A16Linear", "mx_quant_linear"]
29 30 
@@ -118,6 +119,10 @@ class W4A16Linear(torch.nn.Linear):
118 ) -> "W4A16Linear":119 ) -> "W4A16Linear":
119 if config is None:120 if config is None:
120 config = W4A16LinearConfig()121 config = W4A16LinearConfig()
122+ if isinstance(getattr(mod, "weight", None), W4A16DenseTensor):
123+ raise RuntimeError(
124+ "W4A16 prepare requires BF16 master weights. Cannot prepare packed W4A16 weights for QAT."
125+ )
121 126 
122 mod.__class__ = cls127 mod.__class__ = cls
123 mod._quant_config = config128 mod._quant_config = config
@@ -0,0 +1,165 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""Pack trained W4A16 weights for checkpoint export."""
4+ 
5+from typing import Optional, Tuple
6+ 
7+import torch
8+ 
9+from torchao_ascend.features.inference.w4a16 import W4A16DenseTensor, W4A16GMMTensor
10+from torchao_ascend.features.inference.w4a16.fp4_packing import (
11+ BLOCK_SIZE,
12+ FP4_PER_BYTE,
13+ PackError,
14+ pack_nibbles,
15+ unpack_nibbles,
16+)
17+from torchao_ascend.ops import dispatch_op
18+ 
19+from .w4a16_gmm import resolve_expert_layout
20+ 
21+ 
22+def to_e8m0(scale_u8: torch.Tensor) -> torch.Tensor:
23+ """View E8M0 scale bytes as their native dtype where supported."""
24+ dtype = getattr(torch, "float8_e8m0fnu", None)
25+ if dtype is not None:
26+ try:
27+ return scale_u8.view(dtype)
28+ except RuntimeError:
29+ pass
30+ return scale_u8
31+ 
32+ 
33+def decode_out_axis_scale(scale_u8: torch.Tensor, n: int, k: int) -> torch.Tensor:
34+ """Convert NPU scales [ceil(N/64), K, 2] to logical scales [N/32, K]."""
35+ if n % BLOCK_SIZE:
36+ raise PackError(f"Output-axis scales require N divisible by 32, got N={n}")
37+ block_pairs = (n + 2 * BLOCK_SIZE - 1) // (2 * BLOCK_SIZE)
38+ expected = (block_pairs, k, 2)
39+ if tuple(scale_u8.shape) != expected:
40+ raise PackError(
41+ f"Expected raw output-axis scale shape {expected}, got {tuple(scale_u8.shape)}"
42+ )
43+ return (scale_u8.permute(0, 2, 1).contiguous()
44+ .reshape(block_pairs * 2, k)[: n // BLOCK_SIZE])
45+ 
46+ 
47+def _decode_inputs(data, scale):
48+ """Move packed data and scales to CPU for byte operations and export."""
49+ return data.contiguous().view(torch.uint8).cpu(), scale.contiguous().view(torch.uint8).cpu()
50+ 
51+ 
52+def quantize_out_axis(
53+ weight: torch.Tensor
54+) -> Tuple[torch.Tensor, torch.Tensor]:
55+ """Quantize MoE weights along N, returning codes [N, K] and scales [N/32, K]."""
56+ n, k = weight.shape
57+ if n % BLOCK_SIZE or k % FP4_PER_BYTE:
58+ raise PackError(f"Output-axis quantization requires N divisible by 32 and even K, got N={n}, K={k}")
59+ data, scale = dispatch_op(
60+ "dynamic_mx_quant",
61+ weight,
62+ axis=-2,
63+ round_mode="rint",
64+ scale_alg=0,
65+ dst_type=torch.float4_e2m1fn_x2,
66+ block_size=BLOCK_SIZE,
67+ backend="npu",
68+ )
69+ data_u8, scale_u8 = _decode_inputs(data, scale)
70+ codes = unpack_nibbles(data_u8).reshape(n, k)
71+ return codes, decode_out_axis_scale(scale_u8, n, k)
72+ 
73+ 
74+def pack_linear_weight(
75+ weight: torch.Tensor, device: torch.device
76+) -> Tuple[torch.Tensor, torch.Tensor]:
77+ """Return native K-packed [N, K/2] and E8M0 scales [N, K/32] on CPU."""
78+ if weight.dim() != 2:
79+ raise PackError(f"Dense weights must be 2D, got {tuple(weight.shape)}")
80+ n, k = weight.shape
81+ if k % (BLOCK_SIZE * 2) or n % 8:
82+ raise PackError(f"Dense packing requires K divisible by 64 and N by 8, got K={k}, N={n}")
83+ on_device = weight.detach().to(device=device).contiguous()
84+ data, scale = dispatch_op(
85+ "dynamic_mx_quant", on_device, axis=-1, dst_type=torch.float4_e2m1fn_x2,
86+ block_size=BLOCK_SIZE, backend="npu",
87+ )
88+ data_u8, scale_u8 = _decode_inputs(data, scale)
89+ return (
90+ data_u8.reshape(n, k // FP4_PER_BYTE),
91+ scale_u8.reshape(n, k // BLOCK_SIZE).view(torch.float8_e8m0fnu),
92+ )
93+ 
94+ 
95+def pack_expert_weights(
96+ weight: torch.Tensor, device: torch.device
97+) -> Tuple[torch.Tensor, torch.Tensor]:
98+ """Return packed [E, K, N/2] and scales [E, N/32, K] on CPU.
99+ 
100+ Move and quantize one expert at a time to limit NPU memory during offline export.
101+ """
102+ if weight.dim() != 3:
103+ raise PackError(f"MoE weights must be 3D, got {tuple(weight.shape)}")
104+ 
105+ packed_list, scale_list = [], []
106+ for expert in range(weight.shape[0]):
107+ on_device = weight.detach()[expert].to(device=device).contiguous()
108+ if on_device.dtype == torch.float32:
109+ on_device = on_device.to(torch.bfloat16)
110+ codes, scale_u8 = quantize_out_axis(on_device)
111+ packed_list.append(pack_nibbles(codes.t().contiguous()))
112+ scale_list.append(scale_u8)
113+ 
114+ packed = torch.stack(packed_list)
115+ scale = to_e8m0(torch.stack(scale_list))
116+ return packed, scale
117+ 
118+ 
119+def normalize_moe_layout(
120+ gate_up: torch.Tensor, down: torch.Tensor, hidden_size: Optional[int] = None,
121+ weight_layout: str = "auto",
122+) -> Tuple[torch.Tensor, torch.Tensor, str]:
123+ """Normalize to out-first layout: gate_up [E, 2I, K], down [E, K, I]."""
124+ if gate_up.dim() != 3 or down.dim() != 3 or gate_up.shape[0] != down.shape[0]:
125+ raise PackError(
126+ "Expected fused 3D expert weights with the same expert count, "
127+ f"got gate_up={tuple(gate_up.shape)}, down={tuple(down.shape)}"
128+ )
129+ try:
130+ _, layout = resolve_expert_layout(
131+ gate_up.shape, down.shape, hidden_size, weight_layout
132+ )
133+ except ValueError as exc:
134+ raise PackError(str(exc)) from exc
135+ if layout == "out_first":
136+ return gate_up.contiguous(), down.contiguous(), "out_first"
137+ return (
138+ gate_up.transpose(1, 2).contiguous(),
139+ down.transpose(1, 2).contiguous(),
140+ "in_first",
141+ )
142+ 
143+ 
144+@torch.no_grad()
145+def pack_checkpoint_weights(state, dense_names, expert_names, device):
146+ """Replace selected CPU state-dict weights with packed inference tensors."""
147+ if not dense_names and not expert_names:
148+ raise ValueError("W4A16 export requires at least one weight to pack")
149+ 
150+ for name in dense_names:
151+ key = f"{name}.weight"
152+ weight = state[key]
153+ if weight.dtype != torch.bfloat16:
154+ raise ValueError(f"{key}: W4A16 checkpoint requires BF16 logical weights")
155+ packed_k, scale = pack_linear_weight(weight, device=device)
156+ state[key] = W4A16DenseTensor.from_packed(packed_k, scale, weight.shape, weight.dtype, None)
157+ 
158+ for name, hidden in expert_names.items():
159+ gate_key = f"{name}.gate_up_proj"
160+ down_key = f"{name}.down_proj"
161+ gate, down = state[gate_key], state[down_key]
162+ normalized_gate, normalized_down, layout = normalize_moe_layout(gate, down, hidden)
163+ for key, source, normalized in ((gate_key, gate, normalized_gate), (down_key, down, normalized_down)):
164+ qdata, scale = pack_expert_weights(normalized, device=device)
165+ state[key] = W4A16GMMTensor.from_packed(qdata, scale, normalized.shape, source.shape, source.dtype, layout)
@@ -105,11 +105,13 @@ def dynamic_mx_quant_with_dual_axis(
105 return torch_npu.npu_dynamic_mx_quant_with_dual_axis(tensor, **kwargs)105 return torch_npu.npu_dynamic_mx_quant_with_dual_axis(tensor, **kwargs)
106 106 
107 107 
108+@register_op("swiglu", "npu")
108def swiglu(x: torch.Tensor, dim: int = -1) -> torch.Tensor:109def swiglu(x: torch.Tensor, dim: int = -1) -> torch.Tensor:
109 """Fused SiGLU activation: silu(x[..., :D]) * x[..., D:] along ``dim``."""110 """Fused SiGLU activation: silu(x[..., :D]) * x[..., D:] along ``dim``."""
110 return torch_npu.npu_swiglu(x, dim=dim)111 return torch_npu.npu_swiglu(x, dim=dim)
111 112 
112 113 
114+@register_op("permute", "npu")
113def permute(tokens: torch.Tensor, indices: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:115def permute(tokens: torch.Tensor, indices: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
114 """Token permutation for MoE (``torch_npu.npu_moe_token_permute``).116 """Token permutation for MoE (``torch_npu.npu_moe_token_permute``).
115 117 
@@ -118,6 +120,7 @@ def permute(tokens: torch.Tensor, indices: torch.Tensor) -> tuple[torch.Tensor,
118 return torch_npu.npu_moe_token_permute(tokens, indices)120 return torch_npu.npu_moe_token_permute(tokens, indices)
119 121 
120 122 
123+@register_op("unpermute", "npu")
121def unpermute(124def unpermute(
122 permuted_tokens: torch.Tensor,125 permuted_tokens: torch.Tensor,
123 sorted_indices: torch.Tensor,126 sorted_indices: torch.Tensor,
@@ -176,6 +179,23 @@ def mx_quant_matmul(
176 return torch_npu.npu_quant_matmul(input_tensor, weight, scale, **kwargs)179 return torch_npu.npu_quant_matmul(input_tensor, weight, scale, **kwargs)
177 180 
178 181 
182+@register_op("weight_quant_batchmatmul", "npu")
183+def _npu_weight_quant_batchmatmul(
184+ input_tensor: torch.Tensor,
185+ weight: torch.Tensor,
186+ scale: torch.Tensor,
187+ bias: Optional[torch.Tensor],
188+ block_size: int,
189+ *,
190+ weight_dtype: int,
191+) -> torch.Tensor:
192+ """Fused matmul with BF16 activations and packed weight-only quantization."""
193+ return torch_npu.npu_weight_quant_batchmatmul(
194+ input_tensor, weight, scale, None, None, None, bias, block_size, 0,
195+ weight_dtype=weight_dtype,
196+ )
197+ 
198+ 
179@register_op("mx_grouped_matmul", "npu")199@register_op("mx_grouped_matmul", "npu")
180def mx_grouped_matmul(200def mx_grouped_matmul(
181 x,201 x,
@@ -1,7 +1,17 @@
1# Copyright (c) 2026, Huawei Technologies Co., Ltd1# Copyright (c) 2026, Huawei Technologies Co., Ltd
2 2 
3-"""HF safetensors export for quantized checkpoints (MXFP8 / FP8 scope)."""3+"""Hugging Face safetensors serialization for plain and quantized weights."""
4 4 
5-from torchao_ascend.serialization.safetensor import load_safetensors, save_safetensors5+from torchao_ascend.serialization.safetensor import (
6+ load_safetensors,
7+ register_safetensors_tensor_subclass,
8+ safetensors_checkpoint_size,
9+ save_safetensors,
10+)
6 11 
7-__all__ = ["load_safetensors", "save_safetensors"]12+__all__ = [
13+ "load_safetensors",
14+ "register_safetensors_tensor_subclass",
15+ "safetensors_checkpoint_size",
16+ "save_safetensors",
17+]
@@ -2,19 +2,22 @@
2 2 
3"""Save a quantized state dict as a HuggingFace-layout safetensors checkpoint.3"""Save a quantized state dict as a HuggingFace-layout safetensors checkpoint.
4 4 
5-Scope: quantized weights carried by upstream tensor subclasses with the5+Supports plain tensors and registered subclasses implementing AO's
6-``tensor_data_names`` flattening protocol — ``MXTensor`` (MXFP8/MXFP4) and6+``tensor_data_names`` protocol. Output uses a single ``model.safetensors``
7-``Float8Tensor`` (FP8) — plus plain tensors. HiFloat8 / W4A8 packed products7+or numbered shards with a Hugging Face index.
8-are follow-ups. Output layout follows ``transformers`` conventions (single
9-``model.safetensors`` or numbered shards + ``index.json``), so the checkpoint
10-is consumable by ``from_pretrained``-style flows.
11"""8"""
12 9 
13-__all__ = ["load_safetensors", "save_safetensors"]10+__all__ = [
11+ "load_safetensors",
12+ "register_safetensors_tensor_subclass",
13+ "safetensors_checkpoint_size",
14+ "save_safetensors",
15+]
14 16 
15import json17import json
16import re18import re
17from pathlib import Path19from pathlib import Path
20+from threading import Lock
18from typing import Any21from typing import Any
19 22 
20import torch23import torch
@@ -26,6 +29,7 @@ from torchao.prototype.safetensors.safetensors_support import (
26 unflatten_tensor_state_dict,29 unflatten_tensor_state_dict,
27)30)
28from torchao.prototype.safetensors.safetensors_utils import (31from torchao.prototype.safetensors.safetensors_utils import (
32+ ALLOWED_CLASSES,
29 ALLOWED_TENSORS_SUBCLASSES,33 ALLOWED_TENSORS_SUBCLASSES,
30)34)
31 35 
@@ -37,6 +41,20 @@ _SIZE_MULTIBYTES = {"": 1, "K": 1024, "M": 1024**2, "G": 1024**3, "T": 1024**4}
37_SIZE_RE = re.compile(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([KMGT]?)\s*B?\s*", re.IGNORECASE)41_SIZE_RE = re.compile(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([KMGT]?)\s*B?\s*", re.IGNORECASE)
38 42 
39 43 
44+_REGISTRATION_LOCK = Lock()
45+ 
46+ 
47+def register_safetensors_tensor_subclass(cls: type[torch.Tensor]) -> None:
48+ """Register a tensor subclass implementing AO's safetensors protocol."""
49+ name = cls.__name__
50+ # AO 0.18 looks up subclasses by name and has no public registration API.
51+ with _REGISTRATION_LOCK:
52+ if ALLOWED_CLASSES.setdefault(name, cls) is not cls:
53+ raise ValueError(f"A different safetensors class is already registered as {name!r}")
54+ if name not in ALLOWED_TENSORS_SUBCLASSES:
55+ ALLOWED_TENSORS_SUBCLASSES.append(name)
56+ 
57+ 
40def _to_bytes(size: int | str) -> int:58def _to_bytes(size: int | str) -> int:
41 """Parse ``size`` into bytes; accepts ``int`` bytes or ``"5GB"``-style strings (1024-based)."""59 """Parse ``size`` into bytes; accepts ``int`` bytes or ``"5GB"``-style strings (1024-based)."""
42 if isinstance(size, bool) or not isinstance(size, (int, str)):60 if isinstance(size, bool) or not isinstance(size, (int, str)):
@@ -179,6 +197,22 @@ def save_safetensors(
179 return shard_names197 return shard_names
180 198 
181 199 
200+def _checkpoint_shard_names(directory: Path) -> list[str]:
201+ index_path = directory / _INDEX_NAME
202+ if index_path.exists():
203+ index = json.loads(index_path.read_text())
204+ return sorted(set(index["weight_map"].values()))
205+ if (directory / _SINGLE_SHARD_NAME).exists():
206+ return [_SINGLE_SHARD_NAME]
207+ raise FileNotFoundError(f"no safetensors checkpoint found in {directory}")
208+ 
209+ 
210+def safetensors_checkpoint_size(directory: str | Path) -> int:
211+ """Return the on-disk size of the safetensors weight files in bytes."""
212+ directory = Path(directory)
213+ return sum((directory / name).stat().st_size for name in _checkpoint_shard_names(directory))
214+ 
215+ 
182def load_safetensors(directory: str | Path) -> dict[str, torch.Tensor]:216def load_safetensors(directory: str | Path) -> dict[str, torch.Tensor]:
183 """Load a checkpoint written by ``save_safetensors`` and reconstruct the state dict.217 """Load a checkpoint written by ``save_safetensors`` and reconstruct the state dict.
184 218 
@@ -188,14 +222,7 @@ def load_safetensors(directory: str | Path) -> dict[str, torch.Tensor]:
188 metadata; plain entries pass through.222 metadata; plain entries pass through.
189 """223 """
190 directory = Path(directory)224 directory = Path(directory)
191- index_path = directory / _INDEX_NAME225+ shard_names = _checkpoint_shard_names(directory)
192- if index_path.exists():
193- index = json.loads(index_path.read_text())
194- shard_names = sorted(set(index["weight_map"].values()))
195- elif (directory / _SINGLE_SHARD_NAME).exists():
196- shard_names = [_SINGLE_SHARD_NAME]
197- else:
198- raise FileNotFoundError(f"no safetensors checkpoint found in {directory}")
199 226 
200 tensors: dict[str, torch.Tensor] = {}227 tensors: dict[str, torch.Tensor] = {}
201 metadata: dict[str, Any] = {}228 metadata: dict[str, Any] = {}