Merged
feat: add int4 weight only inference example #54
feat: add int4 weight only inference example #54
Merged
LennonAdd on Oct 28
Total: 11 files changed+684-0
@@ -0,0 +1 @@
1+"""Shared helpers for the NPU quantization examples."""
@@ -0,0 +1,31 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd.
2+"""Local Transformers loading without model or quantization policy."""
3+ 
4+import torch
5+ 
6+ 
7+def load_model(
8+ model_path,
9+ *,
10+ model_cls=None,
11+ dtype=torch.bfloat16,
12+ attn_implementation=None,
13+ use_cache=None,
14+ **model_kwargs,
15+):
16+ """Load local weights with a caller-selected model class and options.
17+ 
18+ None preserves the model's attention/cache defaults. The caller owns
19+ expert backends, quantization, device placement and distributed wrapping.
20+ """
21+ if model_cls is None:
22+ from transformers import AutoModelForCausalLM
23+ 
24+ model_cls = AutoModelForCausalLM
25+ kwargs = {"local_files_only": True, "torch_dtype": dtype, **model_kwargs}
26+ if attn_implementation is not None:
27+ kwargs["attn_implementation"] = attn_implementation
28+ model = model_cls.from_pretrained(model_path, **kwargs)
29+ if use_cache is not None:
30+ model.config.use_cache = use_cache
31+ return model
@@ -0,0 +1,113 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd.
2+"""Callback measurement, checkpoint I/O and parameter sampling primitives."""
3+ 
4+import gc
5+import time
6+import torch
7+ 
8+ 
9+def measure(step, *, device_api, warmup, iterations, tokens_per_step, before_measure=None):
10+ """Measure a caller-defined step using an explicit device statistics API.
11+ 
12+ step owns model mode, grad mode, inputs, outputs and backward/optimizer work.
13+ before_measure releases transient state after warmup, outside the timing.
14+ tokens_per_step is the TOTAL unique token count across participating ranks;
15+ the caller must account for data, tensor or expert parallelism.
16+ No model outputs are retained between steps.
17+ """
18+ if warmup < 0 or iterations < 1 or tokens_per_step < 0:
19+ raise ValueError("warmup/tokens_per_step must be nonnegative; iterations positive")
20+ for _ in range(warmup):
21+ step()
22+ if before_measure is not None:
23+ before_measure()
24+ gc.collect()
25+ device_api.synchronize()
26+ device_api.empty_cache()
27+ resident = device_api.memory_allocated()
28+ device_api.reset_peak_memory_stats()
29+ if torch.distributed.is_initialized():
30+ torch.distributed.barrier()
31+ start = time.perf_counter()
32+ for _ in range(iterations):
33+ step()
34+ device_api.synchronize()
35+ elapsed = time.perf_counter() - start
36+ metrics = {
37+ "seconds": elapsed,
38+ "resident_bytes": resident,
39+ "peak_allocated_bytes": device_api.max_memory_allocated(),
40+ "peak_reserved_bytes": device_api.max_memory_reserved(),
41+ }
42+ if torch.distributed.is_initialized():
43+ all_metrics = [None] * torch.distributed.get_world_size()
44+ torch.distributed.all_gather_object(all_metrics, metrics)
45+ else:
46+ all_metrics = [metrics]
47+ elapsed = max(m["seconds"] for m in all_metrics)
48+ return {
49+ "per_rank": all_metrics,
50+ "ms_per_step": elapsed * 1000 / iterations,
51+ "tokens_per_second": tokens_per_step * iterations / elapsed,
52+ }
53+ 
54+ 
55+def training_checkpoint(model, optimizer, directory, load=False):
56+ import torch.distributed.checkpoint as dcp
57+ from torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dict
58+ 
59+ optimizers = optimizer if optimizer is not None else ()
60+ model_state, optimizer_state = get_state_dict(model, optimizers)
61+ state = {"model": model_state, "optimizer": optimizer_state}
62+ if load:
63+ dcp.load(state, checkpoint_id=str(directory))
64+ set_state_dict(
65+ model,
66+ optimizers,
67+ model_state_dict=state["model"],
68+ optim_state_dict=state["optimizer"],
69+ )
70+ else:
71+ dcp.save(state, checkpoint_id=str(directory))
72+ 
73+ 
74+def model_checkpoint(model, directory, load=False):
75+ import torch.distributed.checkpoint as dcp
76+ from torch.distributed.checkpoint.state_dict import (
77+ get_model_state_dict,
78+ set_model_state_dict,
79+ )
80+ 
81+ state = {"model": get_model_state_dict(model)}
82+ if load:
83+ dcp.load(state, checkpoint_id=str(directory))
84+ set_model_state_dict(model, state["model"])
85+ else:
86+ dcp.save(state, checkpoint_id=str(directory))
87+ 
88+ 
89+def weight_update_views(parameters):
90+ """Yield one scalar weight view per parameter with a nonzero local gradient."""
91+ for parameter in parameters:
92+ gradient = parameter.grad
93+ if gradient is None:
94+ continue
95+ weight = parameter.detach()
96+ if hasattr(weight, "to_local"):
97+ weight, gradient = weight.to_local(), gradient.to_local()
98+ if not gradient.numel():
99+ continue
100+ # Find a large gradient without allocating abs() of the full gradient.
101+ flat = gradient.detach().reshape(-1)
102+ low, low_index = flat.min(dim=0)
103+ high, high_index = flat.max(dim=0)
104+ index = torch.where(-low > high, low_index, high_index)
105+ index = torch.where((low != 0) | (high != 0), index, -1).item()
106+ if index < 0:
107+ continue
108+ # Basic indexing keeps a live view even for a noncontiguous master weight.
109+ coordinates = []
110+ for size in reversed(weight.shape):
111+ index, coordinate = divmod(index, size)
112+ coordinates.append(coordinate)
113+ yield weight[tuple(reversed(coordinates))]
@@ -0,0 +1,48 @@
1+# int4_weight_only_inference
2+ 
3+Full-model NPU example. Single device uses Qwen2.5-0.5B-Instruct;
4+eight-rank FSDP2 uses Qwen2.5-72B-Instruct or Qwen3.5-35B-A3B's text model.
5+ 
6+```bash
7+bash examples/qwen2_5/int4_weight_only_inference.sh single --model-path /models/Qwen2.5-0.5B-Instruct
8+bash examples/qwen2_5/int4_weight_only_inference.sh dense --model-path /models/Qwen2.5-72B-Instruct
9+bash examples/qwen2_5/int4_weight_only_inference.sh moe --model-path /models/Qwen3.5-35B-A3B
10+```
11+ 
12+Requires the repository's torch/torchao/torch_npu dependencies, PyYAML, safetensors,
13+and Transformers 5.21.0 for the Qwen3.5 MoE examples. All models/tokenizers must be local.
14+Choose a fresh output directory for each run. All ranks must share that directory.
15+Each rank currently loads a full CPU model before blockwise NPU placement/sharding;
16+provision host RAM for eight copies plus checkpoint export, not just device memory.
17+ 
18+BF16 inference baseline → direct quantization → inference measurement → checkpoint save/rebuild/load → generation. No optimizer, backward, QAT preparation or conversion is used.
19+ 
20+JSON output contains per-rank allocated/reserved memory and aggregate throughput.
21+Inference measures fixed-length forward, not autoregressive decoding throughput.
22+The input text is synthetic: no accuracy, perplexity, or convergence claim is made.
23+ 
24+`packing` defaults to `plain_int32` on Ascend. TorchAO packs INT4 weights with `npu_convert_weight_to_int4pack` and runs inference with `npu_weight_quant_batchmatmul`. The `plain` format uses MSLK.
25+The example matches the scale/offset layout to the transposed weight, converts the
26+TorchAO affine zero point to the NPU kernel's additive offset, and saves the packed
27+INT4 data and group parameters as ordinary checkpoint tensors.
28+Embedding, output head, router and shared-expert gate remain BF16.
29+Qwen3.5 uses its original top-k router, shared expert and packed gate/up and down
30+projections. The BF16 baseline uses the Transformers grouped expert implementation.
31+Quantized routed experts use two eager `npu_grouped_matmul` calls with BF16 activations,
32+packed signed INT4 weights and one scale and additive offset per 128 input channels.
33+The MoE recipe requires `plain_int32` packing and uses FSDP2 data parallelism.
34+ 
35+NPU/FSDP2 tensor-subclass compatibility and Qwen3.5 linear-attention kernels require
36+hardware validation. Kernel/serialization failures propagate; there is no CPU fallback.
37+The full-depth, eight-rank MoE configuration has not been verified.
38+ 
39+Shared helpers in `examples/common/` provide local weight loading, callback-based
40+measurement, checkpoint I/O and weight sampling. This example owns layer selection,
41+Qwen3.5 expert backend selection, blockwise FSDP2 placement, forward/loss semantics,
42+training updates and logits checks. Measurement passes an explicit NPU API and the
43+data-parallel token count to `measure`; it measures fixed-input forward or
44+forward/backward without optimizer updates. Merge the common-helper PR first.
45+ 
46+## 单卡验证
47+ 
48+A5 单卡使用 Qwen2.5-0.5B-Instruct 预训练权重和配套 tokenizer。使用 plain_int32 打包,完成 INT4 权重量化推理、量化模型保存恢复和生成。
@@ -0,0 +1,11 @@
1+#!/usr/bin/env bash
2+set -euo pipefail
3+here="$(cd -- "$(dirname -- "$0")" && pwd)"
4+mode="${1:-single}"
5+shift || true
6+case "$mode" in
7+ single) python "$here/qwen2_5_int4_weight_only_inference.py" --config "$here/qwen2_5_int4_weight_only_inference_config.yaml" "$@" ;;
8+ dense) torchrun --standalone --nproc-per-node=8 "$here/qwen2_5_int4_weight_only_inference.py" --config "$here/qwen2_5_int4_weight_only_inference_dense_config.yaml" "$@" ;;
9+ moe) torchrun --standalone --nproc-per-node=8 "$here/qwen2_5_int4_weight_only_inference.py" --config "$here/../qwen3_5/qwen3_5_int4_weight_only_inference_moe_config.yaml" "$@" ;;
10+ *) echo "Usage: bash int4_weight_only_inference.sh [single|dense|moe] [--model-path PATH]" >&2; exit 2 ;;
11+esac
@@ -0,0 +1,300 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd.
2+"""int4 weight only inference on a single NPU or FSDP2. See README.md."""
3+ 
4+import argparse
5+import gc
6+import json
7+import os
8+from pathlib import Path
9+import sys
10+ 
11+import torch
12+from torch import nn
13+ 
14+# Support direct execution from any working directory.
15+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
16+from common.model_utils import load_model # noqa: E402
17+from common.runtime_utils import measure # noqa: E402
18+from common.runtime_utils import model_checkpoint as checkpoint # noqa: E402
19+ 
20+from qwen3_5.qwen3_5_int4_weight_only_inference_experts import transform_experts # noqa: E402
21+ 
22+ 
23+def select(module, name):
24+ return isinstance(module, torch.nn.Linear) and not name.endswith(
25+ ("lm_head", "shared_expert_gate", ".gate")
26+ )
27+ 
28+ 
29+def load_example_model(
30+ model_path,
31+ model_kind="dense",
32+ dtype=torch.bfloat16,
33+ attn_implementation="eager",
34+ use_cache: bool | None = False,
35+):
36+ """Load local weights on CPU; preserve full depth.
37+ 
38+ Pass attn_implementation=None to retain the Transformers default backend.
39+ KV caching defaults to off; pass use_cache=None to keep the model setting.
40+ Device placement and quantization belong to the caller.
41+ """
42+ from transformers import AutoModelForCausalLM
43+ 
44+ cls = AutoModelForCausalLM
45+ if model_kind == "moe":
46+ from transformers import Qwen3_5MoeForCausalLM
47+ 
48+ cls = Qwen3_5MoeForCausalLM
49+ options = {"experts_implementation": "grouped_mm"} if model_kind == "moe" else {}
50+ model = load_model(
51+ model_path,
52+ model_cls=cls,
53+ dtype=dtype,
54+ attn_implementation=attn_implementation,
55+ use_cache=use_cache,
56+ **options,
57+ )
58+ if model_kind == "moe":
59+ from transformers.integrations.moe import ALL_EXPERTS_FUNCTIONS
60+ 
61+ # Transformers 5.21 switches "grouped_mm" to batched_mm during decode.
62+ # Packed FP8 weights support grouped GEMM but cannot gather per-token weights.
63+ name = "torchao_ascend_grouped_mm"
64+ ALL_EXPERTS_FUNCTIONS.register(name, ALL_EXPERTS_FUNCTIONS["grouped_mm"])
65+ model.set_experts_implementation(name)
66+ return model
67+ 
68+ 
69+def build_model(cfg, device, mesh, transform_block, initialize=None):
70+ model = load_example_model(cfg["model_path"], model_kind=cfg["model_kind"])
71+ if initialize is not None:
72+ initialize(model)
73+ from torch.distributed.fsdp import fully_shard
74+ 
75+ # Quantize and shard each block before moving the next block to NPU.
76+ for block in model.model.layers:
77+ block.to(device)
78+ transform_block(block)
79+ if mesh is not None:
80+ fully_shard(block, mesh=mesh)
81+ if mesh is None:
82+ model.to(device)
83+ else:
84+ # Move only remaining unsharded embedding/head/buffers via root FSDP.
85+ fully_shard(model, mesh=mesh)
86+ return model
87+ 
88+ 
89+def measure_inference(model, batch, cfg):
90+ """Fixed-input Qwen causal-LM forward, excluding labels and generation."""
91+ model.eval()
92+ 
93+ def step():
94+ with torch.no_grad():
95+ model(**{k: v for k, v in batch.items() if k != "labels"})
96+ 
97+ return measure_steps(model, batch, cfg, step)
98+ 
99+ 
100+def measure_steps(model, batch, cfg, step):
101+ # These examples use data parallel FSDP2: each rank processes its own batch.
102+ ranks = torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1
103+ result = measure(
104+ step,
105+ device_api=torch.npu,
106+ warmup=cfg["warmup"],
107+ iterations=cfg["iterations"],
108+ tokens_per_step=batch["input_ids"].numel() * ranks,
109+ before_measure=lambda: model.zero_grad(set_to_none=True),
110+ )
111+ model.zero_grad(set_to_none=True)
112+ return result
113+ 
114+ 
115+def logits(model, batch):
116+ model.eval()
117+ with torch.no_grad():
118+ output = model(**batch)
119+ if not torch.isfinite(output.logits).all().item():
120+ raise RuntimeError("Nonfinite logits")
121+ return output.logits.detach().cpu()
122+ 
123+ 
124+def prepare_packed_int4(model, targets, *, sharded=False):
125+ from torchao.quantization import Int4PlainInt32Tensor
126+ from torchao.utils import unwrap_tensor_subclass
127+ 
128+ class ShardedInt4(nn.Module):
129+ # Keep all FSDP2 parameters contiguous and transpose qparams only for GEMM.
130+ def __init__(self, shape):
131+ super().__init__()
132+ self.shape = shape
133+ 
134+ def right_inverse(self, weight):
135+ return weight.qdata, weight.scale.T.contiguous(), (-weight.zero_point.T).contiguous()
136+ 
137+ def forward(self, data, scale, offset):
138+ return Int4PlainInt32Tensor(data, scale.T, offset.T, [1, 128], self.shape)
139+ 
140+ for name in targets:
141+ weight = model.get_submodule(name).weight
142+ if not isinstance(weight, Int4PlainInt32Tensor):
143+ raise TypeError(f"Expected an INT4 packed weight at {name}")
144+ if sharded:
145+ nn.utils.parametrize.register_parametrization(
146+ model.get_submodule(name), "weight", ShardedInt4(weight.shape), unsafe=True
147+ )
148+ continue
149+ # The kernel consumes transposed W and (q + offset) * scale.
150+ # TorchAO packs q with an affine zero point: (q - zero_point) * scale.
151+ weight.scale = weight.scale.T.contiguous().T
152+ weight.zero_point = (-weight.zero_point.T).contiguous().T
153+ # DCP saves the ordinary packed data, scale and offset tensors. Linear
154+ # still reconstructs an Int4PlainInt32Tensor for its quantized forward.
155+ if not sharded:
156+ unwrap_tensor_subclass(model)
157+ 
158+ 
159+def transform(model, packing, phase, *, moe=False, sharded=False):
160+ from torchao.quantization import Int4WeightOnlyConfig, quantize_
161+ 
162+ if phase == "bf16":
163+ return
164+ if moe and packing != "plain_int32":
165+ raise ValueError("Qwen3.5 routed A16W4 experts require plain_int32 packing")
166+ targets = [name for name, module in model.named_modules() if select(module, name)]
167+ if not targets:
168+ raise RuntimeError("No quantization targets found")
169+ config = Int4WeightOnlyConfig(
170+ group_size=128, int4_packing_format=packing, version=2
171+ )
172+ quantize_(model, config, filter_fn=select)
173+ for name in targets:
174+ module = model.get_submodule(name)
175+ if type(module.weight) is nn.Parameter:
176+ raise RuntimeError(f"Quantization left a plain weight at {name}")
177+ 
178+ if packing == "plain_int32":
179+ prepare_packed_int4(model, targets, sharded=sharded)
180+ if moe:
181+ transform_experts(model)
182+ 
183+ 
184+def build(cfg, phase, device, mesh):
185+ return build_model(
186+ cfg,
187+ device,
188+ mesh,
189+ transform_block=lambda block: transform(
190+ block, cfg["packing"], phase, moe=cfg["model_kind"] == "moe", sharded=mesh is not None
191+ ),
192+ )
193+ 
194+ 
195+def main():
196+ import yaml
197+ 
198+ parser = argparse.ArgumentParser()
199+ parser.add_argument(
200+ "--config", default=str(Path(__file__).with_name("qwen2_5_int4_weight_only_inference_config.yaml"))
201+ )
202+ parser.add_argument("--model-path")
203+ args = parser.parse_args()
204+ cfg = yaml.safe_load(Path(args.config).read_text())
205+ if args.model_path:
206+ cfg["model_path"] = args.model_path
207+ world = int(os.environ.get("WORLD_SIZE", "1"))
208+ if world != cfg["world_size"]:
209+ raise ValueError(f"Config requires {cfg['world_size']} processes, got {world}")
210+ if cfg["warmup"] < 1 or cfg["iterations"] < 1:
211+ raise ValueError("warmup and iterations must be positive")
212+ import torch_npu # noqa: F401 - register NPU backend
213+ import torchao_ascend # noqa: F401 - register quantization implementations
214+ 
215+ local_rank = int(os.environ.get("LOCAL_RANK", "0"))
216+ torch.npu.set_device(local_rank)
217+ device = torch.device("npu", local_rank)
218+ mesh = None
219+ if world > 1:
220+ torch.distributed.init_process_group("hccl")
221+ from torch.distributed.device_mesh import init_device_mesh
222+ 
223+ mesh = init_device_mesh("npu", (world,))
224+ rank = torch.distributed.get_rank() if world > 1 else 0
225+ torch.manual_seed(cfg["seed"])
226+ from transformers import AutoTokenizer
227+ 
228+ tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True)
229+ tokenizer.pad_token = tokenizer.eos_token
230+ text = (
231+ "Explain how low precision arithmetic affects memory and computation. "
232+ * cfg["sequence_length"]
233+ )
234+ batch = tokenizer(
235+ [text] * cfg["batch_size"],
236+ return_tensors="pt",
237+ padding="max_length",
238+ truncation=True,
239+ max_length=cfg["sequence_length"],
240+ )
241+ batch = {k: v.to(device) for k, v in batch.items()}
242+ batch["labels"] = batch["input_ids"].clone()
243+ batch["labels"].masked_fill_(batch["attention_mask"] == 0, -100)
244+ output = Path(cfg["output"])
245+ output.mkdir(parents=True, exist_ok=True)
246+ metrics = {}
247+ 
248+ def report(name, value):
249+ baseline_name = "bf16"
250+ if name not in ("bf16", "bf16_inference") and baseline_name in metrics:
251+ baseline = metrics[baseline_name]
252+ value["speedup"] = baseline["ms_per_step"] / value["ms_per_step"]
253+ old_peak = max((x["peak_allocated_bytes"] for x in baseline["per_rank"]))
254+ new_peak = max((x["peak_allocated_bytes"] for x in value["per_rank"]))
255+ value["max_rank_peak_memory_saving_fraction"] = 1 - new_peak / old_peak
256+ metrics[name] = value
257+ if rank == 0:
258+ with (output / "metrics.jsonl").open("a") as stream:
259+ stream.write(json.dumps({"stage": name, **value}) + "\n")
260+ 
261+ model = build(cfg, "bf16", device, mesh)
262+ report("bf16", measure_inference(model, batch, cfg))
263+ del model
264+ gc.collect()
265+ torch.npu.empty_cache()
266+ phase = "quantized"
267+ model = build(cfg, phase, device, mesh)
268+ report(phase, measure_inference(model, batch, cfg))
269+ saved_logits = logits(model, batch)
270+ checkpoint(model, output / "checkpoint")
271+ del model
272+ gc.collect()
273+ torch.npu.empty_cache()
274+ model = build(cfg, phase, device, mesh)
275+ checkpoint(model, output / "checkpoint", load=True)
276+ torch.testing.assert_close(logits(model, batch), saved_logits)
277+ del saved_logits
278+ model.eval()
279+ with torch.no_grad():
280+ result = model.generate(
281+ input_ids=batch["input_ids"][:, :16],
282+ attention_mask=batch["attention_mask"][:, :16],
283+ max_new_tokens=4,
284+ min_new_tokens=4,
285+ do_sample=False,
286+ use_cache=False,
287+ synced_gpus=world > 1,
288+ )
289+ if result.shape[-1] != 20:
290+ raise RuntimeError("Generation did not produce four tokens")
291+ if rank == 0:
292+ (output / "summary.json").write_text(
293+ json.dumps({"config": cfg, "metrics": metrics}, indent=2)
294+ )
295+ if world > 1:
296+ torch.distributed.destroy_process_group()
297+ 
298+ 
299+if __name__ == "__main__":
300+ main()
@@ -0,0 +1,10 @@
1+model_path: /path/to/Qwen2.5-0.5B-Instruct
2+model_kind: dense
3+world_size: 1
4+packing: plain_int32
5+batch_size: 1
6+sequence_length: 64
7+seed: 42
8+warmup: 3
9+iterations: 10
10+output: ./results/int4_weight_only_inference_single
@@ -0,0 +1,10 @@
1+model_path: /path/to/Qwen2.5-72B-Instruct
2+model_kind: dense
3+world_size: 8
4+packing: plain_int32
5+batch_size: 1
6+sequence_length: 64
7+seed: 42
8+warmup: 3
9+iterations: 10
10+output: ./results/int4_weight_only_inference_dense
@@ -0,0 +1,58 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd.
2+"""Run on an Ascend NPU with torchao 0.18."""
3+ 
4+import unittest
5+ 
6+import torch
7+ 
8+from qwen2_5_int4_weight_only_inference import prepare_packed_int4
9+ 
10+ 
11+class TestPackedInt4(unittest.TestCase):
12+ def test_npu_linear_uses_affine_zero_point(self):
13+ import torch_npu # noqa: F401
14+ from torchao.quantization import Int4PlainInt32Tensor
15+ 
16+ # Exact powers of two and one-hot inputs make the expected outputs
17+ # representable in BF16, including both signs of the affine zero point.
18+ q = (torch.arange(32 * 256, dtype=torch.int32).reshape(32, 256) % 16) - 8
19+ scale = torch.tensor([0.5, 2.0]).expand(32, 2).to(torch.bfloat16)
20+ zero = torch.tensor([-3.0, 2.0]).expand_as(scale).to(torch.bfloat16)
21+ data = torch.ops.npu.npu_convert_weight_to_int4pack(q.npu(), 0)
22+ columns = torch.tensor([0, 127, 128, 255])
23+ x = torch.eye(256, dtype=torch.bfloat16)[columns].npu()
24+ ref = ((q - zero.repeat_interleave(128, 1)) * scale.repeat_interleave(128, 1)).T
25+ for sharded in (False, True):
26+ with self.subTest(sharded=sharded):
27+ weight = Int4PlainInt32Tensor(
28+ data, scale.T.contiguous().npu(), zero.T.contiguous().npu(), [1, 128], q.shape
29+ )
30+ model = torch.nn.Sequential(torch.nn.Linear(256, 32, bias=False, device="meta"))
31+ model[0].weight = torch.nn.Parameter(weight, requires_grad=False)
32+ prepare_packed_int4(model, ["0"], sharded=sharded)
33+ if sharded:
34+ self.assertTrue(all(p.is_contiguous() for p in model.parameters()))
35+ torch.testing.assert_close(model(x).cpu(), ref[columns], atol=0, rtol=0)
36+ 
37+ def test_grouped_matmul_uses_expert_and_k_group(self):
38+ import torch_npu # noqa: F401
39+ from qwen3_5.qwen3_5_int4_weight_only_inference_experts import Int4GroupedLinear
40+ 
41+ # Every row covers the signed INT4 range. The affine midpoint and step
42+ # differ per expert and per K group, so mixing either axis changes outputs.
43+ q = torch.arange(256).repeat(4, 32, 1) % 16 - 8
44+ zeros = torch.tensor([[2, -3], [1, 3], [-2, 1], [3, -1]])[:, None, :]
45+ scales = torch.tensor([[1, 2], [2, 1], [1, 4], [4, 2]])[:, None, :]
46+ weights = ((q - zeros.repeat_interleave(128, -1)) * scales.repeat_interleave(128, -1)).bfloat16()
47+ proj = Int4GroupedLinear(weights.npu())
48+ # Include a zero-token expert, uneven counts, and both signs of offset.
49+ counts = torch.tensor([2, 0, 1, 3])
50+ columns = torch.tensor([0, 129, 144, 15, 128, 255])
51+ x = torch.eye(256, dtype=torch.bfloat16)[columns].npu()
52+ expert_ids = torch.arange(4).repeat_interleave(counts)
53+ expected = weights[expert_ids, :, columns]
54+ torch.testing.assert_close(proj(x, counts.npu()).cpu(), expected, atol=0, rtol=0)
55+ 
56+ 
57+if __name__ == "__main__":
58+ unittest.main()
@@ -0,0 +1,92 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd.
2+"""Ascend A16W4 grouped projections for the Qwen3.5 routed experts."""
3+ 
4+from dataclasses import dataclass
5+ 
6+from torchao.core.config import AOBaseConfig
7+from torchao.quantization.transform_module import register_quantize_module_handler
8+ 
9+import torch
10+from torch import nn
11+ 
12+ 
13+class Int4GroupedLinear(nn.Module):
14+ @torch.no_grad()
15+ def __init__(self, weight):
16+ super().__init__()
17+ from torchao.quantization import Int4PlainInt32Tensor
18+ 
19+ experts, outputs, inputs = weight.shape
20+ groups = inputs // 128
21+ data = weight.new_empty((experts, outputs, inputs // 8), dtype=torch.int32)
22+ scale = weight.new_empty((experts, groups, outputs))
23+ offset = torch.empty_like(scale)
24+ # Limit the peak size of the INT32 temporary created by the packer.
25+ for start in range(0, experts, 8):
26+ chunk = weight[start : start + 8]
27+ packed = Int4PlainInt32Tensor.from_hp(chunk.flatten(0, 1), [1, 128])
28+ length = chunk.shape[0]
29+ data[start : start + length].copy_(packed.qdata.view(length, outputs, -1))
30+ scales = packed.scale.view(groups, length, outputs).transpose(0, 1)
31+ scale[start : start + length].copy_(scales)
32+ zeros = packed.zero_point.view(groups, length, outputs).transpose(0, 1)
33+ offset[start : start + length].copy_(-zeros)
34+ # FSDP2 shards the expert axis. DCP saves ordinary tensors.
35+ self.data_int4 = nn.Parameter(data, requires_grad=False)
36+ self.scale = nn.Parameter(scale, requires_grad=False)
37+ self.offset = nn.Parameter(offset, requires_grad=False)
38+ 
39+ def forward(self, tokens, tokens_per_expert):
40+ import torch_npu
41+ 
42+ return torch_npu.npu_grouped_matmul(
43+ [tokens.contiguous()], [self.data_int4.transpose(1, 2)],
44+ antiquant_scale=[self.scale], antiquant_offset=[self.offset],
45+ group_list=tokens_per_expert, group_list_type=1, group_type=0, split_item=2,
46+ )[0]
47+ 
48+ 
49+class Int4Experts(nn.Module):
50+ def __init__(self, gate_up, down, act_fn):
51+ super().__init__()
52+ self.gate_up = Int4GroupedLinear(gate_up)
53+ self.down = Int4GroupedLinear(down)
54+ self.act_fn = act_fn
55+ self.num_experts = gate_up.shape[0]
56+ 
57+ def forward(self, hidden_states, top_k_index, top_k_weights):
58+ # Same routing order and top-k reduction as Transformers grouped_mm_experts_forward.
59+ num_tokens, top_k = top_k_index.shape
60+ ids, order = torch.sort(top_k_index.reshape(-1))
61+ counts = torch.histc(
62+ ids.int(), bins=self.num_experts, min=0, max=self.num_experts - 1
63+ ).long()
64+ gate, up = self.gate_up(hidden_states[order // top_k], counts).chunk(2, dim=-1)
65+ output = self.down(self.act_fn(gate) * up, counts)
66+ weighted = output * top_k_weights.reshape(-1)[order, None]
67+ inverse = torch.empty_like(order)
68+ inverse[order] = torch.arange(order.numel(), device=order.device)
69+ return weighted[inverse].reshape(num_tokens, top_k, -1).sum(1).to(hidden_states.dtype)
70+ 
71+ 
72+@dataclass
73+class QwenInt4ExpertConfig(AOBaseConfig):
74+ """A16W4 Qwen3.5 expert with plain INT32 packing and groups of 128."""
75+ 
76+ 
77+@register_quantize_module_handler(QwenInt4ExpertConfig)
78+def _convert_int4_expert(experts, config):
79+ return Int4Experts(experts.gate_up_proj, experts.down_proj, experts.act_fn)
80+ 
81+ 
82+def transform_experts(model):
83+ from torchao.quantization import quantize_
84+ from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeExperts
85+ 
86+ if not any(isinstance(mod, Qwen3_5MoeExperts) for mod in model.modules()):
87+ raise RuntimeError("No Qwen3.5 packed routed experts found")
88+ quantize_(
89+ model,
90+ QwenInt4ExpertConfig(),
91+ filter_fn=lambda module, name: isinstance(module, Qwen3_5MoeExperts),
92+ )
@@ -0,0 +1,10 @@
1+model_path: /path/to/Qwen3.5-35B-A3B
2+model_kind: moe
3+world_size: 8
4+packing: plain_int32
5+batch_size: 1
6+sequence_length: 64
7+seed: 42
8+warmup: 3
9+iterations: 10
10+output: ./results/int4_weight_only_inference_moe