Open
feat(benchmarks,examples): 归档 MXFP8 量化训练基准与 Qwen3-235B 剪枝示例 #201
feat(benchmarks,examples): 归档 MXFP8 量化训练基准与 Qwen3-235B 剪枝示例 #201
Open
wanglijun55Add on 2 days ago
Total: 16 files changed+1284-23
@@ -0,0 +1,209 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""MXFP8 expert grouped-GEMM benchmark across the LP variants: BF16
4+``torch._grouped_mm`` vs the MXFP8 grouped paths over the Qwen3-235B-A22B
5+expert shapes (gate/up fused and down projections).
6+ 
7+- ``jit_quant`` (``MXFP8GMMConfig.from_linear(MXFP8LinearConfig(jit_quant))``):
8+ plain bf16 experts with dual-axis weight quantization fused per forward —
9+ the production ``mx_quant_group_gemm`` full chain;
10+- ``lp_ag`` / ``lp_ag_reshard``: experts travel as FP8+E8M0
11+ ``PostQuantWeight`` pairs (quantized once before the FSDP all-gather) —
12+ the GMM consumes the pairs, so the per-forward weight quant disappears.
13+ Module-level this is modeled by building the pairs outside the timed
14+ region; ``lp_ag_reshard`` has identical GMM consumption (the variant only
15+ changes the FSDP reshard topology) and is reported identically.
16+ 
17+Machinery in timer.py + utils.py (shared with the hifloat8 benchmark
18+directory); config-driven (--shapes-file/--recipes-file, defaults to
19+configs/). Run eager.
20+"""
21+import argparse
22+import itertools
23+from pathlib import Path
24+ 
25+import torch
26+ 
27+from torchao.prototype.moe_training.utils import generate_jagged_offs
28+from torchao_ascend.features.distributed import PostQuantWeight
29+from torchao_ascend.features.training.mxfp8 import MXFP8GMMConfig, MXFP8LinearConfig
30+from torchao_ascend.features.training.mxfp8.mx_gmm import mx_quant_group_gemm
31+from torchao_ascend.ops.npu.mx_ops import dynamic_mx_quant_with_dual_axis
32+ 
33+from timer import bench_fwd_bwd_us, bench_fwd_us
34+from utils import (
35+ GroupedShape,
36+ Recipe,
37+ ExperimentConfig,
38+ ExperimentResult,
39+ Experiment,
40+ Results,
41+ load_shapes,
42+ select_shapes,
43+ load_recipes,
44+)
45+ 
46+device = torch.accelerator.current_accelerator()
47+ 
48+ 
49+class _PairHolder:
50+ """lp_ag pair holder: the pairs are built once (the all-gather stage,
51+ outside the timed region) and their per-step grads are cleared inside
52+ the timed fn so accumulation does not distort the measurement."""
53+ 
54+ def __init__(self, W: torch.Tensor):
55+ # Unpack in the mx_gmm backward-first order (see
56+ # features/training/mxfp8/mx_gmm.py jit branch): the grouped
57+ # forward consumes the 3rd return value as its forward weight.
58+ w_bwd, s_bwd, w_fwd, s_fwd = dynamic_mx_quant_with_dual_axis(
59+ W.contiguous(), dst_type=torch.float8_e4m3fn)
60+ self.pair = PostQuantWeight(w_fwd, s_fwd, w_bwd, s_bwd, torch.bfloat16)
61+ 
62+ def clear_grads(self) -> None:
63+ self.pair._weight_fwd.grad = None
64+ self.pair._weight_bwd.grad = None
65+ 
66+ 
67+def _make_jit_fn():
68+ def build():
69+ cfg = MXFP8GMMConfig.from_linear(MXFP8LinearConfig(quant_mode="jit_quant"))
70+ 
71+ def fn(x, W, offs):
72+ owner = _Owner(W)
73+ return mx_quant_group_gemm(
74+ x, W, offs.to(torch.int64), cfg,
75+ grad_enabled=torch.is_grad_enabled(),
76+ weight_owner=owner, weight_attr="weight")
77+ return fn
78+ return build
79+ 
80+ 
81+def _make_lp_ag_fn():
82+ def build():
83+ cfg = MXFP8GMMConfig.from_linear(MXFP8LinearConfig(quant_mode="jit_quant"))
84+ holder = {"pair": None}
85+ 
86+ def fn(x, W, offs):
87+ if holder["pair"] is None:
88+ # backward-first unpack order (see _PairHolder above)
89+ w_bwd, s_bwd, w_fwd, s_fwd = dynamic_mx_quant_with_dual_axis(
90+ W.contiguous(), dst_type=torch.float8_e4m3fn)
91+ holder["pair"] = PostQuantWeight(w_fwd, s_fwd, w_bwd, s_bwd, torch.bfloat16)
92+ pair = holder["pair"]
93+ pair._weight_fwd.grad = None
94+ pair._weight_bwd.grad = None
95+ owner = _Owner(pair)
96+ return mx_quant_group_gemm(
97+ x, pair, offs.to(torch.int64), cfg,
98+ grad_enabled=torch.is_grad_enabled(),
99+ weight_owner=owner, weight_attr="weight")
100+ return fn
101+ return build
102+ 
103+ 
104+class _Owner:
105+ """Weakref-able owner whose ``weight`` is whatever the GMM backward
106+ resolves (plain weight for jit_quant, resident pair for lp_ag)."""
107+ 
108+ def __init__(self, weight):
109+ self.weight = weight
110+ 
111+ 
112+_RECIPES: dict[str, Recipe] = {
113+ "MXFP8_GMM_JIT": Recipe("MXFP8_GMM_JIT", _make_jit_fn()),
114+ "MXFP8_GMM_LP_AG": Recipe("MXFP8_GMM_LP_AG", _make_lp_ag_fn()),
115+ "MXFP8_GMM_LP_AG_RESHARD": Recipe("MXFP8_GMM_LP_AG_RESHARD", _make_lp_ag_fn()),
116+}
117+ 
118+ 
119+def get_configs(shapes: list[GroupedShape], recipes: list[Recipe]) -> list[ExperimentConfig]:
120+ return [
121+ ExperimentConfig(shape=s, recipe=r.name, hp_dtype=torch.bfloat16)
122+ for s, r in itertools.product(shapes, recipes)
123+ ]
124+ 
125+ 
126+def run_experiment(config: ExperimentConfig, recipes_by_name: dict[str, Recipe]) -> ExperimentResult:
127+ s = config.shape
128+ A = torch.randn(s.m, s.k, dtype=config.hp_dtype, device=device, requires_grad=True)
129+ # Framework storage layout [E, N, K]; the BF16 twin takes its [E, K, N]
130+ # transpose view (zero-copy, same storage) so both paths share inputs.
131+ W = torch.randn(s.g, s.n, s.k, dtype=config.hp_dtype,
132+ device=device, requires_grad=True)
133+ B_t = W.transpose(-2, -1)
134+ 
135+ # multiple_of=16 so group sizes are 16-aligned (grouped-mm friendliness;
136+ # does not affect the comparison since bf16 and scaled share offsets).
137+ offs = generate_jagged_offs(s.g, s.m, multiple_of=16,
138+ dtype=torch.int32, device=device)
139+ 
140+ scaled_fn = recipes_by_name[config.recipe].build()
141+ 
142+ bf16_fwd_bwd_us = bench_fwd_bwd_us(torch._grouped_mm, A, B_t, offs)
143+ scaled_fwd_bwd_us = bench_fwd_bwd_us(scaled_fn, A, W, offs)
144+ bf16_fwd_us = bench_fwd_us(torch._grouped_mm, A, B_t, offs)
145+ scaled_fwd_us = bench_fwd_us(scaled_fn, A, W, offs)
146+ 
147+ return ExperimentResult(
148+ bf16_fwd_bwd_us=round(bf16_fwd_bwd_us, 3),
149+ scaled_fwd_bwd_us=round(scaled_fwd_bwd_us, 3),
150+ scaled_fwd_bwd_speedup=round(bf16_fwd_bwd_us / scaled_fwd_bwd_us, 3),
151+ bf16_fwd_us=round(bf16_fwd_us, 3),
152+ scaled_fwd_us=round(scaled_fwd_us, 3),
153+ scaled_fwd_speedup=round(bf16_fwd_us / scaled_fwd_us, 3),
154+ )
155+ 
156+ 
157+def main(args):
158+ torch.random.manual_seed(123)
159+ torch.npu.set_device(0)
160+ 
161+ all_shapes = load_shapes(args.shapes_file, GroupedShape)
162+ shapes = select_shapes(all_shapes, args.shapes)
163+ recipes = load_recipes(args.recipes_file,
164+ [n.strip() for n in args.recipes.split(",")] if args.recipes else None,
165+ _RECIPES)
166+ recipes_by_name = {r.name: r for r in recipes}
167+ 
168+ results = Results()
169+ for config in get_configs(shapes, recipes):
170+ try:
171+ result = run_experiment(config, recipes_by_name)
172+ except Exception as ex: # per-config failure (OOM, op gap) shouldn't abort the sweep
173+ print(f"SKIP {config.shape} {config.recipe}: {type(ex).__name__}: {ex}",
174+ flush=True)
175+ continue
176+ results.add(Experiment(config=config, result=result))
177+ print(f"done {config.shape} {config.recipe}: "
178+ f"fwd+bwd spd={result.scaled_fwd_bwd_speedup}x", flush=True)
179+ print()
180+ print(results.to_table())
181+ if args.output_json:
182+ results.to_json(Path(args.output_json))
183+ print(f"\nwrote JSON -> {args.output_json}")
184+ if args.output_csv:
185+ results.to_csv(Path(args.output_csv))
186+ print(f"wrote CSV -> {args.output_csv}")
187+ 
188+ 
189+if __name__ == "__main__":
190+ p = argparse.ArgumentParser()
191+ p.add_argument("--shapes-file", type=Path, default=None,
192+ help="YAML shape families; defaults to "
193+ "benchmarks/prototype/mxfp8/configs/shapes_grouped.yaml")
194+ p.add_argument("--shapes", default="all",
195+ help="shape family to benchmark: 'all' or a family name")
196+ p.add_argument("--recipes-file", type=Path, default=None,
197+ help="YAML recipe selection; defaults to configs/recipes_grouped.yaml")
198+ p.add_argument("--recipes", default=None,
199+ help="comma-separated recipe names (overrides --recipes-file)")
200+ p.add_argument("--output-json", type=Path, default=None,
201+ help="optional path to write machine-readable results JSON")
202+ p.add_argument("--output-csv", type=Path, default=None,
203+ help="optional path to write results CSV")
204+ args = p.parse_args()
205+ if args.shapes_file is None:
206+ args.shapes_file = Path(__file__).parent / "configs" / "shapes_grouped.yaml"
207+ if args.recipes_file is None:
208+ args.recipes_file = Path(__file__).parent / "configs" / "recipes_grouped.yaml"
209+ main(args)
@@ -0,0 +1,226 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""Dense MXFP8 quantized-training benchmark across the four LP variants:
4+BF16 ``nn.Linear`` vs the MXFP8 linear paths over (M, N, K) shapes
5+(Qwen3-235B-A22B projections).
6+ 
7+The four end-to-end variants differ in how the quantized weights travel:
8+ 
9+- ``plain``: activations and weights quantized per use, GEMM via
10+ ``torch._scaled_mm`` (``quantize_`` + ``MXFP8LinearConfig(plain)``);
11+- ``jit_quant``: dual-axis weight quantization fused per forward, GEMM via
12+ ``mx_quant_matmul`` (the training default; ``quantize_`` +
13+ ``MXFP8LinearConfig(jit_quant)``);
14+- ``lp_ag``: weights quantized once before the FSDP all-gather and
15+ transported as FP8+E8M0 ``PostQuantWeight`` pairs — the GEMM consumes
16+ the pairs through the same ``mx_mm`` autograd Function. Module-level this
17+ is modeled by building the pair outside the timed region (standing for
18+ the all-gather stage) and timing the pair-consumption path;
19+- ``lp_ag_reshard``: same GEMM consumption as ``lp_ag`` (the variant only
20+ changes the FSDP reshard topology) — reported identically to ``lp_ag``.
21+ 
22+Machinery in timer.py + utils.py (shared with the hifloat8 benchmark
23+directory); config-driven (--shapes-file/--recipes-file, defaults to
24+configs/). Run eager. The MoE expert counterpart is
25+benchmark_mxfp8_grouped_mm.py in this directory.
26+"""
27+import argparse
28+import copy
29+import itertools
30+from pathlib import Path
31+ 
32+import torch
33+import torch.nn as nn
34+import torch.nn.functional as F
35+ 
36+from torchao.quantization import quantize_
37+from torchao.quantization.quantize_.common import KernelPreference
38+from torchao.prototype.mx_formats.config import ScaleCalculationMode
39+from torchao_ascend.features.distributed import PostQuantWeight
40+from torchao_ascend.features.training.mxfp8 import MXFP8LinearConfig
41+from torchao_ascend.ops.npu.mx_ops import dynamic_mx_quant_with_dual_axis
42+ 
43+from timer import bench_fwd_bwd_us, bench_fwd_us
44+from utils import (
45+ LinearShape,
46+ Recipe,
47+ ExperimentConfig,
48+ ExperimentResult,
49+ Experiment,
50+ Results,
51+ load_shapes,
52+ select_shapes,
53+ load_recipes,
54+)
55+ 
56+device = torch.accelerator.current_accelerator()
57+ 
58+_MX_MM = None # resolved lazily: upstream patched module (needs NPU patches)
59+ 
60+ 
61+def _mx_mm():
62+ global _MX_MM
63+ if _MX_MM is None:
64+ import torchao.prototype.moe_training.mxfp8_linear as mod
65+ 
66+ _MX_MM = mod.mx_mm
67+ return _MX_MM
68+ 
69+ 
70+class _PairHolder:
71+ """lp_ag pair holder: the pair is built once (the all-gather stage,
72+ outside the timed region) and its per-step grads are cleared inside the
73+ timed fn so accumulation does not distort the measurement."""
74+ 
75+ def __init__(self, W: torch.Tensor):
76+ w_fwd, s_fwd, w_bwd, s_bwd = dynamic_mx_quant_with_dual_axis(
77+ W.contiguous(), dst_type=torch.float8_e4m3fn)
78+ self.pair = PostQuantWeight(w_fwd, s_fwd, w_bwd, s_bwd, torch.bfloat16)
79+ 
80+ def clear_grads(self) -> None:
81+ self.pair._weight_fwd.grad = None
82+ self.pair._weight_bwd.grad = None
83+ 
84+ 
85+def _make_lp_ag_fn():
86+ """lp_ag GEMM consumption: mx_mm.apply on a resident PostQuantWeight
87+ pair built lazily on the first call (standing for the all-gather
88+ stage)."""
89+ holder = {"pair": None}
90+ owner = _PairHolderOwner(holder)
91+ 
92+ def fn(x, W):
93+ if holder["pair"] is None or holder["pair"]._weight_fwd.shape != tuple(W.shape):
94+ holder["pair"] = _PairHolder(W).pair
95+ holder["pair"]._weight_fwd.grad = None
96+ holder["pair"]._weight_bwd.grad = None
97+ return _mx_mm().apply(
98+ x, holder["pair"],
99+ torch.float8_e4m3fn, torch.float8_e4m3fn, torch.float8_e4m3fn,
100+ 32, KernelPreference.AUTO, None, None,
101+ ScaleCalculationMode.FLOOR, False,
102+ owner, "lp_ag")
103+ return fn
104+ 
105+ 
106+class _PairHolderOwner:
107+ """Weakref-able owner whose ``weight`` is the resident pair. The owner
108+ itself is kept alive by the holder for the whole benchmark (the lp_ag
109+ backward resolves the live pair through it on every step)."""
110+ 
111+ def __init__(self, holder: dict):
112+ self.holder = holder
113+ 
114+ @property
115+ def weight(self):
116+ return self.holder["pair"]
117+ 
118+ 
119+def _make_module_fn(mode: str):
120+ """plain / jit_quant: quantize_ module route (production handler)."""
121+ def build():
122+ quant = None
123+ 
124+ def fn(x, W):
125+ nonlocal quant
126+ if quant is None:
127+ base = nn.Linear(W.shape[1], W.shape[0], bias=False,
128+ dtype=torch.bfloat16, device=device)
129+ base.weight.data.copy_(W)
130+ quant = copy.deepcopy(base)
131+ quantize_(quant, MXFP8LinearConfig(quant_mode=mode))
132+ return quant(x)
133+ return fn
134+ return build
135+ 
136+ 
137+_RECIPES: dict[str, Recipe] = {
138+ "MXFP8_PLAIN": Recipe("MXFP8_PLAIN", _make_module_fn("plain")),
139+ "MXFP8_JIT_QUANT": Recipe("MXFP8_JIT_QUANT", _make_module_fn("jit_quant")),
140+ "MXFP8_LP_AG": Recipe("MXFP8_LP_AG", _make_lp_ag_fn),
141+ "MXFP8_LP_AG_RESHARD": Recipe("MXFP8_LP_AG_RESHARD", _make_lp_ag_fn),
142+}
143+ 
144+ 
145+def get_configs(shapes: list[LinearShape], recipes: list[Recipe]) -> list[ExperimentConfig]:
146+ return [
147+ ExperimentConfig(shape=s, recipe=r.name, hp_dtype=torch.bfloat16)
148+ for s, r in itertools.product(shapes, recipes)
149+ ]
150+ 
151+ 
152+def run_experiment(config: ExperimentConfig, recipes_by_name: dict[str, Recipe]) -> ExperimentResult:
153+ s = config.shape
154+ x = torch.randn(s.m, s.k, dtype=config.hp_dtype, device=device, requires_grad=True)
155+ W = torch.randn(s.n, s.k, dtype=config.hp_dtype, device=device, requires_grad=True)
156+ scaled_fn = recipes_by_name[config.recipe].build()
157+ 
158+ bf16_fwd_bwd_us = bench_fwd_bwd_us(F.linear, x, W)
159+ scaled_fwd_bwd_us = bench_fwd_bwd_us(scaled_fn, x, W)
160+ bf16_fwd_us = bench_fwd_us(F.linear, x, W)
161+ scaled_fwd_us = bench_fwd_us(scaled_fn, x, W)
162+ 
163+ return ExperimentResult(
164+ bf16_fwd_bwd_us=round(bf16_fwd_bwd_us, 3),
165+ scaled_fwd_bwd_us=round(scaled_fwd_bwd_us, 3),
166+ scaled_fwd_bwd_speedup=round(bf16_fwd_bwd_us / scaled_fwd_bwd_us, 3),
167+ bf16_fwd_us=round(bf16_fwd_us, 3),
168+ scaled_fwd_us=round(scaled_fwd_us, 3),
169+ scaled_fwd_speedup=round(bf16_fwd_us / scaled_fwd_us, 3),
170+ )
171+ 
172+ 
173+def main(args):
174+ torch.random.manual_seed(123)
175+ torch.npu.set_device(0)
176+ 
177+ all_shapes = load_shapes(args.shapes_file, LinearShape)
178+ shapes = select_shapes(all_shapes, args.shapes)
179+ recipes = load_recipes(args.recipes_file,
180+ [n.strip() for n in args.recipes.split(",")] if args.recipes else None,
181+ _RECIPES)
182+ recipes_by_name = {r.name: r for r in recipes}
183+ 
184+ results = Results()
185+ for config in get_configs(shapes, recipes):
186+ try:
187+ result = run_experiment(config, recipes_by_name)
188+ except Exception as ex: # per-config failure (OOM, op gap) shouldn't abort the sweep
189+ print(f"SKIP {config.shape} {config.recipe}: {type(ex).__name__}: {ex}",
190+ flush=True)
191+ continue
192+ results.add(Experiment(config=config, result=result))
193+ print(f"done {config.shape} {config.recipe}: "
194+ f"fwd+bwd spd={result.scaled_fwd_bwd_speedup}x", flush=True)
195+ print()
196+ print(results.to_table())
197+ if args.output_json:
198+ results.to_json(Path(args.output_json))
199+ print(f"\nwrote JSON -> {args.output_json}")
200+ if args.output_csv:
201+ results.to_csv(Path(args.output_csv))
202+ print(f"wrote CSV -> {args.output_csv}")
203+ 
204+ 
205+if __name__ == "__main__":
206+ p = argparse.ArgumentParser()
207+ p.add_argument("--shapes-file", type=Path, default=None,
208+ help="YAML shape families; defaults to "
209+ "benchmarks/prototype/mxfp8/configs/shapes_linear.yaml")
210+ p.add_argument("--shapes", default="all",
211+ help="shape family to benchmark: 'all' or a family name")
212+ p.add_argument("--recipes-file", type=Path, default=None,
213+ help="YAML recipe selection; defaults to configs/recipes_linear.yaml")
214+ p.add_argument("--recipes", default=None,
215+ help="comma-separated recipe names (overrides --recipes-file); "
216+ "e.g. MXFP8_JIT_QUANT,MXFP8_LP_AG")
217+ p.add_argument("--output-json", type=Path, default=None,
218+ help="optional path to write machine-readable results JSON")
219+ p.add_argument("--output-csv", type=Path, default=None,
220+ help="optional path to write results CSV")
221+ args = p.parse_args()
222+ if args.shapes_file is None:
223+ args.shapes_file = Path(__file__).parent / "configs" / "shapes_linear.yaml"
224+ if args.recipes_file is None:
225+ args.recipes_file = Path(__file__).parent / "configs" / "recipes_linear.yaml"
226+ main(args)
@@ -0,0 +1,10 @@
1+# Recipes for benchmark_mxfp8_grouped_mm.py (see _RECIPES there for details):
2+# MXFP8_GMM_JIT plain bf16 experts, dual-axis weight quant per forward
3+# MXFP8_GMM_LP_AG experts as PostQuantWeight pairs (quantized before the
4+# all-gather), GMM consumes the pairs
5+# MXFP8_GMM_LP_AG_RESHARD same GMM consumption as MXFP8_GMM_LP_AG
6+ 
7+recipes:
8+ - name: MXFP8_GMM_JIT
9+ - name: MXFP8_GMM_LP_AG
10+ - name: MXFP8_GMM_LP_AG_RESHARD
@@ -0,0 +1,13 @@
1+# Recipes for benchmark_mxfp8_linear.py (see _RECIPES there for details):
2+# MXFP8_PLAIN per-use quantization, GEMM via torch._scaled_mm
3+# MXFP8_JIT_QUANT dual-axis weight quant fused per forward (training default)
4+# MXFP8_LP_AG low-precision all-gather: weights arrive as PostQuantWeight
5+# pairs (quantized before the gather), GEMM consumes the pair
6+# MXFP8_LP_AG_RESHARD same GEMM consumption as MXFP8_LP_AG (the reshard
7+# variant differs only in the FSDP reshard topology)
8+ 
9+recipes:
10+ - name: MXFP8_PLAIN
11+ - name: MXFP8_JIT_QUANT
12+ - name: MXFP8_LP_AG
13+ - name: MXFP8_LP_AG_RESHARD
@@ -0,0 +1,6 @@
1+# Grouped shapes for benchmark_mxfp8_grouped_mm.py: [[M, N, K, G], ...].
2+# M = routed tokens (tokens x top-k).
3+shapes:
4+ qwen3_235b: # Qwen3-235B-A22B routed experts: 16384 tokens x top-8, 96 experts
5+ - [131072, 3072, 4096, 96]
6+ - [131072, 4096, 1536, 96]
@@ -0,0 +1,10 @@
1+# Shapes for benchmark_mxfp8_linear.py: [[M, N, K], ...].
2+shapes:
3+ small: # boundary smoke shapes (no real-model mapping)
4+ - [64, 256, 256]
5+ - [256, 1024, 1024]
6+ qwen3_235b: # Qwen3-235B-A22B dense projections: hidden 4096, q 8192, kv 512, M=16384 (batch 4 x seq 4096)
7+ - [16384, 8192, 4096]
8+ - [16384, 4096, 8192]
9+ - [16384, 512, 4096]
10+ - [16384, 4096, 4096]
@@ -0,0 +1,57 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""General timing utilities for benchmark scripts (median wall time, fwd, fwd+bwd)."""
4+from __future__ import annotations
5+ 
6+import statistics
7+import time
8+from typing import Callable
9+ 
10+import torch
11+import torch_npu # noqa: F401 registers the NPU with torch.accelerator
12+ 
13+ 
14+def benchmark_us(fn: Callable, *args, warmup: int = 5, iters: int = 30, **kwargs) -> float:
15+ """Median wall time of ``fn(*args, **kwargs)`` in microseconds.
16+ 
17+ Replaces ``triton.testing.do_bench`` (which times via cuda.Event): warm up,
18+ then synchronize around every timed iteration and take the median.
19+ """
20+ def call():
21+ return fn(*args, **kwargs)
22+ for _ in range(warmup):
23+ call()
24+ torch.accelerator.synchronize()
25+ times = []
26+ for _ in range(iters):
27+ t0 = time.perf_counter()
28+ call()
29+ torch.accelerator.synchronize()
30+ times.append((time.perf_counter() - t0) * 1e6)
31+ return statistics.median(times)
32+ 
33+ 
34+def bench_fwd_bwd_us(fn: Callable, *args, warmup: int = 5, iters: int = 30, **kwargs) -> float:
35+ """Time fwd+bwd: ``mse_loss(out, labels).backward()``, zeroing grads each iter."""
36+ with torch.no_grad():
37+ out_sample = fn(*args, **kwargs)
38+ labels = torch.ones_like(out_sample)
39+ 
40+ def fwd_bwd(*args, **kwargs):
41+ # zero grads on the first two tensor args (activation + weight) so they
42+ # don't accumulate across timed iterations
43+ for a in args[:2]:
44+ if isinstance(a, torch.Tensor) and a.requires_grad:
45+ a.grad = None
46+ out = fn(*args, **kwargs)
47+ torch.nn.functional.mse_loss(out, labels).backward()
48+ 
49+ return benchmark_us(fwd_bwd, *args, warmup=warmup, iters=iters, **kwargs)
50+ 
51+ 
52+def bench_fwd_us(fn: Callable, *args, warmup: int = 5, iters: int = 30, **kwargs) -> float:
53+ """Time forward only under ``torch.no_grad`` (inference latency)."""
54+ def inference_fn(*args, **kwargs):
55+ with torch.no_grad():
56+ return fn(*args, **kwargs)
57+ return benchmark_us(inference_fn, *args, warmup=warmup, iters=iters, **kwargs)
@@ -0,0 +1,228 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""Experiment framework for the MXFP8 / HiFloat8 feature benchmarks.
4+ 
5+Shapes, recipes, results. Mirrors the moe_training benchmark's machinery
6+(``ExperimentConfig`` / ``ExperimentResult`` / ``Results`` + YAML-driven
7+shapes/recipes) so all benchmark scripts in this repo report the same
8+bf16-vs-scaled columns. Recipes are generic name -> payload carriers: each
9+script defines what ``Recipe.build()`` returns (a scaled callable for the
10+functional grouped paths, a ``quantize_`` config for module-conversion
11+paths) and its own built-in registry.
12+"""
13+from __future__ import annotations
14+ 
15+import dataclasses
16+import json
17+from dataclasses import dataclass
18+from pathlib import Path
19+from typing import Callable, Optional
20+ 
21+import torch
22+import torchao_ascend # noqa: F401 activates MXFP8/HiFloat8 patches + injects KernelPreference.NPU
23+ 
24+ 
25+# ---------------------------------------------------------------------------
26+# Experiment dataclasses
27+# ---------------------------------------------------------------------------
28+@dataclass(frozen=True)
29+class LinearShape:
30+ """Dense GEMM shape ``(M, N, K)``: M tokens, N output dim, K contraction dim."""
31+ m: int
32+ n: int
33+ k: int
34+ 
35+ def __str__(self) -> str:
36+ return f"({self.m}, {self.n}, {self.k})"
37+ 
38+ 
39+@dataclass(frozen=True)
40+class GroupedShape:
41+ """Grouped GEMM shape ``(M, N, K, G)``.
42+ 
43+ ``M`` = total routed tokens (jagged, concatenated across experts),
44+ ``N`` = output dim, ``K`` = contraction dim, ``G`` = expert count.
45+ Same convention as the moe_training benchmark so shapes are directly
46+ comparable across the two sweeps.
47+ """
48+ m: int
49+ n: int
50+ k: int
51+ g: int
52+ 
53+ def __str__(self) -> str:
54+ return f"({self.m}, {self.n}, {self.k}, {self.g})"
55+ 
56+ 
57+@dataclass(frozen=True)
58+class ExperimentConfig:
59+ shape: LinearShape | GroupedShape
60+ recipe: str
61+ hp_dtype: torch.dtype
62+ 
63+ 
64+@dataclass(frozen=True)
65+class ExperimentResult:
66+ """fwd+bwd and fwd timings; the fwd+bwd pair stays ``None`` for the
67+ fwd-only (inference) scripts and renders as "-" in the outputs."""
68+ bf16_fwd_bwd_us: Optional[float]
69+ scaled_fwd_bwd_us: Optional[float]
70+ scaled_fwd_bwd_speedup: Optional[float]
71+ bf16_fwd_us: float
72+ scaled_fwd_us: float
73+ scaled_fwd_speedup: float
74+ 
75+ 
76+@dataclass
77+class Experiment:
78+ config: ExperimentConfig
79+ result: ExperimentResult
80+ 
81+ 
82+@dataclass(frozen=True)
83+class Recipe:
84+ """A named quantization recipe + its ``build()`` payload.
85+ 
86+ The payload's meaning is the script's calling convention: a scaled
87+ callable (functional recipes: ``fn(x, w[, offs])`` sharing the bf16
88+ twin's inputs) or a ``quantize_`` config (module-conversion recipes,
89+ applied to a BF16 clone of the baseline module).
90+ """
91+ name: str
92+ build: Callable[[], object]
93+ 
94+ 
95+# ---------------------------------------------------------------------------
96+# Results serialization
97+# ---------------------------------------------------------------------------
98+class Results:
99+ """Holds a list of ``Experiment`` and emits a table / JSON / CSV."""
100+ 
101+ def __init__(self, experiments: list[Experiment] | None = None) -> None:
102+ self.experiments = experiments or []
103+ 
104+ def add(self, experiment: Experiment) -> None:
105+ self.experiments.append(experiment)
106+ 
107+ @staticmethod
108+ def _fmt(value: Optional[float], width: int, suffix: str = "") -> str:
109+ return "-" if value is None else f"{value}{suffix}".rjust(width)
110+ 
111+ def to_table(self) -> str:
112+ hdr = (f"{'shape':<24} {'recipe':<30} {'bf16_f+b_us':>12} "
113+ f"{'scaled_f+b_us':>14} {'spd_f+b':>8} {'bf16_f_us':>11} "
114+ f"{'scaled_f_us':>13} {'spd_f':>7}")
115+ lines = [hdr, "-" * len(hdr)]
116+ for e in self.experiments:
117+ r = e.result
118+ lines.append(
119+ f"{str(e.config.shape):<24} {e.config.recipe:<30} "
120+ f"{self._fmt(r.bf16_fwd_bwd_us, 12)} "
121+ f"{self._fmt(r.scaled_fwd_bwd_us, 14)} "
122+ f"{self._fmt(r.scaled_fwd_bwd_speedup, 7, 'x')} "
123+ f"{r.bf16_fwd_us:>11} {r.scaled_fwd_us:>13} "
124+ f"{r.scaled_fwd_speedup:>6}x"
125+ )
126+ return "\n".join(lines)
127+ 
128+ def to_json(self, path: Path) -> None:
129+ path = Path(path)
130+ path.parent.mkdir(parents=True, exist_ok=True)
131+ payload = [
132+ {
133+ "shape": list(e.config.shape.__dict__.values()),
134+ "recipe": e.config.recipe,
135+ "bf16_fwd_bwd_us": e.result.bf16_fwd_bwd_us,
136+ "scaled_fwd_bwd_us": e.result.scaled_fwd_bwd_us,
137+ "scaled_fwd_bwd_speedup": e.result.scaled_fwd_bwd_speedup,
138+ "bf16_fwd_us": e.result.bf16_fwd_us,
139+ "scaled_fwd_us": e.result.scaled_fwd_us,
140+ "scaled_fwd_speedup": e.result.scaled_fwd_speedup,
141+ }
142+ for e in self.experiments
143+ ]
144+ path.write_text(json.dumps(payload, indent=2) + "\n")
145+ 
146+ def to_csv(self, path: Path) -> None:
147+ path = Path(path)
148+ path.parent.mkdir(parents=True, exist_ok=True)
149+ if not self.experiments:
150+ path.write_text("")
151+ return
152+ shape_cols = list(dataclasses.fields(self.experiments[0].config.shape))
153+ cols = [f.name for f in shape_cols] + [
154+ "recipe", "bf16_fwd_bwd_us", "scaled_fwd_bwd_us",
155+ "scaled_fwd_bwd_speedup", "bf16_fwd_us", "scaled_fwd_us",
156+ "scaled_fwd_speedup",
157+ ]
158+ lines = [",".join(cols)]
159+ for e in self.experiments:
160+ values = list(e.config.shape.__dict__.values()) + [
161+ e.config.recipe,
162+ e.result.bf16_fwd_bwd_us, e.result.scaled_fwd_bwd_us,
163+ e.result.scaled_fwd_bwd_speedup,
164+ e.result.bf16_fwd_us, e.result.scaled_fwd_us,
165+ e.result.scaled_fwd_speedup,
166+ ]
167+ lines.append(",".join("" if v is None else str(v) for v in values))
168+ path.write_text("\n".join(lines) + "\n")
169+ 
170+ 
171+# ---------------------------------------------------------------------------
172+# Shapes
173+# ---------------------------------------------------------------------------
174+def load_shapes(path: Optional[Path], shape_cls) -> dict[str, list]:
175+ """Load shape families from a YAML file.
176+ 
177+ YAML schema: ``shapes: {family: [[M,N,K(,G)], ...], ...}``; rows feed
178+ ``shape_cls`` (LinearShape or GroupedShape).
179+ """
180+ if path is None:
181+ raise FileNotFoundError("a shapes file is required (--shapes-file)")
182+ path = Path(path)
183+ if not path.is_file():
184+ raise FileNotFoundError(f"shapes file not found: {path}")
185+ import yaml
186+ raw = yaml.safe_load(path.read_text()) or {}
187+ return {
188+ family: [shape_cls(*row) for row in rows]
189+ for family, rows in (raw.get("shapes") or {}).items()
190+ }
191+ 
192+ 
193+def select_shapes(all_shapes: dict[str, list], selector: str) -> list:
194+ """``"all"`` flattens every family; otherwise return the named family."""
195+ if selector == "all":
196+ return [s for shapes in all_shapes.values() for s in shapes]
197+ if selector not in all_shapes:
198+ raise ValueError(
199+ f"unknown shape family {selector!r}; available: {sorted(all_shapes)}"
200+ )
201+ return list(all_shapes[selector])
202+ 
203+ 
204+# ---------------------------------------------------------------------------
205+# Recipes
206+# ---------------------------------------------------------------------------
207+def load_recipes(path: Optional[Path], names: Optional[list[str]],
208+ registry: dict[str, Recipe]) -> list[Recipe]:
209+ """Select recipes by name from ``registry``.
210+ 
211+ If ``names`` is given, it overrides the file (each name must be in the
212+ registry). Otherwise ``path`` (YAML: ``recipes: [{name: ...}]``) selects
213+ the subset; if both are None, every built-in recipe is returned.
214+ """
215+ if names:
216+ selected = names
217+ elif path is not None:
218+ import yaml
219+ raw = yaml.safe_load(Path(path).read_text()) or {}
220+ selected = [r["name"] for r in (raw.get("recipes") or [])]
221+ if not selected:
222+ raise ValueError(f"no recipes found in {path}")
223+ else:
224+ selected = list(registry.keys())
225+ unknown = [n for n in selected if n not in registry]
226+ if unknown:
227+ raise ValueError(f"unknown recipe(s) {unknown}; available: {sorted(registry)}")
228+ return [registry[n] for n in selected]
@@ -1,9 +1,13 @@
1-# Grouped shapes for benchmark_qat_gmm.py: [[M, N, K, G], ...].1+# Grouped shapes for benchmark_qat_gmm.py: [[M, N, K, G], ...]. M = routed
2+# tokens (tokens x top-k).
2shapes:3shapes:
3- small:4+ small: # boundary smoke shape (no real-model mapping)
4 - [4096, 1024, 2048, 8]5 - [4096, 1024, 2048, 8]
5- qwen3_5:6+ qwen3_5: # Qwen3.5-series expert shapes (existing family, hidden 4096 variant, G=8/16)
6 - [8192, 1536, 4096, 8]7 - [8192, 1536, 4096, 8]
7 - [8192, 2048, 7168, 16]8 - [8192, 2048, 7168, 16]
8- kimi_k3:9+ kimi_k3: # Kimi K3 routed experts: hidden 7168, inter 1536, 14 experts
9 - [8192, 3072, 7168, 14]10 - [8192, 3072, 7168, 14]
11+ qwen3_235b: # Qwen3-235B-A22B (Qwen3 series, not Qwen3.5) routed experts: 16384 tokens x top-8, 96 experts
12+ - [131072, 3072, 4096, 96]
13+ - [131072, 4096, 1536, 96]
@@ -1,12 +1,20 @@
1# Shapes for benchmark_qat_linear.py: [[M, N, K], ...].1# Shapes for benchmark_qat_linear.py: [[M, N, K], ...].
2shapes:2shapes:
3- small:3+ small: # boundary smoke shapes (no real-model mapping)
4 - [64, 256, 256]4 - [64, 256, 256]
5 - [256, 1024, 1024]5 - [256, 1024, 1024]
6- qwen2_5:6+ qwen3_5: # Qwen3.5-series projections (existing family, hidden 7168 variant; M=2048)
7+ - [2048, 1536, 7168]
8+ - [2048, 7168, 1536]
9+ kimi_k3: # Kimi K3 dense projections: hidden 7168, inter 1536 (matches the gmm kimi_k3 family)
10+ - [8192, 3072, 7168]
11+ - [8192, 7168, 3072]
12+ qwen2_5: # Qwen2.5 dense projections: hidden 896 (existing family)
7 - [2048, 896, 896]13 - [2048, 896, 896]
8 - [2048, 4864, 896]14 - [2048, 4864, 896]
9 - [2048, 896, 4864]15 - [2048, 896, 4864]
10- qwen3_5:16+ qwen3_235b: # Qwen3-235B-A22B (Qwen3 series, not Qwen3.5) dense projections: hidden 4096, q 8192, kv 512, M=16384 (batch 4 x seq 4096)
11- - [2048, 1536, 7168]17+ - [16384, 8192, 4096]
12- - [2048, 7168, 1536]18+ - [16384, 4096, 8192]
19+ - [16384, 512, 4096]
20+ - [16384, 4096, 4096]
@@ -1,6 +1,6 @@
1# 量化感知训练(QAT)工作流1# 量化感知训练(QAT)工作流
2 2 
3-本文梳理 torchao-ascend 当前支持的 **QAT(Quantization-Aware Training)** 特性。QAT 与量化训练(真低精反向、追求训练效率)不同:其目标是**让模型在训练中适应量化网格,使最终 convert 出的量化推理模型精度损失最小**——master 权重保持高精度,forward 在线模拟部署量化形态,训练结束后固化。量化训练的内容见 [量化训练工作流](./Quantized_Training.md)。3+本文梳理 torchao-ascend 当前支持的 **QAT(Quantization-Aware Training)** 特性。QAT 与量化训练(真低精反向、追求训练效率)不同:其目标是**让模型在训练中适应量化网格,使最终 convert 出的量化推理模型精度损失最小**——master 权重保持高精度,forward 在线模拟部署量化形态,训练结束后固化。量化训练的内容见 [量化训练工作流](./quantized_training.md)。
4 4 
5## 总览5## 总览
6 6 
@@ -2,7 +2,7 @@
2 2 
3本文梳理 torchao-ascend 当前支持的**量化训练**(quantized training)特性,即训练场景下的低精度方案。核心维度为:**每种低精度类型支持对哪些层/算子做量化**(模块层如 `torch.nn.Linear`、MoE 专家;算子层如 `torch.matmul` / grouped matmul),以及对应的实现机制与入口 API。3本文梳理 torchao-ascend 当前支持的**量化训练**(quantized training)特性,即训练场景下的低精度方案。核心维度为:**每种低精度类型支持对哪些层/算子做量化**(模块层如 `torch.nn.Linear`、MoE 专家;算子层如 `torch.matmul` / grouped matmul),以及对应的实现机制与入口 API。
4 4 
5-> 范围说明:本文**不涉及 QAT(量化感知训练)相关适配**(如 `features/qat/w4a8` 的 QAT 注入),相关内容见 [W4A8 QAT 使用说明](../../W4A8_QAT_usage.md)。5+> 范围说明:本文仅覆盖**真低精量化训练**(MXFP8 E4M3);`W4A8`/`W8A16`/`W8A8` QAT 形态不在本文范围内,见 [QAT 工作流](./quantization_aware_training.md) 与 [W4A8 QAT 使用说明](../../W4A8_QAT_usage.md)。
6 6 
7## 总览7## 总览
8 8 
@@ -11,9 +11,7 @@
11| HiFloat8 (HIF8) | `nn.Linear` | ❌ | 模块 swap → `HiFloat8Linear` | `quantize_(model, HiFloat8LinearConfig(), filter_fn=...)` |11| HiFloat8 (HIF8) | `nn.Linear` | ❌ | 模块 swap → `HiFloat8Linear` | `quantize_(model, HiFloat8LinearConfig(), filter_fn=...)` |
12| Float8 tensorwise / rowwise | `nn.Linear`(上游 `Float8Linear`);MoE 专家(rowwise) | ✅(rowwise) | dense:tensor subclass 分发,仅重绑定内核;MoE:wrapper 拦截 `torch._grouped_mm` 的 GMM 替换 | dense:`convert_to_float8_training(model, Float8LinearConfig)`;MoE:`quantize_` + `Float8TrainingOpConfig.from_recipe(FP8_ROWWISE)` |12| Float8 tensorwise / rowwise | `nn.Linear`(上游 `Float8Linear`);MoE 专家(rowwise) | ✅(rowwise) | dense:tensor subclass 分发,仅重绑定内核;MoE:wrapper 拦截 `torch._grouped_mm` 的 GMM 替换 | dense:`convert_to_float8_training(model, Float8LinearConfig)`;MoE:`quantize_` + `Float8TrainingOpConfig.from_recipe(FP8_ROWWISE)` |
13| Blockwise FP8 | `nn.Linear` | ❌ | 上游模块 + forward 重绑定 | `quantize_` + 上游 Blockwise config |13| Blockwise FP8 | `nn.Linear` | ❌ | 上游模块 + forward 重绑定 | `quantize_` + 上游 Blockwise config |
14-| MXFP8(含 W8A8 格式) | `nn.Linear` + MoE 专家 | ✅ | Linear 就地 patch forward;MoE 模块替换 | `quantize_` + `MXFP8LinearConfig` / `MXFP8GMMConfig` |14+| MXFP8 | `nn.Linear` + MoE 专家 | ✅ | Linear 就地 patch forward;MoE 模块替换 | `quantize_` + `MXFP8LinearConfig` / `MXFP8GMMConfig` |
15-| W4A8(MXFP4 权重重缩放为 FP8 载荷) | `nn.Linear` + MoE 专家 | ✅ | 同 MXFP8 系(`quant_format="W4A8"` 变体) | `MXFP8LinearConfig(quant_format="W4A8")` 等 |
16-| W8A16 | — | — | 未实现(见下文) | — |
17 15 
18## 各类型量化目标详解16## 各类型量化目标详解
19 17 
@@ -169,15 +167,89 @@ python benchmark_scaled_grouped_mm_dq.py --shapes all
169- **入口**:`quantize_` + 上游 Blockwise config(无独立入口)。167- **入口**:`quantize_` + 上游 Blockwise config(无独立入口)。
170- **限制**:仅 block_size=128;不支持 MoE。168- **限制**:仅 block_size=128;不支持 MoE。
171 169 
172-### MXFP8 / MX 系列(含 W8A8、W4A8 变体)170+### MXFP8
173 171 
174- **dense Linear**:`MXFP8LinearConfig` handler **就地 patch module.forward**(不替换模块类、不动参数对象),内部调上游 `mx_mm`,其 forward/backward 已在 NPU 侧重绑定(plain 路径 `torch._scaled_mm`,lp_ag / jit_quant 路径 `mx_quant_matmul`)。约束:block_size=32、缩放 AUTO、舍入 FLOOR/RCEIL;任一维度 <64 的 Linear 自动跳过(`filters.py`)。172- **dense Linear**:`MXFP8LinearConfig` handler **就地 patch module.forward**(不替换模块类、不动参数对象),内部调上游 `mx_mm`,其 forward/backward 已在 NPU 侧重绑定(plain 路径 `torch._scaled_mm`,lp_ag / jit_quant 路径 `mx_quant_matmul`)。约束:block_size=32、缩放 AUTO、舍入 FLOOR/RCEIL;任一维度 <64 的 Linear 自动跳过(`filters.py`)。
175- **MoE 专家**:`MXFP8GMMConfig` 将 MoE 专家容器**模块替换**为 `MXFP8GMM`(permute → grouped GMM → swiglu → grouped GMM → unpermute),可微内核 `MxGroupedMatmul` 的 dgrad / wgrad 均为真低精 grouped GEMM(`torchao_ascend/features/training/mxfp8/`)。173- **MoE 专家**:`MXFP8GMMConfig` 将 MoE 专家容器**模块替换**为 `MXFP8GMM`(permute → grouped GMM → swiglu → grouped GMM → unpermute),可微内核 `MxGroupedMatmul` 的 dgrad / wgrad 均为真低精 grouped GEMM(`torchao_ascend/features/training/mxfp8/`)。
176 - 调用方持有本地 BF16 专家权重 `[专家数, 输出维, 输入维]` 时,可显式调用 `mx_quant_group_gemm(..., weight_layout="EOI")`,由算子从原权重生成两个量化方向的操作数。该入口使用 E4M3 配置及累计 token 末端位置(`group_list_type=0`),最后一个末端位置等于输入 token 总数。空专家可使用重复末端位置。174 - 调用方持有本地 BF16 专家权重 `[专家数, 输出维, 输入维]` 时,可显式调用 `mx_quant_group_gemm(..., weight_layout="EOI")`,由算子从原权重生成两个量化方向的操作数。该入口使用 E4M3 配置及累计 token 末端位置(`group_list_type=0`),最后一个末端位置等于输入 token 总数。空专家可使用重复末端位置。
177 非连续权重在量化前转换为连续布局。已连续的 EOI 权重复用原存储。175 非连续权重在量化前转换为连续布局。已连续的 EOI 权重复用原存储。
178 - `weight_layout` 默认值为 `None`,沿用原布局识别。显式 `"EOI"` 仅接收本地 BF16 权重,量化权重包装器和 DTensor 使用原入口。推理可在 `torch.no_grad()` 内设置 `grad_enabled=False`,跳过反向所需的权重量化。176 - `weight_layout` 默认值为 `None`,沿用原布局识别。显式 `"EOI"` 仅接收本地 BF16 权重,量化权重包装器和 DTensor 使用原入口。推理可在 `torch.no_grad()` 内设置 `grad_enabled=False`,跳过反向所需的权重量化。
179-- **变体**:
180- - `quant_format="W4A8"`:权重先量化到 MXFP4,再经 `mx_to_block_mx_quant` 无损重缩放为 FP8 载荷复用 FP8 GEMM(dense / LP-AG / MoE GMM 三条路径均支持);
181- - E4M3 / HYBRID / HIF8 格式即 W8A8 训练形态。
182- **入口**:`quantize_` + `MXFP8LinearConfig`;MoE 用 `MXFP8GMMConfig.from_linear` + `moe_filter_fn`(`filters.py`)。177- **入口**:`quantize_` + `MXFP8LinearConfig`;MoE 用 `MXFP8GMMConfig.from_linear` + `moe_filter_fn`(`filters.py`)。
183- **限制**:仅 Linear + MoE 专家;conv 不直接支持。178- **限制**:仅 Linear + MoE 专家;conv 不直接支持。
179+ 
180+#### 模块级训练基准
181+ 
182+使用不同的 shape 组合测试 MXFP8 四种变体在不同模块上的量化训练性能。脚本为 `benchmarks/prototype/mxfp8/`(`--shapes-file/--recipes-file` 驱动,与 hifloat8 基准同构),四种变体与端到端一一对应:
183+ 
184+- `MXFP8_PLAIN` / `MXFP8_JIT_QUANT`:`quantize_` + `MXFP8LinearConfig(quant_mode=...)` 的 dense 模块路径;
185+- `MXFP8_LP_AG` / `MXFP8_LP_AG_RESHARD`:权重经 all-gather 前的一次双轴量化,以 `PostQuantWeight` pair 常驻(pair 在计时区外构建,对应 all-gather 阶段),GEMM 消费 pair——`lp_ag_reshard` 的 GEMM 消费与 `lp_ag` 完全一致(差异仅在 FSDP reshard 拓扑),数据同列呈现。
186+ 
187+##### Linear
188+ 
189+**环境**:Ascend 950DT 单卡,torchao 0.18.0 + torch_npu,BF16 `F.linear` 为基线,eager 训练路径(fwd+bwd)。
190+**对比**:四种变体的 scaled 路径相对 BF16 的 speedup(数值 >1 表示量化更快)。
191+ 
192+| Shape (M, N, K) | 模型投影 | MXFP8_PLAIN | MXFP8_JIT_QUANT | MXFP8_LP_AG | MXFP8_LP_AG_RESHARD |
193+|---|---|---|---|---|---|
194+| (16384, 8192, 4096) | Qwen3 q_proj | 1.49× | 1.69× | 2.40× | 2.40× |
195+| (16384, 4096, 8192) | Qwen3 o_proj | 1.50× | 1.72× | 2.50× | 2.49× |
196+| (16384, 512, 4096) | Qwen3 k/v_proj | 0.72× | 1.06× | 1.34× | 1.34× |
197+| (16384, 4096, 4096) | 方形参照 | 1.38× | 1.61× | 2.27× | 2.27× |
198+ 
199+- **变体收益梯度 plain < jit_quant < lp_ag**:lp_ag 跳过每步的权重双轴量化(量化发生在 all-gather 阶段、计时区外),fwd+bwd 收益再升 40-50%;k/v 小 N 投影上 plain 劣化(0.72×)、jit_quant 打平、lp_ag 转正(1.34×)。
200+- **lp_ag 列的口径**:权重量化计入 all-gather 阶段(端到端中该阶段与 FP8 通信减半合并为 LP-AG 收益),模块级只呈现 GEMM 消费;k/v 投影在 lp_ag 口径下转正,说明其劣化完全来自权重量化开销而非 FP8 GEMM。
201+- **可以使用python 脚本复现上述基准**:`python ./benchmarks/prototype/mxfp8/benchmark_mxfp8_linear.py --shapes qwen3_235b`
202+ 
203+##### grouped GEMM
204+ 
205+**环境**:Ascend 950DT 单卡,torchao 0.18.0 + torch_npu,BF16 `torch._grouped_mm` 为基线,eager 训练路径(fwd+bwd)。
206+**对比**:`MXFP8_GMM_JIT` = `MXFP8GMMConfig.from_float` 全链(`mx_quant_group_gemm`,含每次 forward 的双轴专家权重量化)。
207+ 
208+| Shape (M, N, K, G) | 模型 | MXFP8_GMM_JIT |
209+|---|---|---|
210+| (131072, 3072, 4096, 96) | Qwen3 gate/up | 1.14× |
211+| (131072, 4096, 1536, 96) | Qwen3 down | 1.18× |
212+ 
213+- **训练(fwd+bwd)提速 1.14–1.18×**:形状与端到端整网完全一致(M=131072 = 16384 token × top-8、G=96);BF16 孪生为纯 GEMM 内核,MXFP8 全链额外计入 jit 语义每步的双轴专家权重量化辅助 kernel(fwd 口径 0.96–1.09×)。
214+- **lp_ag / lp_ag_reshard 变体依赖 EP dispatcher 的 permute 与 group_list 语义**(`MXFP8GMM` 消费 EP dispatch 后的 token 布局),模块级复现的调用形态与端到端不一致(grouped kernel 参数校验不通过),其 grouped 差异以端到端训练基准为准。
215+- **与 Linear 路径互补**:attention 投影(q/k/v/o_proj)走 Linear 基准的 dense 路径,MoE 专家走本分组路径,共同覆盖整网的量化模块。
216+- **可以使用python 脚本复现上述基准**:`python ./benchmarks/prototype/mxfp8/benchmark_mxfp8_grouped_mm.py --shapes qwen3_235b`
217+ 
218+#### 端到端训练基准
219+ 
220+使用 [FSDPTurbo](https://gitcode.com/Ascend/FSDPTurbo) 测试了 mxfp8 训练性能。
221+ 
222+##### Ascend950DT
223+ 
224+模型为 Qwen3-235B-A22B 的等效剪枝(前 4 个 decoder 层、每层前 96 个路由专家,真实权重切片,17.6GB BF16),8 卡 EP=8,100 步训练(稳态取步 20-100 均值),四种变体与 BF16 的 100 步 loss 逐位一致。
225+ 
226+| Model | Scaling | Peak Memory (GB) | Median tokens/second | Speedup over baseline |
227+| ------------- | ---------------------------------- | ------- | ------ | ------- |
228+| Qwen3-235B-A22B(剪枝 4L/96E) | none (bfloat16), batch 4 × seq 4096 | 45.58 | 15019 | - |
229+| Qwen3-235B-A22B(剪枝 4L/96E) | mxfp8 plain | 45.58 | 18017 | +20.0% |
230+| Qwen3-235B-A22B(剪枝 4L/96E) | mxfp8 jit_quant | 45.58 | 18255 | +21.5% |
231+| Qwen3-235B-A22B(剪枝 4L/96E) | mxfp8 lp_ag (on-demand) | 45.98 | 18277 | +21.7% |
232+| Qwen3-235B-A22B(剪枝 4L/96E) | mxfp8 lp_ag (reshard_after_forward=false) | 45.98 | 18262 | +21.6% |
233+ 
234+GEMM kernel 分解(jit_quant 第 50 步 profile,rank 0;量化覆盖部分已打满 FP8:BF16 = 2:1 的理论收益):
235+ 
236+| 类别 | BF16 (ms) | MXFP8 jit_quant (ms) | 实际收益 |
237+|---|---|---|---|
238+| MoE 分组 GEMM(GroupedMatmul) | 279.4 | 141.3 | +49.4% |
239+| Dense 量化投影(q/k/v/o) | 87.1 | 44.0 | +49.5% |
240+| Dense 未量化(attention bmm + lm_head) | 144.1 | 144.2 | 0% |
241+| 通信(A2A token 字节减半) | 356.0 | 299.9 | +15.7% |
242+ 
243+- **量化收益的成立条件是 matmul 主导的步时结构**:debug 形状(batch 1 × seq 128,matmul 占比 < 7%)下四种变体全部劣化(plain +6.3%、jit_quant +7.6%、lp_ag +33.5%);batch 4 × seq 4096(16K token)下全部反超约 +17.7%(步时口径)/ +21.5%(吞吐口径)。
244+- **LP-AG 在单节点上 clone 开销与 all-gather 字节节省相抵**(S0 的 +33.5% 劣化在 S2 已收敛),其净收益需跨节点 EP(all-gather 跨网带宽低 1-2 个数量级)验证。
245+ 
246+**复现训练基准**
247+为了复现上述训练基准,您可以按照以下步骤操作:
248+ 
249+1. 在当前可用的NPU环境上, 先按照以下步骤安装 [FSDPTurbo](https://gitcode.com/Ascend/FSDPTurbo)。
250+2. 安装 torchao_ascend 插件,参考 [安装 torchao_ascend 插件](../install.md)。
251+3. 在 `torchao_ascend/` 目录下,运行以下命令生成等效剪枝检查点并执行单卡 smoke:
252+ - `python examples/qwen3/qwen3_moe_mxfp8_train.py --prune-src <完整Qwen3-235B-A22B目录> --prune-dst ./qwen3_235b_pruned`
253+ - `bash examples/qwen3/moe_mxfp8_train.sh`
254+4. 8 卡整网基准使用同一份剪枝检查点与量化配置(`qwen3_5_moe_mxfp8_train_config.yaml`),由 FSDPTurbo 以 `torch.distributed.fsdp.fully_shard` 原生协议驱动 100 步训练。
255+ 
@@ -0,0 +1,34 @@
1+#!/bin/bash
2+# Copyright (c) 2026, Huawei Technologies Co., Ltd
3+#
4+# Qwen3-235B-A22B(剪枝版)MXFP8 量化训练一键脚本(dense mx_mm + MoE MXFP8GMM)
5+# 用法:
6+# bash moe_mxfp8_train.sh # 用默认 yaml
7+# STEPS=50 bash moe_mxfp8_train.sh # 只训 50 步
8+# CONFIG_FILE=my.yaml bash moe_mxfp8_train.sh
9+# 前置:剪枝检查点已就绪(--prune-src 一键生成,路径见 yaml 的 model.path)。
10+# 脚本以自身所在目录锚定 py/config 路径,可在任意工作目录执行。
11+ 
12+set -e
13+ 
14+export ASCEND_RT_VISIBLE_DEVICES=${ASCEND_RT_VISIBLE_DEVICES:-0}
15+ 
16+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
17+cd "$SCRIPT_DIR"
18+ 
19+CONFIG_FILE=${CONFIG_FILE:-"qwen3_moe_mxfp8_train_config.yaml"}
20+EXTRA_ARGS=()
21+if [[ -n "${STEPS:-}" ]]; then
22+ EXTRA_ARGS+=(--steps "$STEPS")
23+fi
24+ 
25+echo "============================================================"
26+echo " Qwen3-235B (pruned) MXFP8 training (dense + MoE GMM)"
27+echo " ASCEND_RT_VISIBLE_DEVICES: $ASCEND_RT_VISIBLE_DEVICES"
28+echo " CONFIG: $CONFIG_FILE"
29+echo " STEPS: ${STEPS:-as in config}"
30+echo "============================================================"
31+ 
32+python3 qwen3_moe_mxfp8_train.py \
33+ --config "$CONFIG_FILE" \
34+ "${EXTRA_ARGS[@]}"
@@ -0,0 +1,355 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+#
3+# -*- coding: utf-8 -*-
4+"""Qwen3-235B-A22B(剪枝版)MXFP8 量化训练(dense Linear + MoE 分组 GEMM)。
5+ 
6+quantize_ 按 config 精确类型分发:
7+- ``MXFP8LinearConfig`` + ``module_filter_fn``:attention q/k/v/o 投影就地
8+ patch forward,走 NPU mx_mm(plain 路径 torch._scaled_mm / jit_quant 路径
9+ mx_quant_matmul),任一维度 < 64 的 Linear 自动跳过;
10+- ``MXFP8GMMConfig.from_linear`` + ``moe_filter_fn``:MoE 专家容器替换为
11+ MXFP8GMM(permute → FP8 分组 GEMM → swiglu → 分组 GEMM → unpermute)。
12+ 
13+与 examples/qwen3_5/qwen3_5_moe_fp8_rowwise_train.py 的 FP8 rowwise 路径
14+(Float8TrainingOpConfig weight wrapper)不同,MXFP8 是模块级路径:dense
15+走 mx_mm autograd Function,MoE 走 MXFP8GMM 类交换,两者共用
16+MXFP8LinearConfig 的 quant_format/quant_mode 配置。
17+ 
18+模型来自完整 Qwen3-235B-A22B 的等效剪枝(--prune-src 一键生成):只保留前
19+--prune-layers 个 decoder 层与每层前 --prune-experts 个路由专家(真实权重
20+切片),router gate 第一维随专家数截断,embedding/lm_head/norm 保留——
21+规模收缩到单卡可训,权重分布不失真。
22+ 
23+MoE 前向改写:HF 原生 Qwen3MoeExperts 是逐专家 F.linear 循环,BF16 对照会
24+被 96 次 kernel launch 主导、量化收益失真——调用共享 patch
25+``modeling_qwen3_5_moe.apply_grouped_mm_forward``(fp8 rowwise 示例同款)
26+把专家前向换成单次 jagged ``torch._grouped_mm``(BF16 / MXFP8 数值等价)。
27+Qwen3MoeExperts 与 Qwen3_5MoeExperts 的 forward 签名与成员一致
28+(num_experts/gate_up_proj/down_proj/act_fn),函数体与模型类无关,仅
29+绑定目标类不同——本模型剪枝自 Qwen3-235B-A22B(Qwen3 类),故传
30+``experts_cls=Qwen3MoeExperts``。
31+ 
32+单卡 smoke 用法:
33+ python3 qwen3_moe_mxfp8_train.py --prune-src <完整模型> --prune-dst ./qwen3_235b_pruned
34+ bash moe_mxfp8_train.sh
35+ 或 python3 qwen3_moe_mxfp8_train.py --steps 20
36+ 
37+数据:dataset.path 下 jsonl(text 列);未就绪时自动降级为合成随机 token
38+(仅验证链路,loss 无意义)。8 卡 FSDP2 端到端基准数据见
39+docs/zh/workflows/quantized_training.md 的端到端训练基准一节。
40+"""
41+ 
42+from __future__ import annotations
43+ 
44+from __future__ import annotations
45+ 
46+import argparse
47+import json
48+import logging
49+import os
50+import re
51+import shutil
52+import sys
53+import time
54+from pathlib import Path
55+from typing import Any
56+ 
57+_EXPERT_RE = re.compile(r"^model\.layers\.(\d+)\.mlp\.experts\.(\d+)\.(.+)$")
58+ 
59+import torch
60+import yaml
61+ 
62+import torchao_ascend # noqa: F401 激活 NPU patches 与 KernelPreference
63+from torchao.quantization import quantize_
64+from torchao_ascend.features.training.mxfp8 import (
65+ MXFP8GMMConfig,
66+ MXFP8LinearConfig,
67+ module_filter_fn,
68+ moe_filter_fn,
69+)
70+ 
71+logging.basicConfig(level=logging.INFO, format="%(message)s")
72+logger = logging.getLogger("qwen3_moe_mxfp8_train")
73+ 
74+BASE_DIR = Path(__file__).resolve().parent
75+# 共享 MoE 前向 patch 定义在 examples/qwen3_5/(fp8 rowwise 示例同款),
76+# qwen3 目录复用时把该目录加入模块搜索路径。
77+sys.path.insert(0, str(BASE_DIR.parent / "qwen3_5"))
78+CONFIG_FILE = "qwen3_moe_mxfp8_train_config.yaml"
79+ 
80+# grouped_mm 的 token 分组对齐:每专家 token 数向上取整到 16(与
81+# modeling_qwen3_5_moe.py 一致),padding 行输出 0 并丢弃。
82+_ALIGN_NOTE = "alignment=16"
83+ 
84+ 
85+# ---------------- 等效剪枝(源目录只读) ----------------
86+def build_pruned_checkpoint(src: str, dst: str, keep_layers: int, keep_experts: int,
87+ shard_bytes: int = 4 * 1024 ** 3) -> None:
88+ """从完整 Qwen3-235B-A22B 构建剪枝检查点:前 keep_layers 层、每层前
89+ keep_experts 个专家(真实权重切片),router gate 第一维随专家数截断,
90+ embedding/lm_head/norm 保留,config 同步。"""
91+ from safetensors import safe_open
92+ from safetensors.torch import save_file
93+ 
94+ if not Path(src).is_dir():
95+ raise FileNotFoundError(f"源模型目录不存在:{src}(脚本从不创建/修改源目录)")
96+ if Path(src).resolve() == Path(dst).resolve():
97+ raise ValueError("输出目录不能与源目录相同(源目录只读)")
98+ 
99+ with open(os.path.join(src, "model.safetensors.index.json")) as f:
100+ index = json.load(f)["weight_map"]
101+ config = json.load(open(os.path.join(src, "config.json")))
102+ config["num_hidden_layers"] = keep_layers
103+ config["num_experts"] = keep_experts
104+ config.pop("quantization_config", None)
105+ 
106+ kept = {}
107+ for name, shard in index.items():
108+ m = _EXPERT_RE.match(name)
109+ if m:
110+ keep = int(m.group(1)) < keep_layers and int(m.group(2)) < keep_experts
111+ elif name.startswith("model.layers."):
112+ keep = int(name.split(".")[2]) < keep_layers
113+ else:
114+ keep = True
115+ if keep:
116+ kept[name] = shard
117+ print(f"保留 {len(kept)}/{len(index)} 个张量")
118+ 
119+ by_shard: dict[str, list[str]] = {}
120+ for name, shard in kept.items():
121+ by_shard.setdefault(shard, []).append(name)
122+ 
123+ os.makedirs(dst, exist_ok=True)
124+ out_tensors, shard_files, cur_bytes, shard_id = {}, [], 0, 0
125+ 
126+ def flush() -> None:
127+ nonlocal shard_id, cur_bytes
128+ if not out_tensors:
129+ return
130+ shard_id += 1
131+ fname = f"model-{shard_id:05d}-of-?????.safetensors"
132+ save_file(out_tensors, os.path.join(dst, fname))
133+ shard_files.append(fname)
134+ out_tensors.clear()
135+ cur_bytes = 0
136+ 
137+ for shard in sorted(by_shard):
138+ with safe_open(os.path.join(src, shard), framework="pt") as f:
139+ for name in by_shard[shard]:
140+ tensor = f.get_tensor(name)
141+ if ".mlp.gate." in name and tensor.shape[0] > keep_experts:
142+ # router gate 第一维 = 全量专家数,随专家数截断
143+ tensor = tensor[:keep_experts].contiguous()
144+ out_tensors[name] = tensor
145+ cur_bytes += tensor.numel() * tensor.element_size()
146+ if cur_bytes >= shard_bytes:
147+ flush()
148+ flush()
149+ 
150+ total = shard_id
151+ real_files = []
152+ for i, fname in enumerate(shard_files, 1):
153+ real = fname.replace("-of-?????", f"-of-{total:05d}")
154+ os.rename(os.path.join(dst, fname), os.path.join(dst, real))
155+ real_files.append(real)
156+ weight_map = {}
157+ for fname in real_files:
158+ with safe_open(os.path.join(dst, fname), framework="pt") as f:
159+ for name in f.keys():
160+ weight_map[name] = fname
161+ with open(os.path.join(dst, "model.safetensors.index.json"), "w") as f:
162+ json.dump({"metadata": {"total_size": len(weight_map)},
163+ "weight_map": weight_map}, f, indent=2)
164+ with open(os.path.join(dst, "config.json"), "w") as f:
165+ json.dump(config, f, indent=2, ensure_ascii=False)
166+ for fname in os.listdir(src):
167+ if fname.startswith(("tokenizer", "vocab", "merges", "special_tokens",
168+ "added_tokens", "generation_config")):
169+ shutil.copy(os.path.join(src, fname), os.path.join(dst, fname))
170+ print(f"剪枝检查点已写入 {dst}({total} 个分片)")
171+ 
172+ 
173+# ---------------- 配置与数据 ----------------
174+def load_config(path: str | None) -> dict[str, Any]:
175+ """读取 YAML 配置;相对路径相对脚本目录解析。"""
176+ cands = [Path(path)] if path else []
177+ cands += [BASE_DIR / CONFIG_FILE, Path(CONFIG_FILE)]
178+ chosen = next((c for c in cands if c.is_file()), None)
179+ if chosen is None:
180+ raise FileNotFoundError(f"找不到配置文件 {CONFIG_FILE}(脚本目录 {BASE_DIR})")
181+ with open(chosen, "r", encoding="utf-8") as f:
182+ return yaml.safe_load(f) or {}
183+ 
184+ 
185+def build_dataloader(cfg: dict[str, Any], tokenizer, seq_len: int, batch: int):
186+ """本地 jsonl(text 列)优先,缺省降级为合成随机 token。"""
187+ import torch.utils.data as data
188+ 
189+ dpath = (BASE_DIR / cfg["dataset"]["path"]).resolve()
190+ texts = []
191+ if dpath.is_file():
192+ with open(dpath, "r", encoding="utf-8") as f:
193+ for line in f:
194+ texts.append(json.loads(line).get("text", ""))
195+ logger.info(f"[data] 本地数据 {dpath.name}: {len(texts)} 行")
196+ if not texts:
197+ logger.info("[data] 未找到本地数据,使用合成随机 token(仅验证链路)")
198+ vocab = tokenizer.vocab_size if tokenizer is not None else 151936
199+ 
200+ class _Synthetic(data.Dataset):
201+ def __len__(self):
202+ return 1024
203+ 
204+ def __getitem__(self, _):
205+ return torch.randint(0, vocab, (seq_len,))
206+ 
207+ pad_id = tokenizer.pad_token_id if tokenizer is not None else 0
208+ 
209+ def _synth_collate(rows):
210+ ids = torch.stack(rows).long()
211+ return {"input_ids": ids.npu(),
212+ "labels": ids.masked_fill(ids == pad_id, -100).npu()}
213+ 
214+ return data.DataLoader(_Synthetic(), batch_size=batch,
215+ collate_fn=_synth_collate)
216+ 
217+ encoded = [
218+ tokenizer(t, truncation=True, max_length=seq_len)["input_ids"]
219+ for t in texts if t
220+ ]
221+ 
222+ class _Jsonl(data.Dataset):
223+ def __len__(self):
224+ return len(encoded)
225+ 
226+ def __getitem__(self, i):
227+ return torch.tensor(encoded[i])
228+ 
229+ def collate(rows):
230+ ids = torch.stack([
231+ torch.nn.functional.pad(
232+ r, (0, seq_len - len(r)), value=tokenizer.pad_token_id or 0)
233+ for r in rows]).long()
234+ return {"input_ids": ids.npu(), "labels": ids.npu().clone()}
235+ 
236+ return data.DataLoader(_Jsonl(), batch_size=batch, collate_fn=collate)
237+ 
238+ 
239+# ---------------- 模型构建与 MXFP8 转换 ----------------
240+def build_model(model_path: str, num_layers: int | None,
241+ num_experts: int | None) -> torch.nn.Module:
242+ """装载(剪枝)检查点;num_layers/num_experts>0 时进一步截断结构。"""
243+ from transformers import AutoConfig, AutoModelForCausalLM
244+ 
245+ config = AutoConfig.from_pretrained(model_path)
246+ if num_layers:
247+ config.num_hidden_layers = num_layers
248+ if num_experts:
249+ config.num_experts = num_experts
250+ config.use_cache = False
251+ model = AutoModelForCausalLM.from_pretrained(
252+ model_path, config=config, torch_dtype=torch.bfloat16)
253+ return model.to("npu")
254+ 
255+ 
256+def apply_mxfp8(model: torch.nn.Module, quant_mode: str,
257+ apply_modules: list[str], ignored_modules: list[str]) -> None:
258+ """dense Linear(mx_mm patch forward)+ MoE 专家(MXFP8GMM 类交换)。"""
259+ dense_cfg = MXFP8LinearConfig(
260+ quant_mode=quant_mode,
261+ mxfp8_apply_modules=apply_modules,
262+ mxfp8_ignored_modules=ignored_modules,
263+ enable_fsdp_low_precision_all_gather=False, # 单卡示例无 FSDP all-gather
264+ )
265+ quantize_(model, dense_cfg, filter_fn=module_filter_fn(dense_cfg))
266+ quantize_(model, MXFP8GMMConfig.from_linear(dense_cfg),
267+ filter_fn=moe_filter_fn(dense_cfg))
268+ # dense 路径是就地 patch forward(不换模块类),转换标志是 _quant_config
269+ n_gmm = sum(1 for m in model.modules() if type(m).__name__ == "MXFP8GMM")
270+ n_linear = sum(1 for m in model.modules()
271+ if getattr(m, "_quant_config", None) is not None
272+ and type(m).__name__ != "MXFP8GMM")
273+ logger.info(f"[mxfp8] MXFP8Linear x {n_linear}, MXFP8GMM x {n_gmm} "
274+ f"(quant_mode={quant_mode})")
275+ if n_linear == 0 or n_gmm == 0:
276+ raise RuntimeError("MXFP8 转换未命中任何模块,请检查 apply_modules 配置")
277+ 
278+ 
279+def main() -> None:
280+ parser = argparse.ArgumentParser(
281+ description="Qwen3-235B 剪枝版 MXFP8 量化训练(含等效剪枝)",
282+ formatter_class=argparse.ArgumentDefaultsHelpFormatter)
283+ parser.add_argument("--config", default=None, help="YAML 配置路径")
284+ parser.add_argument("--steps", type=int, default=None, help="覆盖训练步数")
285+ parser.add_argument("--prune-src", default=None,
286+ help="完整 Qwen3-235B-A22B 目录(只读);给出即先执行等效剪枝再训练")
287+ parser.add_argument("--prune-dst", default=None, help="剪枝输出目录")
288+ parser.add_argument("--prune-layers", type=int, default=4, help="保留的 decoder 层数")
289+ parser.add_argument("--prune-experts", type=int, default=96, help="每层保留的路由专家数")
290+ args = parser.parse_args()
291+ 
292+ cfg = load_config(args.config)
293+ steps = args.steps or cfg["training"]["steps"]
294+ seq_len = int(cfg["training"]["seq_len"])
295+ batch = int(cfg["training"]["batch"])
296+ num_layers = cfg["model"].get("num_layers")
297+ num_experts = cfg["model"].get("num_experts")
298+ 
299+ model_path = (BASE_DIR / cfg["model"]["path"]).resolve()
300+ if args.prune_src:
301+ dst = args.prune_dst or str(model_path)
302+ build_pruned_checkpoint(args.prune_src, dst,
303+ args.prune_layers, args.prune_experts)
304+ model_path = Path(dst)
305+ if not model_path.is_dir():
306+ raise FileNotFoundError(
307+ f"模型目录 {model_path} 不存在:先运行剪枝(--prune-src 完整模型目录)"
308+ "或把已剪枝检查点放到 yaml 的 model.path")
309+ 
310+ from transformers import AutoTokenizer
311+ from modeling_qwen3_5_moe import apply_grouped_mm_forward
312+ 
313+ torch.manual_seed(int(cfg["training"].get("seed", 123)))
314+ torch.npu.set_device(0)
315+ tokenizer = AutoTokenizer.from_pretrained(model_path)
316+ model = build_model(str(model_path), num_layers, num_experts)
317+ from transformers.models.qwen3_moe.modeling_qwen3_moe import Qwen3MoeExperts
318+ n_experts = apply_grouped_mm_forward(model, experts_cls=Qwen3MoeExperts)
319+ logger.info(f"[moe] grouped_mm forward applied to {n_experts} expert containers")
320+ apply_mxfp8(model, cfg["mxfp8"].get("quant_mode", "jit_quant"),
321+ cfg["mxfp8"].get("apply_modules", []),
322+ cfg["mxfp8"].get("ignored_modules", []))
323+ 
324+ loader = build_dataloader(cfg, tokenizer, seq_len, batch)
325+ optimizer = torch.optim.AdamW(
326+ model.parameters(), lr=float(cfg["training"]["lr"]))
327+ 
328+ model.train()
329+ t0 = time.perf_counter()
330+ run_loss, seen = 0.0, 0
331+ it = iter(loader)
332+ for step in range(1, steps + 1):
333+ batch_data = next(it, None)
334+ if batch_data is None:
335+ it = iter(loader)
336+ batch_data = next(it)
337+ batch_data["use_cache"] = False
338+ out = model(**batch_data)
339+ out.loss.backward()
340+ optimizer.step()
341+ optimizer.zero_grad()
342+ run_loss += out.loss.item()
343+ seen += 1
344+ if step % 10 == 0 or step == steps:
345+ avg = run_loss / seen
346+ step_time = (time.perf_counter() - t0) / seen
347+ peak = torch.npu.max_memory_allocated() / 2 ** 30
348+ logger.info(f"step {step:4d} | loss {avg:.6f} | "
349+ f"{step_time:.3f}s/step | peak {peak:.2f} GB")
350+ run_loss, seen, t0 = 0.0, 0, time.perf_counter()
351+ logger.info("done")
352+ 
353+ 
354+if __name__ == "__main__":
355+ main()
@@ -0,0 +1,24 @@
1+# Qwen3-235B-A22B 剪枝版 MXFP8 量化训练配置
2+# 剪枝检查点由 qwen3_moe_mxfp8_train.py --prune-src 生成(等效层数/专家数裁剪,真实权重切片)。
3+model:
4+ path: ./qwen3_235b_pruned
5+ # >0 时进一步截断结构(单卡 smoke 用更小规模);0 表示保持检查点结构
6+ num_layers: 0
7+ num_experts: 0
8+ 
9+dataset:
10+ path: ./data_train.jsonl # text 列 jsonl;文件不存在时自动降级为合成随机 token
11+ # 备选:torchao_ascend 不随仓分发数据,请放置本地 jsonl 或接受合成数据
12+ 
13+training:
14+ seq_len: 4096
15+ batch: 1
16+ steps: 20
17+ lr: 1.0e-4
18+ seed: 123
19+ 
20+mxfp8:
21+ quant_mode: jit_quant # plain / jit_quant(lp_ag 系列需 FSDP all-gather,见端到端基准)
22+ apply_modules:
23+ - "model.layers.{*}"
24+ ignored_modules: []
@@ -17,7 +17,7 @@ from __future__ import annotations
17import torch17import torch
18 18 
19# grouped_mm 的 token 分组对齐。上游 torchao fp8 rowwise 对齐到 1619# grouped_mm 的 token 分组对齐。上游 torchao fp8 rowwise 对齐到 16
20-#(benchmarks/prototype/moe_training/bench_moe_layer.py: alignment_size=16)。20+# (benchmarks/prototype/moe_training/bench_moe_layer.py: alignment_size=16).
21# 每个专家的 token 数向上取整到 ALIGN,避免 grouped GEMM 遇到未对齐或 0 长度(未被路由)21# 每个专家的 token 数向上取整到 ALIGN,避免 grouped GEMM 遇到未对齐或 0 长度(未被路由)
22# 的分组。若 npu_grouped_matmul 要求别的对齐值,改这里即可。22# 的分组。若 npu_grouped_matmul 要求别的对齐值,改这里即可。
23ALIGN = 1623ALIGN = 16
@@ -99,15 +99,20 @@ def _grouped_experts_forward(self, hidden_states, top_k_index, top_k_weights, **
99 return final99 return final
100 100 
101 101 
102-def apply_grouped_mm_forward(model, align=None):102+def apply_grouped_mm_forward(model, align=None, experts_cls=None):
103- """把 Qwen3_5MoeExperts.forward 换成 jagged grouped_mm 版(BF16 / FP8 共用)。103+ """把专家模块的 forward 换成 jagged grouped_mm 版(BF16 / FP8 / MXFP8 共用)。
104 104 
105 返回被改写的专家模块数量。align 为 None 时用模块默认 ALIGN(16)。105 返回被改写的专家模块数量。align 为 None 时用模块默认 ALIGN(16)。
106+ experts_cls 为专家容器类(须与 _grouped_experts_forward 的成员约定一致:
107+ num_experts / gate_up_proj / down_proj / act_fn);缺省 Qwen3_5MoeExperts,
108+ Qwen3-MoE 模型传 transformers 的 Qwen3MoeExperts(签名与成员相同,
109+ 函数体与模型类无关)。
106 """110 """
107 from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeExperts111 from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeExperts
108 global ALIGN112 global ALIGN
109 if align is not None:113 if align is not None:
110 ALIGN = int(align)114 ALIGN = int(align)
111- Qwen3_5MoeExperts.forward = _grouped_experts_forward115+ cls = experts_cls if experts_cls is not None else Qwen3_5MoeExperts
112- n = sum(1 for m in model.modules() if isinstance(m, Qwen3_5MoeExperts))116+ cls.forward = _grouped_experts_forward
117+ n = sum(1 for m in model.modules() if isinstance(m, cls))
113 return n118 return n