| @@ -104,15 +104,19 @@ def main(args): | |||
| 104 | # (torch._grouped_mm / _Float8GroupedMM / _MXFP8GroupedMM), so neither | 104 | # (torch._grouped_mm / _Float8GroupedMM / _MXFP8GroupedMM), so neither |
| 105 | # masks the other. Installed exactly once per ScopeDef. | 105 | # masks the other. Installed exactly once per ScopeDef. |
| 106 | from bf16_grouped_scopes import BF16_GROUPED_SCOPE_DEF | 106 | from bf16_grouped_scopes import BF16_GROUPED_SCOPE_DEF |
| 107 | + from fp8_blockwise_scopes import FP8_BLOCKWISE_SCOPE_DEF | ||
| 107 | from fp8_grouped_scopes import FP8_GROUPED_SCOPE_DEF | 108 | from fp8_grouped_scopes import FP8_GROUPED_SCOPE_DEF |
| 108 | from mxfp8_grouped_scopes import MXFP8_GROUPED_SCOPE_DEF | 109 | from mxfp8_grouped_scopes import MXFP8_GROUPED_SCOPE_DEF |
| 109 | from probe import ScopeDef, install_profiling, set_label | 110 | from probe import ScopeDef, install_profiling, set_label |
| 110 | 111 | ||
| 111 | - has_fp8 = any(r.name.startswith("FP8") for r in recipes) | 112 | + has_fp8_rowwise = any(r.name == "FP8_ROWWISE" for r in recipes) |
| 113 | + has_fp8_blockwise = any(r.name == "FP8_BLOCKWISE" for r in recipes) | ||
| 112 | has_mxfp8 = any(r.name.startswith("MXFP8") for r in recipes) | 114 | has_mxfp8 = any(r.name.startswith("MXFP8") for r in recipes) |
| 113 | scope_defs = [BF16_GROUPED_SCOPE_DEF] | 115 | scope_defs = [BF16_GROUPED_SCOPE_DEF] |
| 114 | - if has_fp8: | 116 | + if has_fp8_rowwise: |
| 115 | scope_defs.append(FP8_GROUPED_SCOPE_DEF) | 117 | scope_defs.append(FP8_GROUPED_SCOPE_DEF) |
| 118 | + if has_fp8_blockwise: | ||
| 119 | + scope_defs.append(FP8_BLOCKWISE_SCOPE_DEF) | ||
| 116 | if has_mxfp8: | 120 | if has_mxfp8: |
| 117 | scope_defs.append(MXFP8_GROUPED_SCOPE_DEF) | 121 | scope_defs.append(MXFP8_GROUPED_SCOPE_DEF) |
| 118 | 122 | ||
| @@ -48,3 +48,9 @@ shapes: | |||
| 48 | # qwen3_hig: the weight-side-overhead regime (per-expert M_e tiny). | 48 | # qwen3_hig: the weight-side-overhead regime (per-expert M_e tiny). |
| 49 | - [32768, 3072, 7168, 112] | 49 | - [32768, 3072, 7168, 112] |
| 50 | - [128000, 3072, 7168, 112] | 50 | - [128000, 3072, 7168, 112] |
| 51 | + qwen3_5: # Qwen3.5-122B-A10B: hidden=3072, moe_inter=1024. M=16384 counts | ||
| 52 | + # ROUTED tokens (post top-k): 2048 tokens x top_k 8 = 16384, i.e. | ||
| 53 | + # 4x the 1-layer example's routed M~4096 (batch 1 x seq 512), kept | ||
| 54 | + # identical across the blockwise-vs-rowwise-vs-bf16 three-way runs. | ||
| 55 | + - [16384, 2048, 3072, 8] | ||
| 56 | + - [16384, 3072, 1024, 8] | ||
| @@ -0,0 +1,122 @@ | |||
| 1 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||
| 2 | + | ||
| 3 | +"""FP8 blockwise grouped GEMM scope definition for the op-attribution probe. | ||
| 4 | + | ||
| 5 | +Fourth recipe ScopeDef (``fp8::`` rowwise / ``mxfp8::`` / ``bf16::`` precedents). | ||
| 6 | +Wraps: | ||
| 7 | + | ||
| 8 | +* autograd boundary -- ``_Float8BlockwiseGroupedMM.forward/backward`` -> | ||
| 9 | + ``fp8bw::grouped::autograd.{forward,backward}`` (trace bracket only). | ||
| 10 | +* compute stage -- the NPU backend's contract surface | ||
| 11 | + (``_NPUGroupedMMBackend.quantize_forward_rhs / quantize_dgrad_rhs / | ||
| 12 | + grouped_mm / wgrad``) -> ``fp8bw::grouped::compute.{fwd_rhs,dgrad_rhs, | ||
| 13 | + grouped_mm,wgrad}``; plus the frontend activation-quant seam | ||
| 14 | + (``grouped_mm.triton_fp8_blockwise_act_quant_lhs`` -- rebind-installed by the | ||
| 15 | + patch, shared by forward and backward) -> ``fp8bw::grouped::compute.act_lhs``. | ||
| 16 | + | ||
| 17 | +Unlike rowwise/mxfp8 (which wrap ``_compute_{fwd,dgrad,wgrad}`` module | ||
| 18 | +dispatchers), the blockwise frontend has no ``_compute_*`` dispatchers -- the | ||
| 19 | +upstream autograd Function calls the backend object's four contract methods | ||
| 20 | +directly, so those methods are the stable anchors. ``act_lhs`` fires in both | ||
| 21 | +forward and backward (one seam, two stages); per-stage attribution comes from | ||
| 22 | +the outer profiled function. Attribution granularity stops at the contract | ||
| 23 | +level (same rationale as fp8/mxfp8: finer per-op attribution couples to the | ||
| 24 | +internal call order -- a Tier1 flip, the HP wgrad switch or a fused | ||
| 25 | +quant+GEMM would silently break labels). The ``wgrad`` scope covers both the | ||
| 26 | +fp8 and HP paths (the switch lives inside the method). | ||
| 27 | + | ||
| 28 | +The ``bf16::grouped_mm`` scope is NOT wrapped here -- it lives in | ||
| 29 | +:data:`BF16_GROUPED_SCOPE_DEF`; the benchmark composes both. | ||
| 30 | +""" | ||
| 31 | +from __future__ import annotations | ||
| 32 | + | ||
| 33 | +import inspect | ||
| 34 | + | ||
| 35 | +import torch | ||
| 36 | +import torch_npu # noqa: F401 registers the NPU with torch.accelerator | ||
| 37 | +import torchao_ascend # noqa: F401 activates the patches (blockwise backend applied) | ||
| 38 | +import torchao.prototype.moe_training.blockwise_fp8.grouped_mm as gmm_mod | ||
| 39 | +from torchao.prototype.moe_training.blockwise_fp8.grouped_mm import ( | ||
| 40 | + _Float8BlockwiseGroupedMM, | ||
| 41 | +) | ||
| 42 | +from torchao_ascend.patches.torchao.prototype.moe_training.blockwise_fp8 import ( | ||
| 43 | + grouped_mm_backend as backend_mod, | ||
| 44 | +) | ||
| 45 | + | ||
| 46 | +from probe import ScopeDef | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +def install(metadata): | ||
| 50 | + """Install ``fp8bw::`` record_function scope wrappers. Returns originals | ||
| 51 | + for :func:`restore`.""" | ||
| 52 | + originals = [] | ||
| 53 | + | ||
| 54 | + def install_one(owner, name, value): | ||
| 55 | + originals.append((owner, name, inspect.getattr_static(owner, name))) | ||
| 56 | + setattr(owner, name, value) | ||
| 57 | + | ||
| 58 | + # autograd.Function forward/backward -> trace bracket only. | ||
| 59 | + def autograd_method(original, stage): | ||
| 60 | + def measured(ctx, *args, **kwargs): | ||
| 61 | + with torch.profiler.record_function(f"fp8bw::grouped::autograd.{stage}"): | ||
| 62 | + return original(ctx, *args, **kwargs) | ||
| 63 | + return staticmethod(measured) | ||
| 64 | + | ||
| 65 | + for stage in ("forward", "backward"): | ||
| 66 | + install_one(_Float8BlockwiseGroupedMM, stage, | ||
| 67 | + autograd_method(getattr(_Float8BlockwiseGroupedMM, stage), stage)) | ||
| 68 | + | ||
| 69 | + # backend contract methods -> the attribution granularity. Instance | ||
| 70 | + # methods: class-level wrap binds normally for the _NPU_BACKEND singleton. | ||
| 71 | + role_for = { | ||
| 72 | + "quantize_forward_rhs": "fwd_rhs", | ||
| 73 | + "quantize_dgrad_rhs": "dgrad_rhs", | ||
| 74 | + "grouped_mm": "grouped_mm", | ||
| 75 | + "wgrad": "wgrad", | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + def compute_method_wrapper(original, role): | ||
| 79 | + label = f"fp8bw::grouped::compute.{role}" | ||
| 80 | + | ||
| 81 | + def wrapped(self, *args, **kwargs): | ||
| 82 | + metadata.append({"scope": label}) | ||
| 83 | + with torch.profiler.record_function(label): | ||
| 84 | + return original(self, *args, **kwargs) | ||
| 85 | + return wrapped | ||
| 86 | + | ||
| 87 | + for name, role in role_for.items(): | ||
| 88 | + if hasattr(backend_mod._NPUGroupedMMBackend, name): | ||
| 89 | + install_one(backend_mod._NPUGroupedMMBackend, name, | ||
| 90 | + compute_method_wrapper( | ||
| 91 | + getattr(backend_mod._NPUGroupedMMBackend, name), role)) | ||
| 92 | + | ||
| 93 | + # frontend activation-quant seam (patch-rebound; shared fwd/bwd) -> scope | ||
| 94 | + def seam_wrapper(original): | ||
| 95 | + label = "fp8bw::grouped::compute.act_lhs" | ||
| 96 | + | ||
| 97 | + def wrapped(*args, **kwargs): | ||
| 98 | + metadata.append({"scope": label}) | ||
| 99 | + with torch.profiler.record_function(label): | ||
| 100 | + return original(*args, **kwargs) | ||
| 101 | + return wrapped | ||
| 102 | + | ||
| 103 | + if hasattr(gmm_mod, "triton_fp8_blockwise_act_quant_lhs"): | ||
| 104 | + install_one(gmm_mod, "triton_fp8_blockwise_act_quant_lhs", | ||
| 105 | + seam_wrapper(gmm_mod.triton_fp8_blockwise_act_quant_lhs)) | ||
| 106 | + | ||
| 107 | + return originals | ||
| 108 | + | ||
| 109 | + | ||
| 110 | +def restore(originals): | ||
| 111 | + """Undo :func:`install`.""" | ||
| 112 | + for owner, name, original in reversed(originals): | ||
| 113 | + setattr(owner, name, original) | ||
| 114 | + | ||
| 115 | + | ||
| 116 | +FP8_BLOCKWISE_SCOPE_DEF = ScopeDef( | ||
| 117 | + install=install, | ||
| 118 | + restore=restore, | ||
| 119 | + prefixes=("fp8bw::",), | ||
| 120 | + infer_path=lambda md: "fp8bw" if any(r.get("scope", "").startswith("fp8bw::") for r in md) else "", | ||
| 121 | + attribution_prefixes=("fp8bw::grouped::compute.",), | ||
| 122 | +) | ||
🟡 Medium Priority 问题:本文件新增了 from bf16_grouped_scopes import BF16_GROUPED_SCOPE_DEF from fp8_grouped_scopes import FP8_GROUPED_SCOPE_DEF from mxfp8_grouped_scopes import MXFP8_GROUPED_SCOPE_DEF has_fp8 = any(r.name.startswith("FP8") for r in recipes) scope_defs = [BF16_GROUPED_SCOPE_DEF] if has_fp8: scope_defs.append(FP8_GROUPED_SCOPE_DEF) 影响链:本 PR 在 失败模式(可复现): 修复方向:在 建议:在 runner 的 profiling 分支按名称精确接线 FP8_BLOCKWISE_SCOPE_DEF(如 has_fp8bw = any(r.name.startswith("FP8_BLOCKWISE") ...),并让 has_fp8 排除 blockwise 名),否则删除该文件或修正 docstring 中「the benchmark composes both」的表述。 ![]() ![]() Incorrect? | |||
| @@ -234,6 +234,43 @@ def _w4a8_builder(block_size: int) -> Callable[[int], Callable]: | |||
| 234 | return builder | 234 | return builder |
| 235 | 235 | ||
| 236 | 236 | ||
| 237 | +def _fp8_blockwise_builder(_alignment_size: int) -> Callable: | ||
| 238 | + """Blockwise FP8 via the patched blockwise entry (fp8 blockwise MoE | ||
| 239 | + training, PR #195). The shared runner generates 16-aligned offsets while | ||
| 240 | + the blockwise wgrad contract requires 128-aligned token groups, so the | ||
| 241 | + entry pads internally (pad_token_groups_for_grouped_mm=True) — the | ||
| 242 | + pad/unpad overhead is part of the honest apples-to-apples cost on | ||
| 243 | + framework-standard offsets (deployment shapes pre-align groups to 128 at | ||
| 244 | + the modeling layer and pass pad=False instead). | ||
| 245 | + kernel_preference=KernelPreference.NPU is the explicit NPU gate (AUTO | ||
| 246 | + keeps upstream semantics, mxfp8-patch convention); BF16 high-precision | ||
| 247 | + wgrad is the perf-benchmark standard, enabled via | ||
| 248 | + grouped_mm_backend.WGRAD_HP = True before launch. | ||
| 249 | + """ | ||
| 250 | + from torchao_ascend.patches.torchao.prototype.moe_training.blockwise_fp8 import ( | ||
| 251 | + grouped_mm_backend as _blockwise_backend, | ||
| 252 | + ) | ||
| 253 | + from torchao.prototype.moe_training.blockwise_fp8.grouped_mm import ( | ||
| 254 | + _to_fp8_blockwise_then_scaled_grouped_mm, | ||
| 255 | + ) | ||
| 256 | + from torchao.quantization.quantize_.common import KernelPreference | ||
| 257 | + | ||
| 258 | + # BF16 high-precision wgrad is the perf-benchmark standard (same as the | ||
| 259 | + # FP8_ROWWISE builder's hardcoded wgrad_with_hp=True). | ||
| 260 | + _blockwise_backend.WGRAD_HP = True | ||
| 261 | + | ||
| 262 | + def fn(A, B_t, offs): | ||
| 263 | + return _to_fp8_blockwise_then_scaled_grouped_mm( | ||
| 264 | + A, B_t, offs, | ||
| 265 | + out_dtype=torch.bfloat16, | ||
| 266 | + float8_dtype=torch.float8_e4m3fn, | ||
| 267 | + block_size=128, | ||
| 268 | + pad_token_groups_for_grouped_mm=True, | ||
| 269 | + kernel_preference=KernelPreference.NPU, | ||
| 270 | + ) | ||
| 271 | + return fn | ||
| 272 | + | ||
| 273 | + | ||
| 237 | _RECIPES: dict[str, Recipe] = { | 274 | _RECIPES: dict[str, Recipe] = { |
| 238 | "MXFP8_RCEIL": Recipe( | 275 | "MXFP8_RCEIL": Recipe( |
| 239 | "MXFP8_RCEIL", _mxfp8_builder(MXFP8TrainingRecipe.MXFP8_RCEIL)), | 276 | "MXFP8_RCEIL", _mxfp8_builder(MXFP8TrainingRecipe.MXFP8_RCEIL)), |
| @@ -243,6 +280,7 @@ _RECIPES: dict[str, Recipe] = { | |||
| 243 | "FP8_ROWWISE", _fp8_rowwise_builder), | 280 | "FP8_ROWWISE", _fp8_rowwise_builder), |
| 244 | "W4A8": Recipe("W4A8", _w4a8_builder(32)), | 281 | "W4A8": Recipe("W4A8", _w4a8_builder(32)), |
| 245 | "W4A8_B128": Recipe("W4A8_B128", _w4a8_builder(128)), | 282 | "W4A8_B128": Recipe("W4A8_B128", _w4a8_builder(128)), |
| 283 | + "FP8_BLOCKWISE": Recipe("FP8_BLOCKWISE", _fp8_blockwise_builder), | ||
| 246 | } | 284 | } |
| 247 | 285 | ||
| 248 | 286 | ||
| @@ -10,7 +10,7 @@ | |||
| 10 | |---|---|---|---|---| | 10 | |---|---|---|---|---| |
| 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 | +| Float8 blockwise | `nn.Linear` + MoE 专家 | ✅ | 上游模块 + forward 重绑定(dense);MoE 经 `torch._grouped_mm` 重绑(融合分组核 / 逐专家循环) | dense:`quantize_` + 上游 Blockwise config;MoE:重绑 `torch._grouped_mm`(见 `examples/qwen3_5`,上游 config 未交付) | |
| 14 | | MXFP8(含 W8A8 格式) | `nn.Linear` + MoE 专家 | ✅ | Linear 就地 patch forward;MoE 模块替换 | `quantize_` + `MXFP8LinearConfig` / `MXFP8GMMConfig` | | 14 | | MXFP8(含 W8A8 格式) | `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")` 等 | | 15 | | W4A8(MXFP4 权重重缩放为 FP8 载荷) | `nn.Linear` + MoE 专家 | ✅ | 同 MXFP8 系(`quant_format="W4A8"` 变体) | `MXFP8LinearConfig(quant_format="W4A8")` 等 | |
| 16 | | W8A16 | — | — | 未实现(见下文) | — | | 16 | | W8A16 | — | — | 未实现(见下文) | — | |
| @@ -162,12 +162,14 @@ cd benchmarks/prototype/moe_training | |||
| 162 | python benchmark_scaled_grouped_mm_dq.py --shapes all | 162 | python benchmark_scaled_grouped_mm_dq.py --shapes all |
| 163 | ``` | 163 | ``` |
| 164 | 164 | ||
| 165 | -### Blockwise FP8 | 165 | +### Float8 blockwise |
| 166 | 166 | ||
| 167 | - **模块层**:仅 `nn.Linear`;上游 `Float8BlockwiseLinear` 的 `__init__` / `forward` 被重绑定为 NPU 实现(激活 1×128 分块、权重 128×128 分块)。 | 167 | - **模块层**:仅 `nn.Linear`;上游 `Float8BlockwiseLinear` 的 `__init__` / `forward` 被重绑定为 NPU 实现(激活 1×128 分块、权重 128×128 分块)。 |
| 168 | - **算子层**:内核级替换——`blockwise_fp8_gemm`、`fp8_blockwise_act_quant`、`weight_quant/dequant` 重绑定为 `npu_dynamic_block_quant` + `npu_quant_matmul`(`patches/torchao/kernel/blockwise_quantization.py`)。 | 168 | - **算子层**:内核级替换——`blockwise_fp8_gemm`、`fp8_blockwise_act_quant`、`weight_quant/dequant` 重绑定为 `npu_dynamic_block_quant` + `npu_quant_matmul`(`patches/torchao/kernel/blockwise_quantization.py`)。 |
| 169 | - **入口**:`quantize_` + 上游 Blockwise config(无独立入口)。 | 169 | - **入口**:`quantize_` + 上游 Blockwise config(无独立入口)。 |
| 170 | -- **限制**:仅 block_size=128;不支持 MoE。 | 170 | +- **MoE(grouped GEMM)**:`torch._grouped_mm` 重绑为 `_to_fp8_blockwise_then_scaled_grouped_mm`(NPU backend:单 launch 融合分组核 / 逐专家循环,显式 kernel_preference=KernelPreference.NPU 进入 NPU 路径,AUTO 保留上游语义;BF16 高精度 wgrad 可选),接入方式见 `examples/qwen3_5/qwen3_5_moe_fp8_blockwise_train.py`。 |
| 171 | +- **运行时开关**(patch 模块旗标,程序化设置):`grouped_mm_backend.WGRAD_HP = True` 启用 BF16 高精度 wgrad(隔离基准快 8%~11%);`grouped_mm_backend.WQ_CACHE = False` 关闭权重量化缓存(深模型显存换重量化)。分组融合核按内核在位自动探测,无需手动选择。 | ||
| 172 | +- **限制**:dense 与 MoE 均 block_size=128;上游 blockwise config 未交付,MoE 接入为 `torch._grouped_mm` 重绑(非 quantize_ 契约)。 | ||
| 171 | 173 | ||
| 172 | ### MXFP8 / MX 系列(含 W8A8、W4A8 变体) | 174 | ### MXFP8 / MX 系列(含 W8A8、W4A8 变体) |
| 173 | 175 | ||
| @@ -0,0 +1,49 @@ | |||
| 1 | +#!/bin/bash | ||
| 2 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||
| 3 | +# | ||
| 4 | +# Qwen3.5-MoE FP8 blockwise 训练一键脚本(GMM 替换路径,HP wgrad) | ||
| 5 | +# 用法: | ||
| 6 | +# bash moe_fp8_blockwise_train.sh # 按默认 yaml(fp8) | ||
| 7 | +# BF16_ONLY=1 bash moe_fp8_blockwise_train.sh # bf16 基线 | ||
| 8 | +# STEPS=50 bash moe_fp8_blockwise_train.sh # 只训 50 步 | ||
| 9 | +# ASCEND_RT_VISIBLE_DEVICES=1 bash ... # 换 1 号卡 | ||
| 10 | +# CONFIG_FILE=my.yaml bash ... # 换一份配置 | ||
| 11 | +# 说明:模型与数据必须已本地就绪(路径见 qwen3_5_moe_fp8_blockwise_train_config.yaml), | ||
| 12 | +# 脚本不会自动下载。脚本以自身所在目录锚定 py/config 路径,可在任意工作目录执行。 | ||
| 13 | +# 需先 source CANN 环境并 conda activate 训练环境(TORCH_DEVICE_BACKEND_AUTOLOAD=0 | ||
| 14 | +# 为本仓运行约定,脚本内已设置)。 | ||
| 15 | + | ||
| 16 | +set -e | ||
| 17 | + | ||
| 18 | +# --- NPU Environment --- | ||
| 19 | +export ASCEND_RT_VISIBLE_DEVICES=${ASCEND_RT_VISIBLE_DEVICES:-0} | ||
| 20 | +export TORCH_DEVICE_BACKEND_AUTOLOAD=0 | ||
| 21 | + | ||
| 22 | +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" | ||
| 23 | +cd "$SCRIPT_DIR" | ||
| 24 | + | ||
| 25 | +# torchao_ascend 插件源码导入(环境未 pip 安装本仓时使用源码路径; | ||
| 26 | +# 本脚本位于 <repo>/examples/qwen3_5/,仓库根为其上两级) | ||
| 27 | +export PYTHONPATH=$(cd ../.. && pwd) | ||
| 28 | + | ||
| 29 | +# --- Training Arguments --- | ||
| 30 | +CONFIG_FILE=${CONFIG_FILE:-"qwen3_5_moe_fp8_blockwise_train_config.yaml"} | ||
| 31 | +EXTRA_ARGS=() | ||
| 32 | +if [[ -n "${STEPS:-}" ]]; then | ||
| 33 | + EXTRA_ARGS+=(--steps "$STEPS") | ||
| 34 | +fi | ||
| 35 | +if [[ -n "${BF16_ONLY:-}" ]]; then | ||
| 36 | + EXTRA_ARGS+=(--bf16) | ||
| 37 | +fi | ||
| 38 | + | ||
| 39 | +echo "============================================================" | ||
| 40 | +echo " Qwen3.5-MoE FP8 blockwise (GMM 替换路径, HP wgrad)" | ||
| 41 | +echo " ASCEND_RT_VISIBLE_DEVICES: $ASCEND_RT_VISIBLE_DEVICES" | ||
| 42 | +echo " CONFIG: $CONFIG_FILE" | ||
| 43 | +echo " STEPS: ${STEPS:-as in config}" | ||
| 44 | +echo " BF16_ONLY: ${BF16_ONLY:-unset}" | ||
| 45 | +echo "============================================================" | ||
| 46 | + | ||
| 47 | +python3 qwen3_5_moe_fp8_blockwise_train.py \ | ||
| 48 | + --config "$CONFIG_FILE" \ | ||
| 49 | + "${EXTRA_ARGS[@]}" | ||
| @@ -0,0 +1,470 @@ | |||||||||||||||||
| 1 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||||||||||||||||
| 2 | + | ||||||||||||||||
| 3 | +# -*- coding: utf-8 -*- | ||||||||||||||||
| 4 | +"""Qwen3.5-MoE 路由专家 FP8 blockwise 训练(GMM 替换路径,M5' 最小 example)。 | ||||||||||||||||
| 5 | + | ||||||||||||||||
| 6 | +与 rowwise 版(examples/qwen3_5)的差异: | ||||||||||||||||
| 7 | +1. 量化方式:无 config/wrapper(blockwise 特性化未交付)——fp8.enabled=true 时把 | ||||||||||||||||
| 8 | + torch._grouped_mm 重绑为 _to_fp8_blockwise_then_scaled_grouped_mm(NPU backend, | ||||||||||||||||
| 9 | + Tier2 默认;融合核按内核在位自动探测),modeling 的两处专家 | ||||||||||||||||
| 10 | + grouped_mm 调用随即走 blockwise FP8(fwd/dgrad/wgrad 三 GEMM 全 FP8), | ||||||||||||||||
| 11 | + 且显式 kernel_preference=KernelPreference.NPU(AUTO 保留上游语义); | ||||||||||||||||
| 12 | +2. ALIGN=128(blockwise wgrad 要求组 128 对齐;rowwise 是 16)—— | ||||||||||||||||
| 13 | + 组已对齐,pad_token_groups_for_grouped_mm=False; | ||||||||||||||||
| 14 | +3. HP wgrad:fp8.wgrad_hp=true 时置 grouped_mm_backend.WGRAD_HP=True | ||||||||||||||||
| 15 | + (M1 开关,wgrad 降噪首选 Ladder A); | ||||||||||||||||
| 16 | +4. modeling 复用同目录 modeling_qwen3_5_moe.py(eager argsort 编排, | ||||||||||||||||
| 17 | + 两处 torch._grouped_mm 调用点即 blockwise 路由点;v4 确认复用原文件); | ||||||||||||||||
| 18 | +5. summary.json 额外记录 elapsed_s / peak_mem_gb(耗时/内存验收)。 | ||||||||||||||||
| 19 | + | ||||||||||||||||
| 20 | +用法: | ||||||||||||||||
| 21 | + bash moe_fp8_blockwise_train.sh | ||||||||||||||||
| 22 | + 或 python3 qwen3_5_moe_fp8_blockwise_train.py [--config 配置] [--steps N] [--bf16] | ||||||||||||||||
| 23 | + 模型与数据必须已本地就绪(路径见 yaml),缺失即报错。 | ||||||||||||||||
| 24 | + | ||||||||||||||||
| 25 | +说明:单卡 + 层数截断(model.num_layers)跑 smoke;完整 244GB 需多卡/流水线。 | ||||||||||||||||
| 26 | +""" | ||||||||||||||||
| 27 | + | ||||||||||||||||
| 28 | +from __future__ import annotations | ||||||||||||||||
| 29 | + | ||||||||||||||||
| 30 | +import argparse | ||||||||||||||||
| 31 | +import json | ||||||||||||||||
| 32 | +import logging | ||||||||||||||||
| 33 | +import math | ||||||||||||||||
| 34 | +import time | ||||||||||||||||
| 35 | +from pathlib import Path | ||||||||||||||||
| 36 | +from typing import Any | ||||||||||||||||
| 37 | + | ||||||||||||||||
| 38 | +import yaml | ||||||||||||||||
| 39 | +import pandas as pd | ||||||||||||||||
| 40 | +import torch | ||||||||||||||||
| 41 | +import torch_npu # noqa: F401 | ||||||||||||||||
| 42 | + | ||||||||||||||||
| 43 | +from torch.utils.data import DataLoader, Dataset | ||||||||||||||||
| 44 | +from transformers import AutoTokenizer, AutoConfig, AutoModelForCausalLM | ||||||||||||||||
| 45 | + | ||||||||||||||||
| 46 | +# blockwise backend patch 随 torchao_ascend 激活(registry apply_all 覆盖 blockwise 组) | ||||||||||||||||
| 47 | +import torchao_ascend # noqa: F401 | ||||||||||||||||
| 48 | +from torchao.prototype.moe_training.blockwise_fp8.grouped_mm import ( | ||||||||||||||||
| 49 | + _to_fp8_blockwise_then_scaled_grouped_mm as _blockwise_gmm_entry, | ||||||||||||||||
| 50 | +) | ||||||||||||||||
| 51 | +from torchao.quantization.quantize_.common import KernelPreference | ||||||||||||||||
| 52 | + | ||||||||||||||||
| 53 | +# modeling 复用同目录 modeling_qwen3_5_moe.py(eager argsort 编排,v4 确认复用原文件) | ||||||||||||||||
| 54 | +from modeling_qwen3_5_moe import apply_grouped_mm_forward | ||||||||||||||||
| 55 | + | ||||||||||||||||
| 56 | +logging.basicConfig(level=logging.INFO, format="%(message)s") | ||||||||||||||||
| 57 | +logger = logging.getLogger("qwen3_5_moe_fp8_blockwise_train") | ||||||||||||||||
| 58 | + | ||||||||||||||||
| 59 | + | ||||||||||||||||
| 60 | +# ---------------- 项目根:所有相对路径都相对脚本所在目录 ---------------- | ||||||||||||||||
| 61 | +BASE_DIR = Path(__file__).resolve().parent | ||||||||||||||||
| 62 | + | ||||||||||||||||
| 63 | +CONFIG_FILE = "qwen3_5_moe_fp8_blockwise_train_config.yaml" | ||||||||||||||||
| 64 | + | ||||||||||||||||
| 65 | +_NUM_COERCION = { | ||||||||||||||||
| 66 | + "model": {"num_layers": int}, | ||||||||||||||||
| 67 | + "train": {"seq_len": int, "batch": int, "max_eval_batches": int}, | ||||||||||||||||
| 68 | + "fp8": {"align": int}, | ||||||||||||||||
| 69 | + "training": {"steps": int, "lr": float, "max_docs": int, | ||||||||||||||||
| 70 | + "max_eval_docs": int, "seed": int}, | ||||||||||||||||
| 71 | +} | ||||||||||||||||
| 72 | + | ||||||||||||||||
| 73 | + | ||||||||||||||||
| 74 | +def _coerce_types(node: dict[str, Any], spec: dict[str, Any]) -> dict[str, Any]: | ||||||||||||||||
| 75 | + out = dict(node) | ||||||||||||||||
| 76 | + for k, v in node.items(): | ||||||||||||||||
| 77 | + if isinstance(v, dict): | ||||||||||||||||
| 78 | + out[k] = _coerce_types(v, spec.get(k, {}) if isinstance(spec, dict) else {}) | ||||||||||||||||
| 79 | + else: | ||||||||||||||||
| 80 | + cast = spec.get(k) if isinstance(spec, dict) else None | ||||||||||||||||
| 81 | + if cast is not None and isinstance(v, str): | ||||||||||||||||
| 82 | + out[k] = cast(v) | ||||||||||||||||
| 83 | + return out | ||||||||||||||||
| 84 | + | ||||||||||||||||
| 85 | + | ||||||||||||||||
| 86 | +def load_config(path: str | None = None) -> dict[str, Any]: | ||||||||||||||||
| 87 | + """定位并读取 YAML 配置,返回已做类型强转的原始字典。""" | ||||||||||||||||
| 88 | + cands = [] | ||||||||||||||||
| 89 | + if path: | ||||||||||||||||
| 90 | + cands.append(Path(path)) | ||||||||||||||||
| 91 | + cands += [BASE_DIR / CONFIG_FILE, Path(CONFIG_FILE)] | ||||||||||||||||
| 92 | + chosen = None | ||||||||||||||||
| 93 | + for c in cands: | ||||||||||||||||
| 94 | + if c.is_file(): | ||||||||||||||||
| 95 | + chosen = c | ||||||||||||||||
| 96 | + break | ||||||||||||||||
| 97 | + if chosen is None: | ||||||||||||||||
| 98 | + raise FileNotFoundError( | ||||||||||||||||
| 99 | + f"找不到配置文件 {CONFIG_FILE},请先在脚本目录({BASE_DIR})放一份") | ||||||||||||||||
| 100 | + with open(chosen, "r", encoding="utf-8") as f: | ||||||||||||||||
| 101 | + raw = yaml.safe_load(f) or {} | ||||||||||||||||
| 102 | + logger.info(f"[config] 读取配置 {chosen}") | ||||||||||||||||
| 103 | + return _coerce_types(raw, _NUM_COERCION) | ||||||||||||||||
| 104 | + | ||||||||||||||||
| 105 | + | ||||||||||||||||
| 106 | +class Config: | ||||||||||||||||
| 107 | + """把嵌套 dict 封装成点号访问(只读)。""" | ||||||||||||||||
| 108 | + | ||||||||||||||||
| 109 | + def __init__(self, data: dict[str, Any]) -> None: | ||||||||||||||||
| 110 | + object.__setattr__(self, "_data", data) | ||||||||||||||||
| 111 | + | ||||||||||||||||
| 112 | + def __getattr__(self, key: str) -> Any: | ||||||||||||||||
| 113 | + v = self._data.get(key) | ||||||||||||||||
| 114 | + if isinstance(v, dict): | ||||||||||||||||
| 115 | + return Config(v) | ||||||||||||||||
| 116 | + return v | ||||||||||||||||
| 117 | + | ||||||||||||||||
| 118 | + | ||||||||||||||||
| 119 | +# ---------------- 路径解析 ---------------- | ||||||||||||||||
| 120 | +_WEIGHT_FILES = ("model.safetensors", "pytorch_model.bin", "adapter_model.safetensors") | ||||||||||||||||
| 121 | + | ||||||||||||||||
| 122 | + | ||||||||||||||||
| 123 | +def _resolve_path(p: str) -> Path: | ||||||||||||||||
| 124 | + """相对路径相对脚本目录解析。""" | ||||||||||||||||
| 125 | + p = Path(p) | ||||||||||||||||
| 126 | + if not p.is_absolute(): | ||||||||||||||||
| 127 | + p = (BASE_DIR / p).resolve() | ||||||||||||||||
| 128 | + return p | ||||||||||||||||
| 129 | + | ||||||||||||||||
| 130 | + | ||||||||||||||||
| 131 | +def _is_weights_dir(p: Path) -> bool: | ||||||||||||||||
| 132 | + # 单文件或分片都接受(大模型通常是 model-NNNNN-of-NNXXX.safetensors 分片) | ||||||||||||||||
| 133 | + if not p.is_dir(): | ||||||||||||||||
| 134 | + return False | ||||||||||||||||
| 135 | + return any(p.glob("*.safetensors")) or any(p.glob("*.bin")) | ||||||||||||||||
| 136 | + | ||||||||||||||||
| 137 | + | ||||||||||||||||
| 138 | +def ensure_model(cfg: Config) -> str: | ||||||||||||||||
| 139 | + """校验模型目录本地就绪(不自动下载)。返回模型目录路径。""" | ||||||||||||||||
| 140 | + path = _resolve_path(cfg.model.path) | ||||||||||||||||
| 141 | + if not _is_weights_dir(path): | ||||||||||||||||
| 142 | + raise FileNotFoundError( | ||||||||||||||||
| 143 | + f"模型目录 {path} 里没有权重文件(*.safetensors / *.bin,单文件或分片)," | ||||||||||||||||
| 144 | + f"请先把模型放到 {path},或修改配置里的 model.path") | ||||||||||||||||
| 145 | + if _is_weights_dir(path / "huggingface"): | ||||||||||||||||
| 146 | + return str(path / "huggingface") | ||||||||||||||||
| 147 | + return str(path) | ||||||||||||||||
| 148 | + | ||||||||||||||||
| 149 | + | ||||||||||||||||
| 150 | +def ensure_dataset(cfg: Config) -> tuple[Path, Path]: | ||||||||||||||||
| 151 | + """校验训练/评测数据就绪。返回 (train_path, eval_path)。""" | ||||||||||||||||
| 152 | + ddir = _resolve_path(cfg.dataset.path) | ||||||||||||||||
| 153 | + train = ddir / cfg.dataset.train_file | ||||||||||||||||
| 154 | + eval_ = ddir / cfg.dataset.eval_file | ||||||||||||||||
| 155 | + if not train.is_file(): | ||||||||||||||||
| 156 | + raise FileNotFoundError( | ||||||||||||||||
| 157 | + f"找不到训练数据 {train},请按 dataset.train_file 放置 wikitext parquet 分片") | ||||||||||||||||
| 158 | + if not eval_.is_file(): | ||||||||||||||||
| 159 | + raise FileNotFoundError( | ||||||||||||||||
| 160 | + f"找不到评测数据 {eval_},请按 dataset.eval_file 放置 wikitext parquet 分片") | ||||||||||||||||
| 161 | + logger.info(f"[data] 使用本地数据:train={train.name} eval={eval_.name}") | ||||||||||||||||
| 162 | + return train, eval_ | ||||||||||||||||
| 163 | + | ||||||||||||||||
| 164 | + | ||||||||||||||||
| 165 | +# ---------------- HP master 权重 dtype ---------------- | ||||||||||||||||
| 166 | +# 与 rowwise 版同一约束:NPU 上 npu 系算子只收 fp16/bf16,fp16 注意力等支持不全 | ||||||||||||||||
| 167 | +_HP_DTYPE_MAP = { | ||||||||||||||||
| 168 | + "bfloat16": torch.bfloat16, | ||||||||||||||||
| 169 | + "bf16": torch.bfloat16, | ||||||||||||||||
| 170 | +} | ||||||||||||||||
| 171 | + | ||||||||||||||||
| 172 | + | ||||||||||||||||
| 173 | +# ---------------- blockwise 路由与自检 ---------------- | ||||||||||||||||
| 174 | +def install_blockwise_routing() -> None: | ||||||||||||||||
| 175 | + """fp8.enabled=true:把 torch._grouped_mm 重绑为 blockwise 入口。 | ||||||||||||||||
| 176 | + | ||||||||||||||||
| 177 | + modeling 的专家前向调用 torch._grouped_mm(A, W.transpose(-1,-2), offs=...); | ||||||||||||||||
| 178 | + ALIGN=128 保证每专家 token 数 128 对齐 -> pad_token_groups_for_grouped_mm=False, | ||||||||||||||||
| 179 | + wgrad 的组对齐要求同样满足。BF16 基线(fp8.enabled=false)不安装,走原生 grouped_mm。 | ||||||||||||||||
| 180 | + """ | ||||||||||||||||
| 181 | + def _blockwise(*args, **kwargs): | ||||||||||||||||
| 182 | + # 显式 KernelPreference.NPU(主线 mxfp8 同款门控惯例:AUTO 保留上游语义) | ||||||||||||||||
| 183 | + kwargs.setdefault("kernel_preference", KernelPreference.NPU) | ||||||||||||||||
| 184 | + return _blockwise_gmm_entry(*args, **kwargs, | ||||||||||||||||
| 185 | + pad_token_groups_for_grouped_mm=False) | ||||||||||||||||
| 186 | + torch._grouped_mm = _blockwise | ||||||||||||||||
| 187 | + | ||||||||||||||||
| 188 | + | ||||||||||||||||
| 189 | +def self_check_blockwise() -> None: | ||||||||||||||||
| 190 | + """自检:(1) blockwise backend patch 已随 torchao_ascend 激活; | ||||||||||||||||
| 191 | + (2) torch._grouped_mm 路由 shim 已安装。""" | ||||||||||||||||
| 192 | + from torchao_ascend.patches.torchao.prototype.moe_training.blockwise_fp8 import ( | ||||||||||||||||
| 193 | + grouped_mm_backend as backend_mod, | ||||||||||||||||
| 194 | + ) | ||||||||||||||||
| 195 | + import torchao.prototype.moe_training.blockwise_fp8.grouped_mm as gmm_mod | ||||||||||||||||
| 196 | + | ||||||||||||||||
| 197 | + if not backend_mod._applied: | ||||||||||||||||
| 198 | + raise RuntimeError( | ||||||||||||||||
| 199 | + "blockwise backend patch 未生效(torchao_ascend activate 未覆盖 blockwise 组)") | ||||||||||||||||
| 200 | + if gmm_mod.triton_fp8_blockwise_act_quant_lhs is not backend_mod._npu_act_quant_lhs: | ||||||||||||||||
| 201 | + raise RuntimeError( | ||||||||||||||||
| 202 | + "blockwise backend patch 未生效:act_lhs seam 未重绑为 NPU 版") | ||||||||||||||||
| 203 | + if getattr(torch._grouped_mm, "__name__", "") != "_blockwise": | ||||||||||||||||
| 204 | + raise RuntimeError("torch._grouped_mm 路由 shim 未安装") | ||||||||||||||||
| 205 | + logger.info("[check] blockwise backend patch + 路由 shim 均生效") | ||||||||||||||||
| 206 | + | ||||||||||||||||
| 207 | + | ||||||||||||||||
| 208 | +# ---------------- 数据:wikitext -> tokenize -> 拼接 -> 定长块 ---------------- | ||||||||||||||||
| 209 | +class PackedDataset(Dataset): | ||||||||||||||||
| 210 | + def __init__(self, path: Path, tokenizer: Any, seq_len: int, column: str, | ||||||||||||||||
| 211 | + max_docs: int | None) -> None: | ||||||||||||||||
| 212 | + texts = (pd.read_parquet(path, columns=[column])[column] | ||||||||||||||||
| 213 | + .dropna().astype(str).tolist()) | ||||||||||||||||
| 214 | + if max_docs and max_docs > 0: | ||||||||||||||||
| 215 | + texts = texts[:max_docs] | ||||||||||||||||
| 216 | + ids = [] | ||||||||||||||||
| 217 | + for t in texts: | ||||||||||||||||
| 218 | + ids.extend(tokenizer.encode(t)) | ||||||||||||||||
| 219 | + ids.append(tokenizer.eos_token_id) | ||||||||||||||||
| 220 | + self.chunks = [ids[i:i + seq_len] | ||||||||||||||||
| 221 | + for i in range(0, len(ids) - seq_len + 1, seq_len)] | ||||||||||||||||
| 222 | + if not self.chunks: | ||||||||||||||||
| 223 | + raise ValueError( | ||||||||||||||||
| 224 | + f"数据 token 数({len(ids)})不足 seq_len={seq_len},无法打包成任何块。" | ||||||||||||||||
| 225 | + f"请减小 seq_len 或增加数据量。") | ||||||||||||||||
| 226 | + logger.info(f"[data] {len(texts)} 篇 -> {len(ids)} tokens -> " | ||||||||||||||||
| 227 | + f"{len(self.chunks)} 个 {seq_len} 长度块") | ||||||||||||||||
| 228 | + | ||||||||||||||||
| 229 | + def __len__(self) -> int: | ||||||||||||||||
| 230 | + return len(self.chunks) | ||||||||||||||||
| 231 | + | ||||||||||||||||
| 232 | + def __getitem__(self, i: int) -> dict[str, torch.Tensor]: | ||||||||||||||||
| 233 | + x = torch.tensor(self.chunks[i], dtype=torch.long) | ||||||||||||||||
| 234 | + return {"input_ids": x, "labels": x.clone()} | ||||||||||||||||
| 235 | + | ||||||||||||||||
| 236 | + | ||||||||||||||||
| 237 | +def make_dataloaders(cfg: Config, tokenizer: Any, train_path: Path, | ||||||||||||||||
| 238 | + eval_path: Path) -> tuple[DataLoader, DataLoader]: | ||||||||||||||||
| 239 | + """按配置构建训练/评测 DataLoader(文本定长打包)。""" | ||||||||||||||||
| 240 | + logger.info("[data] 打包训练集 ...") | ||||||||||||||||
| 241 | + ds = PackedDataset(train_path, tokenizer, cfg.train.seq_len, | ||||||||||||||||
| 242 | + cfg.dataset.column, cfg.training.max_docs) | ||||||||||||||||
| 243 | + if train_path == eval_path: | ||||||||||||||||
| 244 | + eval_ds = ds | ||||||||||||||||
| 245 | + else: | ||||||||||||||||
| 246 | + logger.info("[data] 打包评测集 ...") | ||||||||||||||||
| 247 | + eval_ds = PackedDataset(eval_path, tokenizer, cfg.train.seq_len, | ||||||||||||||||
| 248 | + cfg.dataset.column, cfg.training.max_eval_docs) | ||||||||||||||||
| 249 | + dl = DataLoader(ds, batch_size=cfg.train.batch, shuffle=True, drop_last=True) | ||||||||||||||||
| 250 | + if len(dl) == 0: | ||||||||||||||||
| 251 | + raise ValueError( | ||||||||||||||||
| 252 | + f"训练集样本数不足以构成一个 batch(samples={len(ds)}, batch={cfg.train.batch}):" | ||||||||||||||||
| 253 | + "请调小 train.batch 或增大 max_docs" | ||||||||||||||||
| 254 | + ) | ||||||||||||||||
| 255 | + eval_dl = DataLoader(eval_ds, batch_size=cfg.train.batch, shuffle=False) | ||||||||||||||||
| 256 | + return dl, eval_dl | ||||||||||||||||
| 257 | + | ||||||||||||||||
| 258 | + | ||||||||||||||||
| 259 | +@torch.no_grad() | ||||||||||||||||
| 260 | +def evaluate(model: torch.nn.Module, dl: DataLoader, max_batches: int = 8) -> tuple[float, float, int]: | ||||||||||||||||
| 261 | + """返回 (avg_nll, perplexity, n_batches);perplexity = exp(avg_nll)。""" | ||||||||||||||||
| 262 | + model.eval() | ||||||||||||||||
| 263 | + device = next(model.parameters()).device | ||||||||||||||||
| 264 | + losses = [] | ||||||||||||||||
| 265 | + for i, b in enumerate(dl): | ||||||||||||||||
| 266 | + if i >= max_batches: | ||||||||||||||||
| 267 | + break | ||||||||||||||||
| 268 | + b = {k: v.to(device) for k, v in b.items()} | ||||||||||||||||
| 269 | + losses.append(model(**b).loss.item()) | ||||||||||||||||
| 270 | + if not math.isfinite(losses[-1]): | ||||||||||||||||
| 271 | + break | ||||||||||||||||
| 272 | + model.train() | ||||||||||||||||
| 273 | + n = len(losses) | ||||||||||||||||
| 274 | + if n == 0: | ||||||||||||||||
| 275 | + return float("nan"), float("nan"), 0 | ||||||||||||||||
| 276 | + avg_nll = sum(losses) / n | ||||||||||||||||
| 277 | + return avg_nll, math.exp(min(float(avg_nll), 20.0)), n | ||||||||||||||||
| 278 | + | ||||||||||||||||
| 279 | + | ||||||||||||||||
| 280 | +# ---------------- 主流程 ---------------- | ||||||||||||||||
| 281 | +def resolve_device(name: str) -> torch.device: | ||||||||||||||||
| 282 | + """解析设备。FP8 blockwise 强依赖 NPU 算子(npu_dynamic_block_quant / | ||||||||||||||||
| 283 | + npu_quant_matmul),NPU 不可用直接报错——不回退 CPU。""" | ||||||||||||||||
| 284 | + device = torch.device(str(name)) | ||||||||||||||||
| 285 | + if device.type == "npu" and not torch.npu.is_available(): | ||||||||||||||||
| 286 | + raise RuntimeError( | ||||||||||||||||
| 287 | + "NPU 不可用。FP8 blockwise MoE 训练强依赖 NPU 算子,无法回退 CPU。" | ||||||||||||||||
| 288 | + "请在 NPU 环境运行(并确认驱动/CANN 就绪)。") | ||||||||||||||||
| 289 | + return device | ||||||||||||||||
| 290 | + | ||||||||||||||||
| 291 | + | ||||||||||||||||
| 292 | +def load_model(cfg: Config, hp_dtype: torch.dtype, device: torch.device): | ||||||||||||||||
| 293 | + """加载 Qwen3.5-MoE(可选层数截断用于 smoke),单卡。返回 (model, tokenizer)。""" | ||||||||||||||||
| 294 | + model_dir = ensure_model(cfg) | ||||||||||||||||
| 295 | + tokenizer = AutoTokenizer.from_pretrained(model_dir) | ||||||||||||||||
| 296 | + load_kwargs = dict( | ||||||||||||||||
| 297 | + torch_dtype=hp_dtype, | ||||||||||||||||
| 298 | + low_cpu_mem_usage=True, | ||||||||||||||||
| 299 | + attn_implementation=str(cfg.runtime.attn_implementation or "eager"), | ||||||||||||||||
| 300 | + ) | ||||||||||||||||
| 301 | + num_layers = cfg.model.num_layers | ||||||||||||||||
| 302 | + if num_layers is not None: | ||||||||||||||||
| 303 | + acfg = AutoConfig.from_pretrained(model_dir) | ||||||||||||||||
| 304 | + text_cfg = acfg.text_config if hasattr(acfg, "text_config") else acfg | ||||||||||||||||
| 305 | + text_cfg.num_hidden_layers = int(num_layers) | ||||||||||||||||
| 306 | + text_cfg.use_cache = False | ||||||||||||||||
| 307 | + load_kwargs["config"] = text_cfg | ||||||||||||||||
| 308 | + load_kwargs["ignore_mismatched_sizes"] = True | ||||||||||||||||
| 309 | + logger.info(f"[load] 截断到 {num_layers} 层(smoke)") | ||||||||||||||||
| 310 | + model = AutoModelForCausalLM.from_pretrained(model_dir, **load_kwargs).to(device) | ||||||||||||||||
| 311 | + model.config.use_cache = False | ||||||||||||||||
| 312 | + from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeExperts | ||||||||||||||||
| 313 | + n_exp = sum(1 for m in model.modules() if isinstance(m, Qwen3_5MoeExperts)) | ||||||||||||||||
| 314 | + logger.info(f"[load] Qwen3_5MoeForCausalLM,{n_exp} 个 Qwen3_5MoeExperts 模块") | ||||||||||||||||
| 315 | + return model, tokenizer | ||||||||||||||||
| 316 | + | ||||||||||||||||
| 317 | + | ||||||||||||||||
| 318 | +def main() -> None: | ||||||||||||||||
| 319 | + """读取配置并执行:BF16 基线 -> blockwise 路由 -> 训练 -> 评测。""" | ||||||||||||||||
| 320 | + parser = argparse.ArgumentParser(description="Qwen3.5-MoE FP8 blockwise 训练(torchao-ascend)") | ||||||||||||||||
| 321 | + parser.add_argument("--config", default="", | ||||||||||||||||
| 322 | + help=f"配置文件路径(默认 {BASE_DIR / CONFIG_FILE})") | ||||||||||||||||
| 323 | + parser.add_argument("--steps", type=int, default=None, | ||||||||||||||||
| 324 | + help="覆盖 training.steps") | ||||||||||||||||
| 325 | + parser.add_argument("--bf16", action="store_true", | ||||||||||||||||
| 326 | + help="覆盖 fp8.enabled=false(BF16 基线跑,供 loss 对比)") | ||||||||||||||||
| 327 | + parser.add_argument("--output-root", default=None, | ||||||||||||||||
| 328 | + help="覆盖 output.root(诊断跑隔离输出,防止覆盖验收数据)") | ||||||||||||||||
| 329 | + args = parser.parse_args() | ||||||||||||||||
| 330 | + | ||||||||||||||||
| 331 | + cfg: Config = Config(load_config(args.config or None)) | ||||||||||||||||
| 332 | + total_steps: int = args.steps if args.steps is not None else cfg.training.steps | ||||||||||||||||
| 333 | + fp8_enabled = False if args.bf16 else bool(cfg.fp8.enabled) | ||||||||||||||||
| 334 | + align = int(cfg.fp8.align) | ||||||||||||||||
| 335 | + assert align == 128, f"blockwise 要求 align=128(wgrad 组对齐),当前 {align}" | ||||||||||||||||
| 336 | + | ||||||||||||||||
| 337 | + logger.info(f"[config] 模型 {cfg.model.path} 数据 {cfg.dataset.path} " | ||||||||||||||||
| 338 | + f"num_layers={cfg.model.num_layers} seq_len={cfg.train.seq_len} " | ||||||||||||||||
| 339 | + f"batch={cfg.train.batch} steps={total_steps} lr={cfg.training.lr} " | ||||||||||||||||
| 340 | + f"fp8={fp8_enabled} align={align} device={cfg.runtime.device}") | ||||||||||||||||
| 341 | + | ||||||||||||||||
| 342 | + torch.manual_seed(cfg.training.seed) | ||||||||||||||||
| 343 | + device = resolve_device(str(cfg.runtime.device)) | ||||||||||||||||
| 344 | + dtype_key = str(cfg.runtime.dtype).lower() | ||||||||||||||||
| 345 | + hp_dtype = _HP_DTYPE_MAP.get(dtype_key) | ||||||||||||||||
| 346 | + if hp_dtype is None: | ||||||||||||||||
| 347 | + raise RuntimeError( | ||||||||||||||||
| 348 | + f"仅支持 bfloat16 master 权重(NPU 上 fp32 被 npu 系算子拒绝、" | ||||||||||||||||
| 349 | + f"fp16 注意力等算子支持不全),配置 runtime.dtype={cfg.runtime.dtype},请改为 bfloat16。") | ||||||||||||||||
| 350 | + | ||||||||||||||||
| 351 | + model, tokenizer = load_model(cfg, hp_dtype, device) | ||||||||||||||||
| 352 | + | ||||||||||||||||
| 353 | + # 改写专家前向为 jagged grouped_mm(ALIGN=128:blockwise 组对齐) | ||||||||||||||||
| 354 | + n_exp = apply_grouped_mm_forward(model, align=align) | ||||||||||||||||
| 355 | + logger.info(f"[patch] {n_exp} Qwen3_5MoeExperts.forward -> jagged grouped_mm (align={align})") | ||||||||||||||||
| 356 | + | ||||||||||||||||
| 357 | + # ---- blockwise 路由(fp8 时在基线 eval 之后安装)---- | ||||||||||||||||
| 358 | + if fp8_enabled: | ||||||||||||||||
| 359 | + wgrad_hp = bool(getattr(cfg.fp8, "wgrad_hp", False)) | ||||||||||||||||
| 360 | + if wgrad_hp: | ||||||||||||||||
| 361 | + from torchao_ascend.patches.torchao.prototype.moe_training.blockwise_fp8 import ( | ||||||||||||||||
| 362 | + grouped_mm_backend as _blockwise_backend, | ||||||||||||||||
| 363 | + ) | ||||||||||||||||
| 364 | + _blockwise_backend.WGRAD_HP = True | ||||||||||||||||
| 365 | + logger.info("[fp8] HP wgrad 开关已置位(grouped_mm_backend.WGRAD_HP=True)") | ||||||||||||||||
| 366 | + | ||||||||||||||||
| 367 | + train_path, eval_path = ensure_dataset(cfg) | ||||||||||||||||
| 368 | + train_dl, eval_dl = make_dataloaders(cfg, tokenizer, train_path, eval_path) | ||||||||||||||||
| 369 | + | ||||||||||||||||
| 370 | + def _run_eval(desc: str) -> None: | ||||||||||||||||
| 371 | + avg_nll, ppl, _ = evaluate(model, eval_dl, int(cfg.train.max_eval_batches)) | ||||||||||||||||
| 372 | + logger.info(f"[eval] {desc} = {avg_nll:.4f} ppl={ppl:.4f}") | ||||||||||||||||
| 373 | + | ||||||||||||||||
| 374 | + _run_eval("BF16 基线 loss(grouped_mm 前向,未量化)") | ||||||||||||||||
| 375 | + | ||||||||||||||||
| 376 | + # ---- FP8 blockwise 路由 ---- | ||||||||||||||||
| 377 | + if fp8_enabled: | ||||||||||||||||
| 378 | + install_blockwise_routing() | ||||||||||||||||
| 379 | + self_check_blockwise() | ||||||||||||||||
| 380 | + logger.info("[fp8] torch._grouped_mm -> blockwise entry(三 GEMM 全 FP8)") | ||||||||||||||||
| 381 | + _run_eval("FP8 量化后未训练 loss") | ||||||||||||||||
| 382 | + else: | ||||||||||||||||
| 383 | + logger.info("[fp8] enabled=false,仅 BF16 基线") | ||||||||||||||||
| 384 | + | ||||||||||||||||
| 385 | + # ---- 训练 ---- | ||||||||||||||||
| 386 | + # AdamW:LLM 训练标准优化器;smoke 不加 cosine/warmup(对比只需同优化器同 lr)。 | ||||||||||||||||
| 387 | + optimizer = torch.optim.AdamW(model.parameters(), lr=float(cfg.training.lr)) | ||||||||||||||||
| 388 | + model.train() | ||||||||||||||||
| 389 | + start_time, step = time.time(), 0 | ||||||||||||||||
| 390 | + non_finite_step: int | None = None | ||||||||||||||||
| 391 | + losses: list[float] = [] | ||||||||||||||||
| 392 | + | ||||||||||||||||
| 393 | + def _sync() -> None: | ||||||||||||||||
| 394 | + if device.type == "npu": | ||||||||||||||||
| 395 | + torch.npu.synchronize() | ||||||||||||||||
| 396 | + | ||||||||||||||||
| 397 | + def _peak_mem_gb() -> float: | ||||||||||||||||
| 398 | + return torch.npu.max_memory_allocated() / 2 ** 30 if device.type == "npu" else 0.0 | ||||||||||||||||
| 399 | + | ||||||||||||||||
| 400 | + while step < total_steps: | ||||||||||||||||
| 401 | + for batch in train_dl: | ||||||||||||||||
| 402 | + if step >= total_steps: | ||||||||||||||||
| 403 | + break | ||||||||||||||||
🟡 Medium Priority 建议:在构建 train_dl 之后(或训练循环之前)校验 ![]() ![]() Incorrect? | |||||||||||||||||
| 404 | + out = model(input_ids=batch["input_ids"].to(device), | ||||||||||||||||
| 405 | + labels=batch["labels"].to(device)) | ||||||||||||||||
| 406 | + loss_value = out.loss.item() | ||||||||||||||||
| 407 | + if not math.isfinite(loss_value): | ||||||||||||||||
| 408 | + non_finite_step = step + 1 | ||||||||||||||||
| 409 | + logger.info(f"[train] 非有限 loss at step {non_finite_step},跳过该步并提前终止") | ||||||||||||||||
| 410 | + break | ||||||||||||||||
| 411 | + out.loss.backward() | ||||||||||||||||
| 412 | + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | ||||||||||||||||
| 413 | + optimizer.step() | ||||||||||||||||
🟡 Medium Priority 建议:在 Suggestions
![]() ![]() Incorrect? | |||||||||||||||||
| 414 | + optimizer.zero_grad() | ||||||||||||||||
| 415 | + _sync() | ||||||||||||||||
| 416 | + losses.append(loss_value) | ||||||||||||||||
| 417 | + step += 1 | ||||||||||||||||
| 418 | + if step % 10 == 0 or step == 1: | ||||||||||||||||
| 419 | + tok_per_sec = (step * cfg.train.batch * cfg.train.seq_len | ||||||||||||||||
| 420 | + / max(1e-9, time.time() - start_time)) | ||||||||||||||||
| 421 | + logger.info(f"step {step}/{total_steps} loss={loss_value:.4f} " | ||||||||||||||||
| 422 | + f"mem={_peak_mem_gb():.1f}GB {tok_per_sec:.0f} tok/s") | ||||||||||||||||
| 423 | + else: | ||||||||||||||||
| 424 | + logger.info(f"step {step}/{total_steps} loss={loss_value:.4f}") | ||||||||||||||||
| 425 | + if non_finite_step is not None: | ||||||||||||||||
| 426 | + logger.info(f"[train] 非有限 loss at step {non_finite_step},提前终止") | ||||||||||||||||
| 427 | + break | ||||||||||||||||
| 428 | + if non_finite_step is not None: | ||||||||||||||||
| 429 | + break | ||||||||||||||||
| 430 | + | ||||||||||||||||
| 431 | + elapsed_s = time.time() - start_time | ||||||||||||||||
| 432 | + peak_mem_gb = _peak_mem_gb() | ||||||||||||||||
| 433 | + logger.info(f"[train] 训练耗时 {elapsed_s:.1f}s 峰值显存 {peak_mem_gb:.1f}GB") | ||||||||||||||||
| 434 | + | ||||||||||||||||
| 435 | + _run_eval("训练后 loss") | ||||||||||||||||
| 436 | + | ||||||||||||||||
| 437 | + # ---- 输出:loss 日志 + summary ---- | ||||||||||||||||
| 438 | + out_root = _resolve_path(args.output_root or cfg.output.root) | ||||||||||||||||
| 439 | + out_root.mkdir(parents=True, exist_ok=True) | ||||||||||||||||
| 440 | + tag = cfg.output.tag if cfg.output.tag else ("fp8_blockwise" if fp8_enabled else "bf16") | ||||||||||||||||
| 441 | + loss_path = out_root / f"{tag}_loss.txt" | ||||||||||||||||
| 442 | + with open(loss_path, "w") as f: | ||||||||||||||||
| 443 | + for v in losses: | ||||||||||||||||
| 444 | + f.write(f"{v}\n") | ||||||||||||||||
| 445 | + summary = { | ||||||||||||||||
| 446 | + "fp8": fp8_enabled, | ||||||||||||||||
| 447 | + "model": str(cfg.model.name_hf), | ||||||||||||||||
| 448 | + "num_layers": cfg.model.num_layers, | ||||||||||||||||
| 449 | + "steps": total_steps, | ||||||||||||||||
| 450 | + "mean_loss": sum(losses) / max(1, len(losses)), | ||||||||||||||||
| 451 | + "final_loss": losses[-1] if losses else None, | ||||||||||||||||
| 452 | + "elapsed_s": round(elapsed_s, 1), | ||||||||||||||||
| 453 | + "peak_mem_gb": round(peak_mem_gb, 2), | ||||||||||||||||
| 454 | + "wgrad_hp": bool(getattr(cfg.fp8, "wgrad_hp", False)) and fp8_enabled, | ||||||||||||||||
| 455 | + "non_finite_step": non_finite_step, | ||||||||||||||||
| 456 | + } | ||||||||||||||||
| 457 | + summary_path = out_root / f"{tag}_summary.json" | ||||||||||||||||
| 458 | + with open(summary_path, "w") as f: | ||||||||||||||||
| 459 | + json.dump(summary, f, indent=2, ensure_ascii=False) | ||||||||||||||||
| 460 | + logger.info(f"[save] loss -> {loss_path}; summary -> {summary_path}") | ||||||||||||||||
| 461 | + | ||||||||||||||||
| 462 | + if cfg.output.save_ckpt: | ||||||||||||||||
| 463 | + ckpt_name = cfg.output.fp8 if fp8_enabled else cfg.output.bf16 | ||||||||||||||||
| 464 | + ckpt = out_root / ckpt_name | ||||||||||||||||
| 465 | + torch.save(model.state_dict(), ckpt) | ||||||||||||||||
| 466 | + logger.info(f"[save] 权重 -> {ckpt}") | ||||||||||||||||
| 467 | + | ||||||||||||||||
| 468 | + | ||||||||||||||||
| 469 | +if __name__ == "__main__": | ||||||||||||||||
| 470 | + main() | ||||||||||||||||
| @@ -0,0 +1,49 @@ | |||
| 1 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||
| 2 | + | ||
| 3 | +# -*- coding: utf-8 -*- | ||
| 4 | +# Qwen3.5-MoE FP8 blockwise 训练运行配置 | ||
| 5 | +# 所有相对路径都相对本配置文件所在目录或脚本目录。 | ||
| 6 | +# 模型/数据必须已本地就绪;脚本不会自动下载。 | ||
| 7 | + | ||
| 8 | +model: | ||
| 9 | + path: ./models/Qwen3.5-122B-A10B | ||
| 10 | + name_hf: Qwen/Qwen3.5-122B-A10B # 仅用于 summary 元数据 | ||
| 11 | + num_layers: 1 # 截断层数(smoke)。null = 完整层数(244GB,单卡放不下) | ||
| 12 | + | ||
| 13 | +dataset: | ||
| 14 | + path: ./datasets | ||
| 15 | + train_file: train-00000-of-00001.parquet | ||
| 16 | + eval_file: validation-00000-of-00001.parquet | ||
| 17 | + column: text # 数据集里存放文本的列名 | ||
| 18 | + | ||
| 19 | +train: | ||
| 20 | + seq_len: 512 | ||
| 21 | + batch: 1 | ||
| 22 | + max_eval_batches: 8 # 评测时最多取多少个 batch,避免全量评测太慢 | ||
| 23 | + | ||
| 24 | +fp8: | ||
| 25 | + enabled: true # true = torch._grouped_mm 重绑为 blockwise 入口;false = 仅 BF16 基线(--bf16 亦可覆盖) | ||
| 26 | + align: 128 # blockwise 组对齐 = 128(wgrad 组对齐约束;rowwise 是 16) | ||
| 27 | + wgrad_hp: true # M1 HP wgrad 开关(TORCHAO_NPU_BLOCKWISE_WGRAD_HP=1,wgrad 降噪 Ladder A) | ||
| 28 | + | ||
| 29 | +training: | ||
| 30 | + steps: 100 | ||
| 31 | + lr: '1e-6' # 1e-5 会在 100 步内把 1 层 toy 配置记忆坍缩到 loss≈0(单点口径退化);1e-6 保持 loss 在有意义区间 | ||
| 32 | + max_docs: 2000 # 最多取多少篇文本参与训练(null 表示不限制) | ||
| 33 | + max_eval_docs: 50 # 评测集最多取多少篇(null 表示不限制) | ||
| 34 | + seed: 42 | ||
| 35 | + | ||
| 36 | +runtime: | ||
| 37 | + device: npu:0 | ||
| 38 | + dtype: bfloat16 # HP master 权重(fp16 注意力等算子支持不全) | ||
| 39 | + attn_implementation: eager # NPU 上用 eager 注意力 | ||
| 40 | + | ||
| 41 | +output: | ||
| 42 | + # 指标输出目录(loss 日志 + summary.json + 运行日志) | ||
| 43 | + root: ./results/fp8_blockwise | ||
| 44 | + # 是否保存最终权重(截断模型仍较大,默认 false;true 时存到 output.bf16/fp8) | ||
| 45 | + save_ckpt: false | ||
| 46 | + bf16: blockwise_bf16_baseline.pt | ||
| 47 | + fp8: blockwise_final.pt | ||
| 48 | + # 可选的试验标签前缀(null 时默认 fp8_blockwise / bf16) | ||
| 49 | + tag: null | ||
| @@ -0,0 +1,131 @@ | |||
| 1 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||
| 2 | + | ||
| 3 | +# -*- coding: utf-8 -*- | ||
| 4 | +"""Shared MoE-pipeline helpers for the blockwise-FP8 test suites (L2/L3/L4). | ||
| 5 | + | ||
| 6 | +The L2 (module-level), L3 (shape-equivalence training) and L4 (real-checkpoint | ||
| 7 | +e2e) suites each grew a private copy of the same routing plumbing: sort routed | ||
| 8 | +rows by expert, restore token order, the BF16 per-expert reference, the | ||
| 9 | +blockwise-FP8 grouped path and the expert-load comparison stats. This module | ||
| 10 | +is the single source of those helpers and of the shared test base (the | ||
| 11 | +``TestCase``/``run_tests`` import fallback and the NPU device assertion); | ||
| 12 | +suite-specific code (L3's mini model, L4's FSDP shell) stays in the | ||
| 13 | +respective files. | ||
| 14 | + | ||
| 15 | +Import mechanics: the suites live beside this module (``moe_training/``) or | ||
| 16 | +one level below it (``e2e/``), which puts this directory on ``sys.path`` in | ||
| 17 | +every launch mode (pytest rootdir insertion, direct ``python`` script run, | ||
| 18 | +``torchrun`` rank processes) — no package machinery involved. | ||
| 19 | + | ||
| 20 | +Contract exercised here (``blockwise_fp8_analysis.md`` §8.5): fused | ||
| 21 | +``[E, N, K]`` weights (per-expert column-major after ``transpose(-2, -1)``), | ||
| 22 | +int32 group offsets, 1x128 / 128x128 block scales (``ALIGN = 128``). | ||
| 23 | +""" | ||
| 24 | +import torch | ||
| 25 | +import torch.nn.functional as F | ||
| 26 | + | ||
| 27 | +# Shared test base: the torch_npu TestCase when available, the plain | ||
| 28 | +# unittest fallback otherwise (direct-script runs without torch_npu), so | ||
| 29 | +# each suite file stays free of framework boilerplate. | ||
| 30 | +try: | ||
| 31 | + from torch_npu.testing.testcase import TestCase, run_tests | ||
| 32 | +except ImportError: | ||
| 33 | + import sys | ||
| 34 | + import unittest | ||
| 35 | + from unittest import TestCase | ||
| 36 | + | ||
| 37 | + def run_tests(): | ||
| 38 | + unittest.main(argv=sys.argv) | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def require_npu_device(testcase): | ||
| 42 | + """Assert the privateuse1 backend resolved to 'npu'; return the device.""" | ||
| 43 | + device_name = torch._C._get_privateuse1_backend_name() | ||
| 44 | + testcase.assertEqual( | ||
| 45 | + device_name, "npu", f"Expected device 'npu', got '{device_name}'" | ||
| 46 | + ) | ||
| 47 | + return torch.device(device_name) | ||
| 48 | + | ||
| 49 | +ALIGN = 128 | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +def _permute(x, topv, topi, num_experts): | ||
| 53 | + """Sort routed rows by expert, mirroring upstream ``TokenReorderer``.""" | ||
| 54 | + top_k = topi.shape[1] | ||
| 55 | + flat_expert = topi.reshape(-1) | ||
| 56 | + _, order = torch.sort(flat_expert, stable=True) | ||
| 57 | + token_ids = torch.div(order, top_k, rounding_mode="floor") | ||
| 58 | + counts = torch.zeros(num_experts, dtype=torch.int64, device=x.device) | ||
| 59 | + counts.index_add_(0, flat_expert, torch.ones_like(flat_expert)) | ||
| 60 | + return x[token_ids], topv.reshape(-1)[order], counts, token_ids | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +def _unpermute(sorted_out, token_ids, num_tokens): | ||
| 64 | + out = torch.zeros( | ||
| 65 | + (num_tokens, sorted_out.shape[-1]), | ||
| 66 | + dtype=sorted_out.dtype, | ||
| 67 | + device=sorted_out.device, | ||
| 68 | + ) | ||
| 69 | + return out.index_add(0, token_ids, sorted_out) | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +def _ref_experts(sorted_x, sorted_score, counts, w1, w2, w3): | ||
| 73 | + """torchtitan reference: score before experts, then the gated FFN.""" | ||
| 74 | + xg = sorted_x * sorted_score.unsqueeze(-1) | ||
| 75 | + parts = [] | ||
| 76 | + start = 0 | ||
| 77 | + for expert, count in enumerate(counts.tolist()): | ||
| 78 | + if count: | ||
| 79 | + x_e = xg[start : start + count] | ||
| 80 | + h = F.silu(x_e @ w1[expert].t()) * (x_e @ w3[expert].t()) | ||
| 81 | + parts.append(h @ w2[expert].t()) | ||
| 82 | + else: | ||
| 83 | + parts.append(xg.new_zeros((0, xg.shape[-1]))) | ||
| 84 | + start += count | ||
| 85 | + return torch.cat(parts, dim=0) | ||
| 86 | + | ||
| 87 | + | ||
| 88 | +def _fp8_experts(sorted_x, sorted_score, counts, w1, w2, w3, pad=True): | ||
| 89 | + """Same math as ``_ref_experts`` with the three GEMMs in blockwise FP8. | ||
| 90 | + | ||
| 91 | + ``pad=False`` is legal only when every group is already 128-row aligned | ||
| 92 | + (the wgrad block-alignment contract); the suites keep ``pad=True`` for | ||
| 93 | + arbitrary routing. | ||
| 94 | + """ | ||
| 95 | + from torchao.prototype.moe_training.blockwise_fp8.grouped_mm import ( | ||
| 96 | + _to_fp8_blockwise_then_scaled_grouped_mm, | ||
| 97 | + ) | ||
| 98 | + from torchao.quantization.quantize_.common import KernelPreference | ||
| 99 | + | ||
| 100 | + offs = torch.cumsum(counts, 0).to(torch.int32) | ||
| 101 | + | ||
| 102 | + def gmm(a, weight): | ||
| 103 | + # weight (E, out, in) is contiguous, so its transpose is per-expert | ||
| 104 | + # column-major (E, in, out) as the grouped MM frontend requires. | ||
| 105 | + return _to_fp8_blockwise_then_scaled_grouped_mm( | ||
| 106 | + a, | ||
| 107 | + weight.transpose(-2, -1), | ||
| 108 | + offs, | ||
| 109 | + out_dtype=torch.bfloat16, | ||
| 110 | + float8_dtype=torch.float8_e4m3fn, | ||
| 111 | + block_size=ALIGN, | ||
| 112 | + pad_token_groups_for_grouped_mm=pad, | ||
| 113 | + kernel_preference=KernelPreference.NPU, | ||
| 114 | + ) | ||
| 115 | + | ||
| 116 | + xg = sorted_x * sorted_score.unsqueeze(-1) | ||
| 117 | + h = F.silu(gmm(xg, w1)) * gmm(xg, w3) | ||
| 118 | + return gmm(h, w2) | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +def _load_stats(c_ref, c_fp8): | ||
| 122 | + """Compare two tokens-per-expert load vectors (routing drift metrics).""" | ||
| 123 | + total = max(int(c_ref.sum()), 1) | ||
| 124 | + a, b = c_ref.float(), c_fp8.float() | ||
| 125 | + return { | ||
| 126 | + "rel_l1": float((c_ref - c_fp8).abs().sum()) / total, | ||
| 127 | + "max_abs_diff": int((c_ref - c_fp8).abs().max()), | ||
| 128 | + "cosine": float((a * b).sum() / (a.norm() * b.norm() + 1e-12)), | ||
| 129 | + "min_load_ref": int(c_ref.min()), | ||
| 130 | + "min_load_fp8": int(c_fp8.min()), | ||
| 131 | + } | ||
| @@ -0,0 +1,147 @@ | |||
| 1 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||
| 2 | + | ||
| 3 | +# -*- coding: utf-8 -*- | ||
| 4 | +"""Blockwise-FP8 + FSDP1 NPU functional smoke (rowwise-bar parity). | ||
| 5 | + | ||
| 6 | +Coverage deliberately mirrors ``test_float8_fsdp_npu.py`` (the rowwise FP8 | ||
| 7 | +bar): a single-card functional check that the blockwise path composes with | ||
| 8 | +FSDP wrapping — forward/backward precision, gradient flow and the plain-full- | ||
| 9 | +parameter contract. It is NOT the deployment-level e2e (multi-card, | ||
| 10 | +real-checkpoint, memory ratios) that used to live in | ||
| 11 | +``e2e/test_blockwise_fp8_qwen3_l4_e2e.py``; that was removed in the | ||
| 12 | +verification slimming, keeping blockwise's distributed coverage at the same | ||
| 13 | +bar as rowwise. | ||
| 14 | + | ||
| 15 | +FSDP1 (``FullyShardedDataParallel``) is the matching shell: it materialises | ||
| 16 | +plain full parameters (``use_orig_params``), so the NPU grouped-GEMM kernels | ||
| 17 | +see ordinary tensors and no collective is added inside the blockwise path | ||
| 18 | +(FSDP2/DTensor would additionally need an explicit ``to_local`` step, which | ||
| 19 | +the blockwise path does not implement). | ||
| 20 | + | ||
| 21 | +Run: python -m pytest test/npu/prototype/moe_training/test_blockwise_fp8_fsdp_npu.py -v | ||
| 22 | +""" | ||
| 23 | +import os | ||
| 24 | + | ||
| 25 | +import torch | ||
| 26 | +import torch.distributed as dist | ||
| 27 | +import torch.nn as nn | ||
| 28 | +import torch_npu | ||
| 29 | +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP | ||
| 30 | +from torch.distributed.tensor import DTensor | ||
| 31 | + | ||
| 32 | +from _blockwise_test_utils import TestCase, require_npu_device, run_tests | ||
| 33 | + | ||
| 34 | +# 保守精度阈值,与 rowwise 侧(test_float8_*_npu.py)一致。 | ||
| 35 | +_MIN_COSINE = 0.95 | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +def _cosine_sim(a: torch.Tensor, b: torch.Tensor) -> float: | ||
| 39 | + return torch.nn.functional.cosine_similarity( | ||
| 40 | + a.detach().flatten().float(), b.detach().flatten().float(), dim=0 | ||
| 41 | + ).item() | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +class _SmallMoE(nn.Module): | ||
| 45 | + """Fused w1/w2/w3 MoE block routed through the blockwise-FP8 grouped path.""" | ||
| 46 | + | ||
| 47 | + def __init__(self, dim=128, hidden=128, num_experts=4, top_k=2, use_fp8=True): | ||
| 48 | + super().__init__() | ||
| 49 | + self.router = nn.Linear(dim, num_experts, bias=False) | ||
| 50 | + bound = 1.0 / dim**0.5 | ||
| 51 | + self.w1 = nn.Parameter(torch.randn(num_experts, hidden, dim) * bound) | ||
| 52 | + self.w2 = nn.Parameter(torch.randn(num_experts, dim, hidden) * bound) | ||
| 53 | + self.w3 = nn.Parameter(torch.randn(num_experts, hidden, dim) * bound) | ||
| 54 | + self.top_k = top_k | ||
| 55 | + self.num_experts = num_experts | ||
| 56 | + self.use_fp8 = use_fp8 | ||
| 57 | + | ||
| 58 | + def forward(self, x): | ||
| 59 | + from _blockwise_test_utils import _fp8_experts, _permute, _ref_experts, _unpermute | ||
| 60 | + | ||
| 61 | + probs = torch.softmax(self.router(x).float(), dim=-1) | ||
| 62 | + topv, topi = probs.topk(self.top_k, dim=-1) | ||
| 63 | + topv = (topv / topv.sum(dim=-1, keepdim=True)).to(x.dtype) | ||
| 64 | + xs, ss, counts, token_ids = _permute(x, topv, topi, self.num_experts) | ||
| 65 | + if self.use_fp8: | ||
| 66 | + dt = xs.dtype | ||
| 67 | + rows = _fp8_experts( | ||
| 68 | + xs, ss, counts, self.w1.to(dt), self.w2.to(dt), self.w3.to(dt) | ||
| 69 | + ) | ||
| 70 | + else: | ||
| 71 | + rows = _ref_experts(xs, ss, counts, self.w1, self.w2, self.w3) | ||
| 72 | + return _unpermute(rows, token_ids, x.shape[0]) | ||
| 73 | + | ||
| 74 | + | ||
| 75 | +class TestBlockwiseFp8FSDP1NPU(TestCase): | ||
| 76 | + @classmethod | ||
| 77 | + def setUpClass(cls): | ||
| 78 | + super().setUpClass() | ||
| 79 | + # world_size=1 functional smoke; port offset per pid (mirrors rowwise file). | ||
| 80 | + torch.npu.set_device(0) | ||
| 81 | + port = 29500 + os.getpid() % 1000 | ||
| 82 | + dist.init_process_group( | ||
| 83 | + "hccl", init_method=f"tcp://127.0.0.1:{port}", rank=0, world_size=1 | ||
| 84 | + ) | ||
| 85 | + | ||
| 86 | + @classmethod | ||
| 87 | + def tearDownClass(cls): | ||
| 88 | + dist.destroy_process_group() | ||
| 89 | + super().tearDownClass() | ||
| 90 | + | ||
| 91 | + def setUp(self): | ||
| 92 | + super().setUp() | ||
| 93 | + self.device = require_npu_device(self) | ||
| 94 | + | ||
| 95 | + @staticmethod | ||
| 96 | + def _apply_patches(): | ||
| 97 | + from torchao_ascend.patches.torchao.prototype.moe_training.blockwise_fp8 import ( | ||
| 98 | + grouped_mm_backend as patch_mod, | ||
| 99 | + ) | ||
| 100 | + | ||
| 101 | + patch_mod.apply() | ||
| 102 | + # patch 注册态守护断言:防止补丁静默未生效(回归看护) | ||
| 103 | + assert patch_mod._applied, "blockwise backend patch must be applied" | ||
| 104 | + | ||
| 105 | + def test_fsdp1_fwd_bwd_plain_params(self): | ||
| 106 | + """FSDP1 包裹后的 blockwise 前反向:精度、梯度与 plain-param 契约。""" | ||
| 107 | + self._apply_patches() | ||
| 108 | + torch.manual_seed(0) | ||
| 109 | + model = _SmallMoE(use_fp8=True).bfloat16().to(self.device) | ||
| 110 | + ref_model = _SmallMoE(use_fp8=False).bfloat16().to(self.device) | ||
| 111 | + ref_model.load_state_dict(model.state_dict()) | ||
| 112 | + x = torch.randn(256, model.w1.shape[-1], device=self.device, dtype=torch.bfloat16) | ||
| 113 | + expected = ref_model(x) # graph kept: the reference takes a real backward below | ||
| 114 | + | ||
| 115 | + wrapped = FSDP( | ||
| 116 | + model, use_orig_params=True, device_id=self.device, limit_all_gathers=True | ||
| 117 | + ) | ||
| 118 | + got = wrapped(x) | ||
| 119 | + got.sum().backward() | ||
| 120 | + expected.sum().backward() # same scalar target -> reference grads exist | ||
| 121 | + | ||
| 122 | + self.assertGreater(_cosine_sim(got, expected), _MIN_COSINE) | ||
| 123 | + for name, param in wrapped.named_parameters(): | ||
| 124 | + self.assertIsNotNone(param.grad, f"{name} grad missing") | ||
| 125 | + # FSDP1 use_orig_params: blockwise kernels see plain full tensors, | ||
| 126 | + # never DTensor (the FSDP2 to_local step is not implemented). | ||
| 127 | + self.assertNotIsInstance(param, DTensor, f"{name} must be a plain tensor") | ||
| 128 | + | ||
| 129 | + # 梯度方向对照 bf16 逐专家参考(同一 init、同一路由)。FSDP1 的 | ||
| 130 | + # named_parameters 带 ``_fsdp_wrapped_module.`` 前缀,比对前剥离, | ||
| 131 | + # 否则逐参余弦断言静默空转(评审意见:参数名前缀门)。 | ||
| 132 | + ref_params = dict(ref_model.named_parameters()) | ||
| 133 | + compared = 0 | ||
| 134 | + for name, param in wrapped.named_parameters(): | ||
| 135 | + ref_name = name.replace("_fsdp_wrapped_module.", "") | ||
| 136 | + if ref_name in ref_params and ref_params[ref_name].grad is not None: | ||
| 137 | + compared += 1 | ||
| 138 | + self.assertGreater( | ||
| 139 | + _cosine_sim(param.grad, ref_params[ref_name].grad), | ||
| 140 | + _MIN_COSINE, | ||
| 141 | + f"{ref_name} grad cosine below {_MIN_COSINE}", | ||
| 142 | + ) | ||
| 143 | + self.assertGreater(compared, 0, "per-parameter grad cosine never compared") | ||
| 144 | + | ||
| 145 | + | ||
| 146 | +if __name__ == "__main__": | ||
| 147 | + run_tests() | ||
| @@ -0,0 +1,371 @@ | |||
| 1 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||
| 2 | + | ||
| 3 | +# -*- coding: utf-8 -*- | ||
| 4 | +"""Correctness test for the MoE blockwise-FP8 grouped GEMM patch. | ||
| 5 | + | ||
| 6 | +Exercises ``torchao.prototype.moe_training.blockwise_fp8`` after the NPU | ||
| 7 | +backend patch (``torchao_ascend/patches/torchao/prototype/moe_training/ | ||
| 8 | +blockwise_fp8/grouped_mm_backend.py``) is applied: | ||
| 9 | + | ||
| 10 | +* T0 — Tier-1 grouped block quant (``npu_grouped_dynamic_block_quant``) vs the | ||
| 11 | + per-expert dense primitive, when the installed build exposes it. The Tier-1 | ||
| 12 | + kernel emits one padding row after every group's scale segment (layout probed | ||
| 13 | + on Ascend950/CANN 9.2), so the padded rows are gathered out before compare. | ||
| 14 | +* T2 — grouped GEMM forward/backward vs a BF16 per-expert reference, aligned | ||
| 15 | + and padded (unaligned) token groups, zero-token experts. | ||
| 16 | +* T3 — wgrad demands block-aligned groups when padding is disabled. | ||
| 17 | +* HP — wgrad HP fallback (``grouped_mm_backend.WGRAD_HP``) matches the | ||
| 18 | + BF16 per-expert reference; fp8 and HP paths share the ``[E, N, K]`` contract. | ||
| 19 | + | ||
| 20 | +Patches are applied in isolation (only this patch), so unrelated patch groups | ||
| 21 | +cannot mask the result. | ||
| 22 | + | ||
| 23 | +Run: python -m pytest test/npu/prototype/moe_training/test_blockwise_fp8_grouped_mm.py -v | ||
| 24 | +""" | ||
| 25 | +from unittest import mock | ||
| 26 | + | ||
| 27 | +import torch | ||
| 28 | +import torch_npu # noqa: F401 | ||
| 29 | + | ||
| 30 | +from _blockwise_test_utils import TestCase, require_npu_device, run_tests | ||
| 31 | +from torchao.quantization.quantize_.common import KernelPreference | ||
| 32 | + | ||
| 33 | +ALIGN = 128 | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def _starts_ends(offs): | ||
| 37 | + ends = offs.tolist() | ||
| 38 | + return [0] + ends[:-1], ends | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def _ref_fwd(A, B_t, offs): | ||
| 42 | + starts, ends = _starts_ends(offs) | ||
| 43 | + parts = [A[s:e] @ B_t[i] for i, (s, e) in enumerate(zip(starts, ends))] | ||
| 44 | + return torch.cat(parts, dim=0) | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +def _ref_bwd(A, B_t, offs, grad_output): | ||
| 48 | + starts, ends = _starts_ends(offs) | ||
| 49 | + grad_A, grad_B_t = [], torch.zeros_like(B_t) | ||
| 50 | + for i, (s, e) in enumerate(zip(starts, ends)): | ||
| 51 | + if e == s: | ||
| 52 | + continue | ||
| 53 | + go_e = grad_output[s:e] | ||
| 54 | + grad_A.append(go_e @ B_t[i].t()) | ||
| 55 | + grad_B_t[i] = (go_e.t() @ A[s:e]).t() | ||
| 56 | + return torch.cat(grad_A, dim=0), grad_B_t | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def _snr_db(ref, out): | ||
| 60 | + """Signal-to-noise ratio in dB (same convention as torchao.compute_error).""" | ||
| 61 | + ref = ref.detach().float() | ||
| 62 | + out = out.detach().float() | ||
| 63 | + signal = ref.square().sum().clamp_min(1e-12) | ||
| 64 | + noise = (ref - out).square().sum().clamp_min(1e-12) | ||
| 65 | + return float(10.0 * torch.log10(signal / noise)) | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +def _tier1_scale_data_rows(s1, ends): | ||
| 69 | + """Gather the per-token scale rows out of Tier-1's padded scale layout. | ||
| 70 | + | ||
| 71 | + ``npu_grouped_dynamic_block_quant`` appends one padding row after every | ||
| 72 | + group's segment (empty groups included), so the scale carries | ||
| 73 | + ``M + num_groups`` rows and token ``t`` of group ``g`` lives at row | ||
| 74 | + ``t + g``. Padding rows are uninitialised and must never be compared. | ||
| 75 | + """ | ||
| 76 | + ends_list = ends.tolist() | ||
| 77 | + starts = [0] + ends_list[:-1] | ||
| 78 | + idx = [] | ||
| 79 | + for g, (st, en) in enumerate(zip(starts, ends_list)): | ||
| 80 | + idx.extend(range(st + g, en + g)) | ||
| 81 | + index = torch.tensor(idx, dtype=torch.int64, device=s1.device) | ||
| 82 | + return s1.index_select(0, index) | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +class TestBlockwiseFp8GroupedMMNPU(TestCase): | ||
| 86 | + def setUp(self): | ||
| 87 | + super().setUp() | ||
| 88 | + self.device = require_npu_device(self) | ||
| 89 | + | ||
| 90 | + @staticmethod | ||
| 91 | + def _apply_patches(): | ||
| 92 | + from torchao_ascend.patches.torchao.prototype.moe_training.blockwise_fp8 import ( | ||
| 93 | + grouped_mm_backend as patch_mod, | ||
| 94 | + ) | ||
| 95 | + | ||
| 96 | + patch_mod.apply() | ||
| 97 | + # patch 注册态守护断言:防止补丁静默未生效(回归看护) | ||
| 98 | + assert patch_mod._applied, "blockwise backend patch must be applied" | ||
| 99 | + | ||
| 100 | + # ------------------------------------------------------------------ T0 | ||
| 101 | + def test_tier1_grouped_block_quant_matches_tier2(self): | ||
| 102 | + """Tier-1 grouped quant must match the per-expert loop bit-for-bit-ish.""" | ||
| 103 | + from torchao_ascend.ops.npu import fp8_block_ops | ||
| 104 | + | ||
| 105 | + if not fp8_block_ops.HAS_GROUPED_BLOCK_QUANT: | ||
| 106 | + self.skipTest("npu_grouped_dynamic_block_quant not available in this build") | ||
| 107 | + torch.manual_seed(0) | ||
| 108 | + ends = torch.tensor([128, 384, 512], dtype=torch.int32, device=self.device) | ||
| 109 | + x = torch.randn(512, 256, dtype=torch.bfloat16, device=self.device) | ||
| 110 | + | ||
| 111 | + with mock.patch.object(fp8_block_ops, "HAS_GROUPED_BLOCK_QUANT", False): | ||
| 112 | + q2, s2 = fp8_block_ops.grouped_block_quant( | ||
| 113 | + x, ends, dst_type=torch.float8_e4m3fn, | ||
| 114 | + row_block_size=1, col_block_size=ALIGN, | ||
| 115 | + ) | ||
| 116 | + with mock.patch.object(fp8_block_ops, "HAS_GROUPED_BLOCK_QUANT", True): | ||
| 117 | + q1, s1 = fp8_block_ops.grouped_block_quant( | ||
| 118 | + x, ends, dst_type=torch.float8_e4m3fn, | ||
| 119 | + row_block_size=1, col_block_size=ALIGN, | ||
| 120 | + ) | ||
| 121 | + self.assertEqual(q1.shape, q2.shape) | ||
| 122 | + # Tier-1 pads the scale with one row per group; data rows must align. | ||
| 123 | + self.assertEqual(s1.shape[0], s2.shape[0] + ends.numel()) | ||
| 124 | + self.assertEqual(s1.shape[1], s2.shape[1]) | ||
| 125 | + s1_data = _tier1_scale_data_rows(s1, ends) | ||
| 126 | + self.assertGreater(_snr_db(q2.float(), q1.float()), 40.0) | ||
| 127 | + self.assertGreater(_snr_db(s2, s1_data), 40.0) | ||
| 128 | + | ||
| 129 | + # ------------------------------------------------------------------ T2 | ||
| 130 | + def test_grouped_mm_fwd_bwd_aligned_groups(self): | ||
| 131 | + from torchao.prototype.moe_training.blockwise_fp8.grouped_mm import ( | ||
| 132 | + _to_fp8_blockwise_then_scaled_grouped_mm, | ||
| 133 | + ) | ||
| 134 | + | ||
| 135 | + self._apply_patches() | ||
| 136 | + torch.manual_seed(0) | ||
| 137 | + E, K, N = 2, 256, 256 | ||
| 138 | + tokens = [256, 256] | ||
| 139 | + M = sum(tokens) | ||
| 140 | + A = (torch.randn(M, K, dtype=torch.bfloat16, device=self.device) * 0.5).requires_grad_(True) | ||
| 141 | + B_t = ( | ||
| 142 | + torch.randn(E, N, K, dtype=torch.bfloat16, device=self.device) * 0.5 | ||
| 143 | + ).contiguous().transpose(-2, -1).requires_grad_(True) | ||
| 144 | + offs = torch.tensor( | ||
| 145 | + [tokens[0], M], dtype=torch.int32, device=self.device | ||
| 146 | + ) | ||
| 147 | + | ||
| 148 | + out = _to_fp8_blockwise_then_scaled_grouped_mm( | ||
| 149 | + A, B_t, offs, pad_token_groups_for_grouped_mm=False, | ||
| 150 | + kernel_preference=KernelPreference.NPU, | ||
| 151 | + ) | ||
| 152 | + ref = _ref_fwd(A.detach(), B_t.detach(), offs) | ||
| 153 | + self.assertEqual(out.shape, ref.shape) | ||
| 154 | + self.assertGreater(_snr_db(ref, out), 25.0, "fwd SNR below 25dB") | ||
| 155 | + | ||
| 156 | + grad_output = torch.randn_like(out) * 0.5 | ||
| 157 | + out.backward(grad_output) | ||
| 158 | + ref_ga, ref_gb = _ref_bwd(A.detach(), B_t.detach(), offs, grad_output) | ||
| 159 | + self.assertGreater(_snr_db(ref_ga, A.grad), 24.0, "grad_A SNR below 24dB") | ||
| 160 | + self.assertGreater(_snr_db(ref_gb, B_t.grad), 24.0, "grad_B_t SNR below 24dB") | ||
| 161 | + | ||
| 162 | + def test_grouped_mm_fwd_bwd_padded_groups(self): | ||
| 163 | + from torchao.prototype.moe_training.blockwise_fp8.grouped_mm import ( | ||
| 164 | + _to_fp8_blockwise_then_scaled_grouped_mm, | ||
| 165 | + ) | ||
| 166 | + | ||
| 167 | + self._apply_patches() | ||
| 168 | + torch.manual_seed(1) | ||
| 169 | + E, K, N = 3, 256, 256 | ||
| 170 | + tokens = [129, 255, 116] # unaligned: padding must kick in | ||
| 171 | + M = sum(tokens) | ||
| 172 | + A = (torch.randn(M, K, dtype=torch.bfloat16, device=self.device) * 0.5).requires_grad_(True) | ||
| 173 | + B_t = ( | ||
| 174 | + torch.randn(E, N, K, dtype=torch.bfloat16, device=self.device) * 0.5 | ||
| 175 | + ).contiguous().transpose(-2, -1).requires_grad_(True) | ||
| 176 | + offs = torch.tensor( | ||
| 177 | + [tokens[0], tokens[0] + tokens[1], M], dtype=torch.int32, device=self.device | ||
| 178 | + ) | ||
| 179 | + | ||
| 180 | + out = _to_fp8_blockwise_then_scaled_grouped_mm( | ||
| 181 | + A, B_t, offs, pad_token_groups_for_grouped_mm=True, | ||
| 182 | + kernel_preference=KernelPreference.NPU, | ||
| 183 | + ) | ||
| 184 | + ref = _ref_fwd(A.detach(), B_t.detach(), offs) | ||
| 185 | + self.assertEqual(out.shape, (M, N)) | ||
| 186 | + self.assertGreater(_snr_db(ref, out), 25.0, "padded fwd SNR below 25dB") | ||
| 187 | + | ||
| 188 | + grad_output = torch.randn_like(out) * 0.5 | ||
| 189 | + out.backward(grad_output) | ||
| 190 | + ref_ga, ref_gb = _ref_bwd(A.detach(), B_t.detach(), offs, grad_output) | ||
| 191 | + self.assertGreater(_snr_db(ref_ga, A.grad), 24.0, "padded grad_A SNR below 24dB") | ||
| 192 | + self.assertGreater(_snr_db(ref_gb, B_t.grad), 24.0, "padded grad_B_t SNR below 24dB") | ||
| 193 | + | ||
| 194 | + def test_grouped_mm_zero_token_expert(self): | ||
| 195 | + from torchao.prototype.moe_training.blockwise_fp8.grouped_mm import ( | ||
| 196 | + _to_fp8_blockwise_then_scaled_grouped_mm, | ||
| 197 | + ) | ||
| 198 | + | ||
| 199 | + self._apply_patches() | ||
| 200 | + torch.manual_seed(2) | ||
| 201 | + E, K, N = 3, 128, 128 | ||
| 202 | + A = (torch.randn(256, K, dtype=torch.bfloat16, device=self.device) * 0.5).requires_grad_(True) | ||
| 203 | + B_t = ( | ||
| 204 | + torch.randn(E, N, K, dtype=torch.bfloat16, device=self.device) * 0.5 | ||
| 205 | + ).contiguous().transpose(-2, -1).requires_grad_(True) | ||
| 206 | + offs = torch.tensor([128, 128, 256], dtype=torch.int32, device=self.device) | ||
| 207 | + | ||
| 208 | + out = _to_fp8_blockwise_then_scaled_grouped_mm( | ||
| 209 | + A, B_t, offs, pad_token_groups_for_grouped_mm=False, | ||
| 210 | + kernel_preference=KernelPreference.NPU, | ||
| 211 | + ) | ||
| 212 | + self.assertFalse(torch.isnan(out).any(), "zero-token expert produced NaN") | ||
| 213 | + ref = _ref_fwd(A.detach(), B_t.detach(), offs) | ||
| 214 | + self.assertGreater(_snr_db(ref, out), 25.0) | ||
| 215 | + | ||
| 216 | + out.backward(torch.randn_like(out) * 0.5) | ||
| 217 | + self.assertEqual(B_t.grad[1].abs().max().item(), 0.0) | ||
| 218 | + self.assertFalse(torch.isnan(B_t.grad).any(), "grad produced NaN") | ||
| 219 | + | ||
| 220 | + # ------------------------------------------------------------------ T3 | ||
| 221 | + def test_wgrad_requires_block_aligned_groups(self): | ||
| 222 | + from torchao.prototype.moe_training.blockwise_fp8.grouped_mm import ( | ||
| 223 | + _to_fp8_blockwise_then_scaled_grouped_mm, | ||
| 224 | + ) | ||
| 225 | + | ||
| 226 | + self._apply_patches() | ||
| 227 | + torch.manual_seed(3) | ||
| 228 | + E, K, N = 2, 128, 128 | ||
| 229 | + tokens = [100, 156] # not block-aligned, padding disabled | ||
| 230 | + M = sum(tokens) | ||
| 231 | + A = torch.randn(M, K, dtype=torch.bfloat16, device=self.device).requires_grad_(True) | ||
| 232 | + B_t = ( | ||
| 233 | + torch.randn(E, N, K, dtype=torch.bfloat16, device=self.device) | ||
| 234 | + ).contiguous().transpose(-2, -1).requires_grad_(True) | ||
| 235 | + offs = torch.tensor([tokens[0], M], dtype=torch.int32, device=self.device) | ||
| 236 | + | ||
| 237 | + out = _to_fp8_blockwise_then_scaled_grouped_mm( | ||
| 238 | + A, B_t, offs, pad_token_groups_for_grouped_mm=False, | ||
| 239 | + kernel_preference=KernelPreference.NPU, | ||
| 240 | + ) | ||
| 241 | + with self.assertRaises(ValueError): | ||
| 242 | + out.backward(torch.randn_like(out)) | ||
| 243 | + | ||
| 244 | + # ------------------------------------------------------------------ HP wgrad | ||
| 245 | + def test_wgrad_hp_matches_bf16_reference(self): | ||
| 246 | + """HP wgrad (grouped_mm_backend.WGRAD_HP) vs BF16 per-expert ref.""" | ||
| 247 | + from torchao_ascend.patches.torchao.prototype.moe_training.blockwise_fp8 import ( | ||
| 248 | + grouped_mm_backend as patch_mod, | ||
| 249 | + ) | ||
| 250 | + | ||
| 251 | + self._apply_patches() | ||
| 252 | + torch.manual_seed(4) | ||
| 253 | + E, K, N = 2, 128, 128 | ||
| 254 | + offs = torch.tensor([128, 256], dtype=torch.int32, device=self.device) | ||
| 255 | + M = int(offs[-1]) | ||
| 256 | + go = torch.randn(M, N, dtype=torch.bfloat16, device=self.device) * 0.5 | ||
| 257 | + a = torch.randn(M, K, dtype=torch.bfloat16, device=self.device) * 0.5 | ||
| 258 | + | ||
| 259 | + with mock.patch.object(patch_mod, "WGRAD_HP", True): | ||
| 260 | + out = patch_mod._NPU_BACKEND.wgrad( | ||
| 261 | + go, a, offs, torch.bfloat16, ALIGN, torch.float8_e4m3fn | ||
| 262 | + ) | ||
| 263 | + self.assertEqual(out.shape, (E, N, K)) | ||
| 264 | + starts, ends = _starts_ends(offs) | ||
| 265 | + ref = torch.stack( | ||
| 266 | + [go[s:e].t() @ a[s:e] for s, e in zip(starts, ends)] | ||
| 267 | + ).to(torch.bfloat16) | ||
| 268 | + rel = (out.float() - ref.float()).norm() / ref.float().norm().clamp_min(1e-12) | ||
| 269 | + self.assertLess(float(rel), 1e-2, "HP wgrad deviates from BF16 reference") | ||
| 270 | + | ||
| 271 | + def test_wgrad_two_path_shapes_consistent(self): | ||
| 272 | + """fp8 (default) and HP wgrad outputs share the [E, N, K] contract.""" | ||
| 273 | + from torchao_ascend.patches.torchao.prototype.moe_training.blockwise_fp8 import ( | ||
| 274 | + grouped_mm_backend as patch_mod, | ||
| 275 | + ) | ||
| 276 | + | ||
| 277 | + self._apply_patches() | ||
| 278 | + torch.manual_seed(5) | ||
| 279 | + E, K, N = 2, 128, 128 | ||
| 280 | + offs = torch.tensor([128, 256], dtype=torch.int32, device=self.device) | ||
| 281 | + M = int(offs[-1]) | ||
| 282 | + go = torch.randn(M, N, dtype=torch.bfloat16, device=self.device) * 0.5 | ||
| 283 | + a = torch.randn(M, K, dtype=torch.bfloat16, device=self.device) * 0.5 | ||
| 284 | + | ||
| 285 | + with mock.patch.object(patch_mod, "WGRAD_HP", False): | ||
| 286 | + out_fp8 = patch_mod._NPU_BACKEND.wgrad( | ||
| 287 | + go, a, offs, torch.bfloat16, ALIGN, torch.float8_e4m3fn | ||
| 288 | + ) | ||
| 289 | + with mock.patch.object(patch_mod, "WGRAD_HP", True): | ||
| 290 | + out_hp = patch_mod._NPU_BACKEND.wgrad( | ||
| 291 | + go, a, offs, torch.bfloat16, ALIGN, torch.float8_e4m3fn | ||
| 292 | + ) | ||
| 293 | + self.assertEqual(out_fp8.shape, (E, N, K)) | ||
| 294 | + self.assertEqual(out_hp.shape, out_fp8.shape) | ||
| 295 | + # fp8 quantizes both operands; HP is bf16-exact. The gap is the fp8 | ||
| 296 | + # blockwise quantization noise — same magnitude class as the ≥26 dB | ||
| 297 | + # gradient thresholds used by the T2 cases above. | ||
| 298 | + self.assertGreater(_snr_db(out_hp, out_fp8), 26.0) | ||
| 299 | + | ||
| 300 | + # ------------------------------------------------- coverage completion | ||
| 301 | + def test_quantize_dgrad_rhs_requires_forward_first(self): | ||
| 302 | + """quantize_dgrad_rhs 为纯缓存读取:必须先跑 quantize_forward_rhs。 | ||
| 303 | + | ||
| 304 | + autograd 流程里 forward 总是先行(ctx.backend 复用同一实例,dgrad_rhs | ||
| 305 | + 必然缓存命中);独立 cache-miss 调用按 fail-loud 契约直接 raise | ||
| 306 | + (评审意见:该分支在正常流程中不可达,移除)。 | ||
| 307 | + """ | ||
| 308 | + from torchao_ascend.patches.torchao.prototype.moe_training.blockwise_fp8 import ( | ||
| 309 | + grouped_mm_backend as patch_mod, | ||
| 310 | + ) | ||
| 311 | + | ||
| 312 | + self._apply_patches() | ||
| 313 | + torch.manual_seed(6) | ||
| 314 | + E, K, N = 2, 256, 128 | ||
| 315 | + B_t = torch.randn(E, K, N, dtype=torch.bfloat16, device=self.device) | ||
| 316 | + with mock.patch.object(patch_mod, "WQ_CACHE", True): | ||
| 317 | + backend = patch_mod._NPUGroupedMMBackend() | ||
| 318 | + fwd_q, _ = backend.quantize_forward_rhs(B_t, ALIGN, torch.float8_e4m3fn) | ||
| 319 | + dgrad_q, dgrad_s = backend.quantize_dgrad_rhs(B_t, ALIGN, torch.float8_e4m3fn) | ||
| 320 | + self.assertIs(dgrad_q, backend._q_cache[0], "WQ_CACHE=1: dgrad reads the cache") | ||
| 321 | + self.assertEqual(tuple(dgrad_q.shape), (E, N, K)) | ||
| 322 | + self.assertEqual(dgrad_q.data_ptr(), fwd_q.data_ptr(), | ||
| 323 | + "dgrad reads the same storage forward quantized") | ||
| 324 | + | ||
| 325 | + with mock.patch.object(patch_mod, "WQ_CACHE", False): | ||
| 326 | + backend = patch_mod._NPUGroupedMMBackend() | ||
| 327 | + fwd_q0, _ = backend.quantize_forward_rhs(B_t, ALIGN, torch.float8_e4m3fn) | ||
| 328 | + self.assertIsNone(backend._q_cache, "WQ_CACHE=0: forward must not stash") | ||
| 329 | + dgrad_q0, dgrad_s0 = backend.quantize_dgrad_rhs(B_t, ALIGN, torch.float8_e4m3fn) | ||
| 330 | + self.assertIsNot(dgrad_q0.data_ptr(), fwd_q0.data_ptr(), | ||
| 331 | + "WQ_CACHE=0: dgrad re-quantizes (fresh storage)") | ||
| 332 | + self.assertEqual(dgrad_q0.shape, fwd_q0.transpose(-2, -1).shape) | ||
| 333 | + self.assertGreater(_snr_db(fwd_q0.transpose(-2, -1).float(), dgrad_q0.float()), 40.0, | ||
| 334 | + "re-quantized values must match the forward quantization") | ||
| 335 | + | ||
| 336 | + def test_wgrad_zero_group_and_alignment_contract(self): | ||
| 337 | + """零 token 组的 wgrad 梯度恰零;未对齐组必须被拒绝(backend 契约)。""" | ||
| 338 | + from torchao_ascend.patches.torchao.prototype.moe_training.blockwise_fp8 import ( | ||
| 339 | + grouped_mm_backend as patch_mod, | ||
| 340 | + ) | ||
| 341 | + | ||
| 342 | + self._apply_patches() | ||
| 343 | + torch.manual_seed(7) | ||
| 344 | + K, N = 256, 128 | ||
| 345 | + padded_a = torch.randn(256, K, dtype=torch.bfloat16, device=self.device) * 0.5 | ||
| 346 | + padded_go = torch.randn(256, N, dtype=torch.bfloat16, device=self.device) * 0.5 | ||
| 347 | + # 组大小 128 / 0 / 128:零 token 专家位于中间 | ||
| 348 | + offs = torch.tensor([128, 128, 256], dtype=torch.int32, device=self.device) | ||
| 349 | + grad = patch_mod._NPU_BACKEND.wgrad( | ||
| 350 | + padded_go, padded_a, offs, torch.bfloat16, ALIGN, torch.float8_e4m3fn | ||
| 351 | + ) | ||
| 352 | + self.assertEqual(tuple(grad.shape), (3, N, K)) | ||
| 353 | + self.assertEqual( | ||
| 354 | + float(grad[1].abs().max()), 0.0, "zero-group grad must be exactly zero" | ||
| 355 | + ) | ||
| 356 | + self.assertGreater(float(grad[0].abs().max()), 0.0) | ||
| 357 | + self.assertGreater(float(grad[2].abs().max()), 0.0) | ||
| 358 | + | ||
| 359 | + bad_offs = torch.tensor([100, 256], dtype=torch.int32, device=self.device) | ||
| 360 | + with self.assertRaises(ValueError): | ||
| 361 | + patch_mod._NPU_BACKEND.wgrad( | ||
| 362 | + padded_go, padded_a, bad_offs, torch.bfloat16, ALIGN, torch.float8_e4m3fn | ||
| 363 | + ) | ||
| 364 | + | ||
| 365 | + | ||
| 366 | + | ||
| 367 | + | ||
| 368 | + | ||
| 369 | + | ||
| 370 | +if __name__ == "__main__": | ||
| 371 | + run_tests() | ||
| @@ -0,0 +1,362 @@ | |||
| 1 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||
| 2 | + | ||
| 3 | +# -*- coding: utf-8 -*- | ||
| 4 | +"""L3 (shape-equivalence end-to-end) Qwen3-MoE training test on NPU. | ||
| 5 | + | ||
| 6 | +Standalone script — deliberately exposes no ``test_*`` callables so a default | ||
| 7 | +``pytest`` sweep of the directory does not pick up a multi-minute training run. | ||
| 8 | +Run directly on A5: | ||
| 9 | + | ||
| 10 | + python test/npu/prototype/moe_training/test_blockwise_fp8_moe_training_equivalence.py | ||
| 11 | + python ... --steps 200 --tier 1 # force the one-shot grouped kernels | ||
| 12 | + | ||
| 13 | +Spec (``blockwise_fp8_analysis.md`` §8.5 "L3 用例(Qwen3 形状全流程)"): | ||
| 14 | + | ||
| 15 | +* torchtitan-style ``MoE`` (fused ``w1/w2/w3`` Parameters), random init, no | ||
| 16 | + checkpoint, Qwen3-30B-A3B hyper-parameters: | ||
| 17 | + dim=2048 / moe_intermediate=768 / E=128 / top_k=8 / GQA 32:4 / | ||
| 18 | + norm_topk_prob=True / head_dim=128 / rms_eps=1e-6 / rope_theta=1e6. | ||
| 19 | +* ``batch*seq = 32768`` tokens (doc: >= 32k so 128-row padding is negligible): | ||
| 20 | + 262144 routed rows, ~2048 rows per expert. | ||
| 21 | +* Two *identically initialised* 2-layer decoders: reference runs every expert | ||
| 22 | + GEMM in bf16 (per-expert ``F.linear``), the FP8 model routes them through | ||
| 23 | + the blockwise-FP8 grouped path. Everything else (attention, router, norms, | ||
| 24 | + embeddings) is shared bf16/fp32 code so the only difference under test is | ||
| 25 | + the expert GEMM backend. | ||
| 26 | +* AdamW, fixed lr/seed, 8 synthetic batches cycled for ``--steps`` (200). | ||
| 27 | + | ||
| 28 | +Assertions (doc §8.5 L3 row): | ||
| 29 | + * first-step loss diff (absolute) < 1e-3 | ||
| 30 | + * last-step loss diff (relative) < 2% | ||
| 31 | + * loss decreases for both runs | ||
| 32 | + * no NaN/Inf in any loss or gradient | ||
| 33 | + * ``tokens_per_expert``: layer-0 step-0 identical (same weights + inputs -> | ||
| 34 | + same routing); final step same distribution (load-vector cosine >= 0.995) | ||
| 35 | +""" | ||
| 36 | +import argparse | ||
| 37 | +import json | ||
| 38 | +import math | ||
| 39 | +import sys | ||
| 40 | + | ||
| 41 | +import torch | ||
| 42 | +import torch.nn as nn | ||
| 43 | +import torch.nn.functional as F | ||
| 44 | +import torch_npu # noqa: F401 | ||
| 45 | + | ||
| 46 | +from _blockwise_test_utils import ( | ||
| 47 | + _fp8_experts, | ||
| 48 | + _load_stats, | ||
| 49 | + _permute, | ||
| 50 | + _ref_experts, | ||
| 51 | + _unpermute, | ||
| 52 | +) | ||
| 53 | + | ||
| 54 | +# ---------------------------------------------------------------- Qwen3-30B-A3B | ||
| 55 | +DIM = 2048 | ||
| 56 | +INTER = 768 | ||
| 57 | +NUM_EXPERTS = 128 | ||
| 58 | +TOP_K = 8 | ||
| 59 | +NUM_HEADS = 32 | ||
| 60 | +NUM_KV_HEADS = 4 | ||
| 61 | +HEAD_DIM = 128 # Qwen3-30B-A3B: q/kv widths follow head_dim, not DIM/NUM_HEADS | ||
| 62 | +RMS_EPS = 1e-6 | ||
| 63 | +ROPE_THETA = 1_000_000.0 | ||
| 64 | +VOCAB = 8192 # reduced from 151936: equivalence needs MoE shapes, not the vocab | ||
| 65 | +NUM_LAYERS = 2 | ||
| 66 | +INIT_STD = 0.02 | ||
| 67 | + | ||
| 68 | +NUM_BATCHES = 8 | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +# ------------------------------------------------------------- model blocks | ||
| 72 | +def _rope_cache(seq, device): | ||
| 73 | + inv = 1.0 / ( | ||
| 74 | + ROPE_THETA | ||
| 75 | + ** (torch.arange(0, HEAD_DIM, 2, device=device, dtype=torch.float32) / HEAD_DIM) | ||
| 76 | + ) | ||
| 77 | + t = torch.arange(seq, device=device, dtype=torch.float32) | ||
| 78 | + freqs = torch.outer(t, inv) | ||
| 79 | + emb = torch.cat((freqs, freqs), dim=-1) | ||
| 80 | + return emb.cos(), emb.sin() | ||
| 81 | + | ||
| 82 | + | ||
| 83 | +def _rotate_half(x): | ||
| 84 | + x1, x2 = x.chunk(2, dim=-1) | ||
| 85 | + return torch.cat((-x2, x1), dim=-1) | ||
| 86 | + | ||
| 87 | + | ||
| 88 | +class RMSNorm(nn.Module): | ||
| 89 | + def __init__(self, dim, eps=RMS_EPS): | ||
| 90 | + super().__init__() | ||
| 91 | + self.weight = nn.Parameter(torch.ones(dim)) | ||
| 92 | + self.eps = eps | ||
| 93 | + | ||
| 94 | + def forward(self, x): | ||
| 95 | + dtype = x.dtype | ||
| 96 | + x = x.float() | ||
| 97 | + x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) | ||
| 98 | + return (self.weight.float() * x).to(dtype) | ||
| 99 | + | ||
| 100 | + | ||
| 101 | +class Attention(nn.Module): | ||
| 102 | + """GQA 32:4 with per-head q/k RMSNorm and RoPE (HF rotate_half style).""" | ||
| 103 | + | ||
| 104 | + def __init__(self): | ||
| 105 | + super().__init__() | ||
| 106 | + self.q_proj = nn.Linear(DIM, NUM_HEADS * HEAD_DIM, bias=False) | ||
| 107 | + self.k_proj = nn.Linear(DIM, NUM_KV_HEADS * HEAD_DIM, bias=False) | ||
| 108 | + self.v_proj = nn.Linear(DIM, NUM_KV_HEADS * HEAD_DIM, bias=False) | ||
| 109 | + self.o_proj = nn.Linear(NUM_HEADS * HEAD_DIM, DIM, bias=False) | ||
| 110 | + self.q_norm = RMSNorm(HEAD_DIM) | ||
| 111 | + self.k_norm = RMSNorm(HEAD_DIM) | ||
| 112 | + self.n_rep = NUM_HEADS // NUM_KV_HEADS | ||
| 113 | + | ||
| 114 | + def forward(self, x, cos, sin): | ||
| 115 | + bsz, seq, _ = x.shape | ||
| 116 | + q = self.q_proj(x).view(bsz, seq, NUM_HEADS, HEAD_DIM).transpose(1, 2) | ||
| 117 | + k = self.k_proj(x).view(bsz, seq, NUM_KV_HEADS, HEAD_DIM).transpose(1, 2) | ||
| 118 | + v = self.v_proj(x).view(bsz, seq, NUM_KV_HEADS, HEAD_DIM).transpose(1, 2) | ||
| 119 | + q = self.q_norm(q) | ||
| 120 | + k = self.k_norm(k) | ||
| 121 | + cos, sin = cos.to(q.dtype), sin.to(q.dtype) | ||
| 122 | + q = q * cos + _rotate_half(q) * sin | ||
| 123 | + k = k * cos + _rotate_half(k) * sin | ||
| 124 | + k = k.repeat_interleave(self.n_rep, dim=1) | ||
| 125 | + v = v.repeat_interleave(self.n_rep, dim=1) | ||
| 126 | + scores = (q @ k.transpose(-2, -1)) * (HEAD_DIM**-0.5) | ||
| 127 | + scores = scores.float() | ||
| 128 | + mask = torch.triu( | ||
| 129 | + torch.full((seq, seq), float("-inf"), device=x.device, dtype=torch.float32), | ||
| 130 | + diagonal=1, | ||
| 131 | + ) | ||
| 132 | + probs = torch.softmax(scores + mask, dim=-1).to(v.dtype) | ||
| 133 | + y = (probs @ v).transpose(1, 2).reshape(bsz, seq, NUM_HEADS * HEAD_DIM) | ||
| 134 | + return self.o_proj(y) | ||
| 135 | + | ||
| 136 | + | ||
| 137 | +class MoE(nn.Module): | ||
| 138 | + """torchtitan-style MoE: fused w1/w2/w3 Parameters, token-choice top-k.""" | ||
| 139 | + | ||
| 140 | + def __init__(self, use_fp8): | ||
| 141 | + super().__init__() | ||
| 142 | + self.router = nn.Parameter(torch.zeros(NUM_EXPERTS, DIM)) | ||
| 143 | + self.w1 = nn.Parameter(torch.empty(NUM_EXPERTS, INTER, DIM)) | ||
| 144 | + self.w2 = nn.Parameter(torch.empty(NUM_EXPERTS, DIM, INTER)) | ||
| 145 | + self.w3 = nn.Parameter(torch.empty(NUM_EXPERTS, INTER, DIM)) | ||
| 146 | + self.use_fp8 = use_fp8 | ||
| 147 | + self.last_counts = None | ||
| 148 | + | ||
| 149 | + def forward(self, x): | ||
| 150 | + bsz, seq, dim = x.shape | ||
| 151 | + xf = x.reshape(-1, dim) | ||
| 152 | + probs = torch.softmax(F.linear(xf, self.router).float(), dim=-1) | ||
| 153 | + topv, topi = probs.topk(TOP_K, dim=-1) | ||
| 154 | + topv = (topv / topv.sum(dim=-1, keepdim=True)).to(xf.dtype) # norm_topk_prob | ||
| 155 | + xs, ss, counts, token_ids = _permute(xf, topv, topi, NUM_EXPERTS) | ||
| 156 | + self.last_counts = counts.detach() | ||
| 157 | + if self.use_fp8: | ||
| 158 | + # autocast does not touch custom calls: cast fp32 master weights. | ||
| 159 | + dt = xs.dtype | ||
| 160 | + rows = _fp8_experts( | ||
| 161 | + xs, ss, counts, self.w1.to(dt), self.w2.to(dt), self.w3.to(dt) | ||
| 162 | + ) | ||
| 163 | + else: | ||
| 164 | + rows = _ref_experts(xs, ss, counts, self.w1, self.w2, self.w3) | ||
| 165 | + return _unpermute(rows, token_ids, xf.shape[0]).reshape(bsz, seq, dim) | ||
| 166 | + | ||
| 167 | + | ||
| 168 | +class DecoderLayer(nn.Module): | ||
| 169 | + def __init__(self, use_fp8): | ||
| 170 | + super().__init__() | ||
| 171 | + self.input_layernorm = RMSNorm(DIM) | ||
| 172 | + self.post_attention_layernorm = RMSNorm(DIM) | ||
| 173 | + self.self_attn = Attention() | ||
| 174 | + self.moe = MoE(use_fp8) | ||
| 175 | + | ||
| 176 | + def forward(self, x, cos, sin): | ||
| 177 | + x = x + self.self_attn(self.input_layernorm(x), cos, sin) | ||
| 178 | + x = x + self.moe(self.post_attention_layernorm(x)) | ||
| 179 | + return x | ||
| 180 | + | ||
| 181 | + | ||
| 182 | +class Qwen3MiniMoe(nn.Module): | ||
| 183 | + def __init__(self, seq, use_fp8): | ||
| 184 | + super().__init__() | ||
| 185 | + self.embed_tokens = nn.Embedding(VOCAB, DIM) | ||
| 186 | + self.layers = nn.ModuleList(DecoderLayer(use_fp8) for _ in range(NUM_LAYERS)) | ||
| 187 | + self.norm = RMSNorm(DIM) | ||
| 188 | + self.lm_head = nn.Linear(DIM, VOCAB, bias=False) | ||
| 189 | + cos, sin = _rope_cache(seq, torch.device("cpu")) | ||
| 190 | + self.register_buffer("cos", cos, persistent=False) | ||
| 191 | + self.register_buffer("sin", sin, persistent=False) | ||
| 192 | + | ||
| 193 | + def forward(self, ids): | ||
| 194 | + x = self.embed_tokens(ids) | ||
| 195 | + for layer in self.layers: | ||
| 196 | + x = layer(x, self.cos, self.sin) | ||
| 197 | + return self.lm_head(self.norm(x)) | ||
| 198 | + | ||
| 199 | + | ||
| 200 | +def _init_weights(module): | ||
| 201 | + if isinstance(module, (nn.Linear, nn.Embedding)): | ||
| 202 | + nn.init.normal_(module.weight, std=INIT_STD) | ||
| 203 | + elif isinstance(module, MoE): | ||
| 204 | + nn.init.normal_(module.router, std=INIT_STD) | ||
| 205 | + for w in (module.w1, module.w2, module.w3): | ||
| 206 | + nn.init.normal_(w, std=INIT_STD) | ||
| 207 | + | ||
| 208 | + | ||
| 209 | +# ------------------------------------------------------------------ training | ||
| 210 | +def _make_batches(batch, seq, seed, device): | ||
| 211 | + g = torch.Generator(device="cpu").manual_seed(seed + 1000) | ||
| 212 | + ids = torch.randint(0, VOCAB, (NUM_BATCHES, batch, seq), generator=g) | ||
| 213 | + return ids.to(device) | ||
| 214 | + | ||
| 215 | + | ||
| 216 | +def _train(model, batches, steps, lr, tag, log_every=10): | ||
| 217 | + device_type = torch._C._get_privateuse1_backend_name() | ||
| 218 | + opt = torch.optim.AdamW( | ||
| 219 | + model.parameters(), lr=lr, betas=(0.9, 0.95), eps=1e-8, weight_decay=0.0 | ||
| 220 | + ) | ||
| 221 | + losses = [] | ||
| 222 | + counts_snap = {} | ||
| 223 | + for step in range(steps): | ||
| 224 | + ids = batches[step % len(batches)] | ||
| 225 | + with torch.autocast(device_type, dtype=torch.bfloat16): | ||
| 226 | + logits = model(ids) | ||
| 227 | + loss = F.cross_entropy( | ||
| 228 | + logits[:, :-1].reshape(-1, logits.shape[-1]).float(), | ||
| 229 | + ids[:, 1:].reshape(-1), | ||
| 230 | + ) | ||
| 231 | + loss_val = loss.item() | ||
| 232 | + if not math.isfinite(loss_val): | ||
| 233 | + raise RuntimeError(f"[{tag}] step {step}: non-finite loss {loss_val}") | ||
| 234 | + opt.zero_grad(set_to_none=True) | ||
| 235 | + loss.backward() | ||
| 236 | + for name, p in model.named_parameters(): | ||
| 237 | + if p.grad is not None and not bool(torch.isfinite(p.grad).all()): | ||
| 238 | + raise RuntimeError(f"[{tag}] step {step}: non-finite grad in {name}") | ||
| 239 | + opt.step() | ||
| 240 | + losses.append(loss_val) | ||
| 241 | + if step == 0 or step == steps - 1: | ||
| 242 | + counts_snap[step] = [l.moe.last_counts.clone() for l in model.layers] | ||
| 243 | + if step % log_every == 0 or step == steps - 1: | ||
| 244 | + print(f"[{tag}] step {step:4d}/{steps} loss {loss_val:.6f}", flush=True) | ||
| 245 | + return losses, counts_snap | ||
| 246 | + | ||
| 247 | + | ||
| 248 | +def main(): | ||
| 249 | + parser = argparse.ArgumentParser(description=__doc__) | ||
| 250 | + parser.add_argument("--steps", type=int, default=200) | ||
| 251 | + parser.add_argument("--batch", type=int, default=128) | ||
| 252 | + parser.add_argument("--seq", type=int, default=256) | ||
| 253 | + parser.add_argument("--lr", type=float, default=1e-5) | ||
| 254 | + parser.add_argument("--seed", type=int, default=0) | ||
| 255 | + parser.add_argument("--tier", choices=["auto", "1", "2"], default="auto") | ||
| 256 | + args = parser.parse_args() | ||
| 257 | + | ||
| 258 | + device = torch.device(torch._C._get_privateuse1_backend_name()) | ||
| 259 | + import torchao_ascend.ops.npu.fp8_block_ops as fp8_block_ops_mod | ||
| 260 | + if args.tier == "1": | ||
| 261 | + fp8_block_ops_mod.HAS_GROUPED_BLOCK_QUANT = True | ||
| 262 | + elif args.tier == "2": | ||
| 263 | + fp8_block_ops_mod.HAS_GROUPED_BLOCK_QUANT = False | ||
| 264 | + # auto: leave the probe as-is | ||
| 265 | + | ||
| 266 | + from torchao_ascend.patches.torchao.prototype.moe_training.blockwise_fp8 import ( | ||
| 267 | + grouped_mm_backend as patch_mod, | ||
| 268 | + ) | ||
| 269 | + | ||
| 270 | + patch_mod.apply() | ||
| 271 | + | ||
| 272 | + tokens = args.batch * args.seq | ||
| 273 | + print( | ||
| 274 | + f"L3 Qwen3-MoE: layers={NUM_LAYERS} batch={args.batch} seq={args.seq} " | ||
| 275 | + f"({tokens} tokens/step, {tokens * TOP_K} routed rows) " | ||
| 276 | + f"dim={DIM} inter={INTER} E={NUM_EXPERTS} top_k={TOP_K} " | ||
| 277 | + f"tier={args.tier or 'AUTO'} steps={args.steps} lr={args.lr} seed={args.seed}", | ||
| 278 | + flush=True, | ||
| 279 | + ) | ||
| 280 | + | ||
| 281 | + batches = _make_batches(args.batch, args.seq, args.seed, device) | ||
| 282 | + torch.manual_seed(args.seed) | ||
| 283 | + ref = Qwen3MiniMoe(args.seq, use_fp8=False) | ||
| 284 | + ref.apply(_init_weights) | ||
| 285 | + ref = ref.to(device) | ||
| 286 | + torch.manual_seed(args.seed) | ||
| 287 | + fp8m = Qwen3MiniMoe(args.seq, use_fp8=True) | ||
| 288 | + fp8m.apply(_init_weights) | ||
| 289 | + fp8m = fp8m.to(device) | ||
| 290 | + for (na, pa), (nb, pb) in zip(ref.named_parameters(), fp8m.named_parameters()): | ||
| 291 | + assert na == nb and torch.equal(pa.data, pb.data), f"init mismatch: {na} vs {nb}" | ||
| 292 | + print("identical init verified", flush=True) | ||
| 293 | + | ||
| 294 | + losses_ref, counts_ref = _train(ref, batches, args.steps, args.lr, "bf16") | ||
| 295 | + del ref | ||
| 296 | + if hasattr(torch, "npu") and hasattr(torch.npu, "empty_cache"): | ||
| 297 | + torch.npu.empty_cache() | ||
| 298 | + losses_fp8, counts_fp8 = _train(fp8m, batches, args.steps, args.lr, "fp8 ") | ||
| 299 | + | ||
| 300 | + summary = { | ||
| 301 | + "tokens_per_step": tokens, | ||
| 302 | + "routed_rows_per_step": tokens * TOP_K, | ||
| 303 | + "steps": args.steps, | ||
| 304 | + "tier": args.tier, | ||
| 305 | + "loss_bf16_first": losses_ref[0], | ||
| 306 | + "loss_fp8_first": losses_fp8[0], | ||
| 307 | + "loss_bf16_last": losses_ref[-1], | ||
| 308 | + "loss_fp8_last": losses_fp8[-1], | ||
| 309 | + } | ||
| 310 | + | ||
| 311 | + # 1) no NaN/Inf already enforced per-step inside _train. | ||
| 312 | + # 2) first-step absolute loss diff < 1e-3. | ||
| 313 | + d0 = abs(losses_fp8[0] - losses_ref[0]) | ||
| 314 | + summary["first_step_abs_diff"] = d0 | ||
| 315 | + assert d0 < 1e-3, f"first-step loss diff {d0:.6g} >= 1e-3" | ||
| 316 | + | ||
| 317 | + # 3) last-step relative diff < 2 %. | ||
| 318 | + rel = abs(losses_fp8[-1] - losses_ref[-1]) / max(abs(losses_ref[-1]), 1e-9) | ||
| 319 | + summary["last_step_rel_diff"] = rel | ||
| 320 | + assert rel < 0.02, f"last-step loss relative diff {rel:.4%} >= 2%" | ||
| 321 | + | ||
| 322 | + # 4) decreasing trend for both runs (disjoint halves so short smokes work). | ||
| 323 | + for tag, ls in (("bf16", losses_ref), ("fp8", losses_fp8)): | ||
| 324 | + half = max(len(ls) // 2, 1) | ||
| 325 | + head = sum(ls[:half]) / half | ||
| 326 | + tail = sum(ls[len(ls) - half :]) / half | ||
| 327 | + summary[f"{tag}_decrease"] = head - tail | ||
| 328 | + assert tail < head, f"[{tag}] loss did not decrease: {head:.6f} -> {tail:.6f}" | ||
| 329 | + | ||
| 330 | + # 5) tokens_per_expert: step-0 layer-0 must be identical; layer-1 may flip | ||
| 331 | + # a handful of near-tie tokens (fp8 noise on the block-0 output); the | ||
| 332 | + # final-step loads must stay the same distribution. | ||
| 333 | + for li in range(NUM_LAYERS): | ||
| 334 | + eq0 = torch.equal(counts_ref[0][li], counts_fp8[0][li]) | ||
| 335 | + s0 = _load_stats(counts_ref[0][li], counts_fp8[0][li]) | ||
| 336 | + sN = _load_stats(counts_ref[args.steps - 1][li], counts_fp8[args.steps - 1][li]) | ||
| 337 | + summary[f"layer{li}_step0_identical"] = eq0 | ||
| 338 | + summary[f"layer{li}_step0"] = s0 | ||
| 339 | + summary[f"layer{li}_final"] = sN | ||
| 340 | + if li == 0: | ||
| 341 | + assert eq0, "layer-0 step-0 routing must be identical" | ||
| 342 | + else: | ||
| 343 | + # Layer-1 routing is computed from a layer-0 output that already went | ||
| 344 | + # through FP8 experts, so near-tie tokens legitimately flip: measured | ||
| 345 | + # rel_l1 is ~2e-3 on A5/950DT (layer-0 stays bit-identical). The | ||
| 346 | + # per-expert flip cap scales with mean expert load: max_abs_diff is a | ||
| 347 | + # max over E buckets and too seed/kernel-noise sensitive to pin | ||
| 348 | + # absolutely (measured worst flip 14/2048 rows ~ 0.7% of mean load). | ||
| 349 | + mean_load = args.batch * args.seq * TOP_K / NUM_EXPERTS | ||
| 350 | + flip_cap = max(8, math.ceil(0.01 * mean_load)) | ||
| 351 | + assert s0["rel_l1"] <= 1e-2 and s0["max_abs_diff"] <= flip_cap, ( | ||
| 352 | + f"layer-1 step-0 routing drifted too far: {s0} (cap {flip_cap})" | ||
| 353 | + ) | ||
| 354 | + assert sN["cosine"] >= 0.995, f"layer-{li} final load cosine {sN['cosine']:.6f} < 0.995" | ||
| 355 | + | ||
| 356 | + summary["status"] = "PASS" | ||
| 357 | + print(json.dumps(summary, indent=2), flush=True) | ||
| 358 | + print("L3 PASS", flush=True) | ||
| 359 | + | ||
| 360 | + | ||
| 361 | +if __name__ == "__main__": | ||
| 362 | + main() | ||
| @@ -0,0 +1,154 @@ | |||
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 2 | +# All rights reserved. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD 3-Clause license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | +# | ||
| 7 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||
| 8 | + | ||
| 9 | +# -*- coding: utf-8 -*- | ||
| 10 | +"""NPU port of upstream ``torchao/test/prototype/moe_training/test_fp8_blockwise_grouped_mm.py``. | ||
| 11 | + | ||
| 12 | +The upstream suite (CUDA FP8 GPUs) checks the EMULATED simulated path against | ||
| 13 | +the ``torch._grouped_mm`` bf16 reference (fwd >= 27.0 / bwd >= 26.0). This port | ||
| 14 | +keeps the same shapes, group offsets, bf16 reference and error thresholds, and | ||
| 15 | +swaps the subject to an explicit kernel preference — KernelPreference.NPU on | ||
| 16 | +NPU (the patched selector's explicit gate) and KernelPreference.AUTO on other | ||
| 17 | +FP8-capable accelerators (upstream semantics), so the parity being asserted is exactly | ||
| 18 | +"NPU blockwise-FP8 backend matches the upstream bf16 grouped-MM reference". | ||
| 19 | + | ||
| 20 | +Adaptations: | ||
| 21 | + | ||
| 22 | +* the upstream EMULATED path requires triton quantization kernels and is not | ||
| 23 | + runnable on a triton-less NPU setup; the NPU backend shares the same | ||
| 24 | + 1x128 / 128x128 block-quantization semantics, so the deviation from the bf16 | ||
| 25 | + reference is the same inherent fp8 quantization error and the upstream | ||
| 26 | + thresholds carry over unchanged; | ||
| 27 | +* the upstream ``torch.compile`` fullgraph case is not ported (NPU inductor | ||
| 28 | + support is limited); | ||
| 29 | +* the device is resolved through ``torch.accelerator`` instead of hardcoding | ||
| 30 | + ``"npu"`` (mirrors ``test_mxfp8_grouped_mm.py``), so the same suite also | ||
| 31 | + exercises the upstream AUTO path on other FP8-capable accelerators. | ||
| 32 | +""" | ||
| 33 | +import pytest | ||
| 34 | +import torch | ||
| 35 | +try: | ||
| 36 | + import torch_npu # noqa: F401 # torch.accelerator reports "npu" via its hook | ||
| 37 | +except ImportError: # non-NPU platforms: the module-level skip below decides | ||
| 38 | + torch_npu = None | ||
| 39 | + | ||
| 40 | +from torchao.utils import is_MI300, is_MI350, is_sm_at_least_90 | ||
| 41 | + | ||
| 42 | +# Cross-platform device resolution: on NPU the suite passes KernelPreference.NPU | ||
| 43 | +# explicitly (the patched selector's gate); other accelerators keep upstream | ||
| 44 | +# AUTO behaviour. | ||
| 45 | +DEVICE = ( | ||
| 46 | + torch.accelerator.current_accelerator().type | ||
| 47 | + if torch.accelerator.is_available() | ||
| 48 | + else "cpu" | ||
| 49 | +) | ||
| 50 | + | ||
| 51 | +if DEVICE != "npu" and not ( | ||
| 52 | + torch.cuda.is_available() | ||
| 53 | + and (is_sm_at_least_90() or is_MI300() or is_MI350()) | ||
| 54 | +): | ||
| 55 | + pytest.skip( | ||
| 56 | + "Requires NPU or FP8-capable GPU (CUDA SM90+, MI300, or MI350)", | ||
| 57 | + allow_module_level=True, | ||
| 58 | + ) | ||
| 59 | +if DEVICE != "npu": | ||
| 60 | + pytest.importorskip("triton", reason="Triton required on CUDA") | ||
| 61 | + | ||
| 62 | +import torchao_ascend # noqa: F401,E402 (installs the NPU backend patches) | ||
| 63 | + | ||
| 64 | +from torchao.prototype.moe_training.blockwise_fp8.grouped_mm import ( # noqa: E402 | ||
| 65 | + _to_fp8_blockwise_then_scaled_grouped_mm, | ||
| 66 | +) | ||
| 67 | +from torchao.quantization.quantize_.common import KernelPreference # noqa: E402 | ||
| 68 | +from torchao.quantization.utils import compute_error # noqa: E402 | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def _make_column_major_weight_t(E: int, N: int, K: int) -> torch.Tensor: | ||
| 72 | + weight = torch.randn(E, N, K, dtype=torch.bfloat16, device=DEVICE) | ||
| 73 | + return weight.contiguous().transpose(-2, -1) | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +@pytest.mark.parametrize( | ||
| 77 | + "offs,pad_token_groups_for_grouped_mm", | ||
| 78 | + [ | ||
| 79 | + (torch.tensor([256, 512], dtype=torch.int32), False), | ||
| 80 | + (torch.tensor([129, 384, 500], dtype=torch.int32), True), | ||
| 81 | + ], | ||
| 82 | +) | ||
| 83 | +def test_fp8_blockwise_grouped_mm_fwd_bwd(offs, pad_token_groups_for_grouped_mm): | ||
| 84 | + torch.manual_seed(0) | ||
| 85 | + offs = offs.to(DEVICE) | ||
| 86 | + E = offs.numel() | ||
| 87 | + M = int(offs[-1].item()) | ||
| 88 | + K, N = 256, 256 | ||
| 89 | + A = torch.randn(M, K, dtype=torch.bfloat16, device=DEVICE, requires_grad=True) | ||
| 90 | + B_t = _make_column_major_weight_t(E, N, K).requires_grad_(True) | ||
| 91 | + | ||
| 92 | + A_ref = A.detach().clone().requires_grad_(True) | ||
| 93 | + B_t_ref = B_t.detach().clone().requires_grad_(True) | ||
| 94 | + | ||
| 95 | + # Explicit kernel preference: KernelPreference.NPU on NPU (the patched | ||
| 96 | + # selector's gate); AUTO elsewhere keeps upstream semantics. | ||
| 97 | + out = _to_fp8_blockwise_then_scaled_grouped_mm( | ||
| 98 | + A, | ||
| 99 | + B_t, | ||
| 100 | + offs, | ||
| 101 | + pad_token_groups_for_grouped_mm=pad_token_groups_for_grouped_mm, | ||
| 102 | + kernel_preference=( | ||
| 103 | + KernelPreference.NPU if DEVICE == "npu" else KernelPreference.AUTO | ||
| 104 | + ), | ||
| 105 | + ) | ||
🟡 Medium Priority 变更行:本文件模块 docstring(第 15–17 行「swaps the subject to the AUTO path — on NPU tensors the patched selector dispatches to the NPU backend」、第 27–30 行「the device is resolved through torch.accelerator ... so the same suite also exercises the upstream AUTO path on other FP8-capable accelerators」)与被测代码第 92–98 行 建议:让 kernel_preference 随 DEVICE 选择(NPU 走 NPU、其它 FP8 加速器走 AUTO),或删除 docstring 中「swaps the subject to the AUTO path / 同一套件覆盖其它加速器 AUTO」的表述并把 CUDA 从模块级放行条件里去掉,使文档与实现一致。 ![]() ![]() Incorrect? | |||
| 106 | + ref = torch._grouped_mm(A_ref, B_t_ref, offs=offs, out_dtype=torch.bfloat16) | ||
| 107 | + | ||
| 108 | + assert out.shape == ref.shape | ||
| 109 | + assert out.dtype == torch.bfloat16 | ||
| 110 | + assert compute_error(ref, out) >= 27.0 | ||
| 111 | + | ||
| 112 | + out.float().square().mean().backward() | ||
| 113 | + ref.float().square().mean().backward() | ||
| 114 | + | ||
| 115 | + assert compute_error(A_ref.grad, A.grad) >= 26.0 | ||
| 116 | + assert compute_error(B_t_ref.grad, B_t.grad) >= 26.0 | ||
| 117 | + | ||
| 118 | + | ||
| 119 | +@pytest.mark.skipif(DEVICE != "npu", reason="NPU backend selection contract") | ||
| 120 | +def test_backend_selection_contract(): | ||
| 121 | + """Only the explicit ``KernelPreference.NPU`` dispatches to the NPU | ||
| 122 | + backend; AUTO/EMULATED flow past to the upstream selector (mxfp8-patch | ||
| 123 | + convention).""" | ||
| 124 | + from torchao.prototype.moe_training.blockwise_fp8.grouped_mm_backend import ( | ||
| 125 | + _select_fp8_blockwise_grouped_mm_backend, | ||
| 126 | + ) | ||
| 127 | + | ||
| 128 | + A = torch.randn(256, 256, dtype=torch.bfloat16, device=DEVICE) | ||
| 129 | + offs = torch.tensor([256], dtype=torch.int32, device=DEVICE) | ||
| 130 | + | ||
| 131 | + backend = _select_fp8_blockwise_grouped_mm_backend( | ||
| 132 | + KernelPreference.NPU, A, torch.bfloat16, 128, offs | ||
| 133 | + ) | ||
| 134 | + assert getattr(backend, "kind", None) == "npu" | ||
| 135 | + | ||
| 136 | + # AUTO keeps the upstream semantics (CUDA DeepGEMM / emulation) — it does | ||
| 137 | + # NOT auto-probe NPU even on NPU tensors (mxfp8-patch convention). | ||
| 138 | + backend = _select_fp8_blockwise_grouped_mm_backend( | ||
| 139 | + KernelPreference.AUTO, A, torch.bfloat16, 128, offs | ||
| 140 | + ) | ||
| 141 | + assert getattr(backend, "kind", None) != "npu" | ||
| 142 | + | ||
| 143 | + # EMULATED is always served by the upstream simulated backend. | ||
| 144 | + backend = _select_fp8_blockwise_grouped_mm_backend( | ||
| 145 | + KernelPreference.EMULATED, A, torch.bfloat16, 128, offs | ||
| 146 | + ) | ||
| 147 | + assert getattr(backend, "kind", None) != "npu" | ||
| 148 | + | ||
| 149 | + # KernelPreference.NPU on non-NPU tensors raises (device validation). | ||
| 150 | + A_cpu = torch.randn(256, 256, dtype=torch.bfloat16) | ||
| 151 | + with pytest.raises(ValueError): | ||
| 152 | + _select_fp8_blockwise_grouped_mm_backend( | ||
| 153 | + KernelPreference.NPU, A_cpu, torch.bfloat16, 128, offs.cpu() | ||
| 154 | + ) | ||
| @@ -15,6 +15,16 @@ per-op modules — ``mx_ops`` (shared wrappers), ``mx_dynamic_quant`` and | |||
| 15 | shared by the training features; framework op registries (planned consumer: | 15 | shared by the training features; framework op registries (planned consumer: |
| 16 | FSDPTurbo) bind these same functions. | 16 | FSDPTurbo) bind these same functions. |
| 17 | """ | 17 | """ |
| 18 | +from .fp8_block_ops import ( | ||
| 19 | + GROUP_SIZES, | ||
| 20 | + HAS_GROUPED_BLOCK_QUANT, | ||
| 21 | + LHS_BLOCK, | ||
| 22 | + RHS_BLOCK, | ||
| 23 | + block_quant, | ||
| 24 | + block_quant_matmul, | ||
| 25 | + grouped_block_quant, | ||
| 26 | + grouped_block_quant_matmul, | ||
| 27 | +) | ||
| 18 | from .hifloat8_ops import ( | 28 | from .hifloat8_ops import ( |
| 19 | hifloat8_dynamic_quant, | 29 | hifloat8_dynamic_quant, |
| 20 | hifloat8_grouped_matmul, | 30 | hifloat8_grouped_matmul, |
| @@ -42,12 +52,20 @@ from .mx_ops import ( | |||
| 42 | from . import mx_gemm # noqa: F401,E402 # import registers the "mx_addmm" NPU kernel | 52 | from . import mx_gemm # noqa: F401,E402 # import registers the "mx_addmm" NPU kernel |
| 43 | 53 | ||
| 44 | __all__ = [ | 54 | __all__ = [ |
| 55 | + "GROUP_SIZES", | ||
| 56 | + "HAS_GROUPED_BLOCK_QUANT", | ||
| 57 | + "LHS_BLOCK", | ||
| 58 | + "RHS_BLOCK", | ||
| 59 | + "block_quant", | ||
| 60 | + "block_quant_matmul", | ||
| 45 | "dynamic_mx_quant", | 61 | "dynamic_mx_quant", |
| 46 | "dynamic_mx_quant_with_dual_axis", | 62 | "dynamic_mx_quant_with_dual_axis", |
| 47 | "float4_e2m1fn_x2", | 63 | "float4_e2m1fn_x2", |
| 48 | "float8_e8m0fnu", | 64 | "float8_e8m0fnu", |
| 49 | "get_float4_dtype", | 65 | "get_float4_dtype", |
| 50 | "get_hifloat8_dtype", | 66 | "get_hifloat8_dtype", |
| 67 | + "grouped_block_quant", | ||
| 68 | + "grouped_block_quant_matmul", | ||
| 51 | "grouped_dynamic_mx_quant", | 69 | "grouped_dynamic_mx_quant", |
| 52 | "hifloat8", | 70 | "hifloat8", |
| 53 | "hifloat8_dynamic_quant", | 71 | "hifloat8_dynamic_quant", |
| @@ -0,0 +1,243 @@ | |||
| 1 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||
| 2 | + | ||
| 3 | +"""torchao_ascend.ops.npu.fp8_block_ops — Ascend blockwise-FP8 operators. | ||
| 4 | + | ||
| 5 | +Single call-site for the blockwise FP8 primitives used by training: | ||
| 6 | + | ||
| 7 | +* ``block_quant`` — ``npu_dynamic_block_quant`` (1x128 / 128x128) | ||
| 8 | +* ``block_quant_matmul`` — ``npu_quant_matmul`` group-block GEMM | ||
| 9 | +* ``grouped_block_quant`` — grouped form (Tier 1, per-expert fallback) | ||
| 10 | +* ``grouped_block_quant_matmul``— grouped GEMM (Tier 1, per-expert fallback) | ||
| 11 | + | ||
| 12 | +Tier 1 uses the one-shot grouped APIs (``npu_grouped_dynamic_block_quant`` / | ||
| 13 | +``npu_grouped_matmul``) which may not exist in every torch_npu build; the | ||
| 14 | +per-expert loop below reuses the same dense kernels, so numerics stay | ||
| 15 | +identical and only the launch count differs (E launches). | ||
| 16 | + | ||
| 17 | +Tier 1 (the one-shot grouped kernels) is selected automatically when present | ||
| 18 | +in the torch_npu build — reproducibility-verified on Ascend950DT / CANN | ||
| 19 | +9.3.0-1028 via 3-round interleaved sampling (Tier1 26.7s mean, spread 0.1s, | ||
| 20 | +vs bf16 30.9s / Tier2 30.8s on example 100-step training; GEMM 6.8x, grouped | ||
| 21 | +quant 15x isolated) — else falls back to Tier 2. The L1 contract test pins | ||
| 22 | +both paths by patching ``HAS_GROUPED_BLOCK_QUANT``. | ||
| 23 | +""" | ||
| 24 | +from __future__ import annotations | ||
| 25 | + | ||
| 26 | +import torch | ||
| 27 | +import torch_npu | ||
| 28 | + | ||
| 29 | +__all__ = [ | ||
| 30 | + "GROUP_SIZES", | ||
| 31 | + "HAS_GROUPED_BLOCK_QUANT", | ||
| 32 | + "LHS_BLOCK", | ||
| 33 | + "RHS_BLOCK", | ||
| 34 | + "block_quant", | ||
| 35 | + "block_quant_matmul", | ||
| 36 | + "grouped_block_quant", | ||
| 37 | + "grouped_block_quant_matmul", | ||
| 38 | +] | ||
| 39 | + | ||
| 40 | +# aclnnQuantMatmulV5 group-block tile sizes. | ||
| 41 | +LHS_BLOCK = (1, 128) | ||
| 42 | +RHS_BLOCK = (128, 128) | ||
| 43 | +GROUP_SIZES = [0, 128, 128] | ||
| 44 | + | ||
| 45 | +# Tier-1 capability probe. ``npu_grouped_dynamic_block_quant`` is a newer | ||
| 46 | +# entry point and may be absent from the installed torch_npu build. | ||
| 47 | +HAS_GROUPED_BLOCK_QUANT = hasattr(torch_npu, "npu_grouped_dynamic_block_quant") | ||
| 48 | +# AUTO: Tier 1 when the fused kernels are present — reproducibility-verified | ||
| 49 | +# on Ascend950DT / CANN 9.3.0-1028: 3-round interleaved sampling (example 100 | ||
| 50 | +# steps x {bf16, Tier1, Tier2}) gave Tier1 26.7s mean (spread 0.1s) vs bf16 | ||
| 51 | +# 30.9s / Tier2 30.8s — 13.5% faster than the bf16 baseline at the example | ||
| 52 | +# shapes (E=8, M_e~512), with the bf16 control run disproving the earlier | ||
| 53 | +# one-off 53.4s anomaly (same-round bench bf16 column also 17x-off = | ||
| 54 | +# environmental event). GEMM 6.8x, grouped quant 15x in isolation; numerics | ||
| 55 | +# equivalent T0 + training-level. Falls back to Tier 2 when the fused | ||
| 56 | +# kernels are absent from the build. Tier tests pin both paths by patching | ||
| 57 | +# HAS_GROUPED_BLOCK_QUANT. | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +def block_quant( | ||
| 61 | + hp: torch.Tensor, | ||
| 62 | + *, | ||
| 63 | + dst_type: torch.dtype, | ||
| 64 | + row_block_size: int, | ||
| 65 | + col_block_size: int, | ||
| 66 | +) -> tuple[torch.Tensor, torch.Tensor]: | ||
| 67 | + """Dynamic block quantization; returns ``(qdata, scale)``. | ||
| 68 | + | ||
| 69 | + ``row_block_size=1, col_block_size=128`` for activations (1x128) and | ||
| 70 | + ``128, 128`` for weights. | ||
| 71 | + """ | ||
| 72 | + return torch_npu.npu_dynamic_block_quant( | ||
| 73 | + hp, | ||
| 74 | + dst_type=dst_type, | ||
| 75 | + row_block_size=row_block_size, | ||
| 76 | + col_block_size=col_block_size, | ||
| 77 | + ) | ||
| 78 | + | ||
| 79 | + | ||
| 80 | +def block_quant_matmul( | ||
| 81 | + x1: torch.Tensor, | ||
| 82 | + x2: torch.Tensor, | ||
| 83 | + scale: torch.Tensor, | ||
| 84 | + *, | ||
| 85 | + pertoken_scale: torch.Tensor, | ||
| 86 | + output_dtype: torch.dtype, | ||
| 87 | + bias: torch.Tensor | None = None, | ||
| 88 | +) -> torch.Tensor: | ||
| 89 | + """Group/block FP8 matmul (``aclnnQuantMatmulV5`` group-block mode). | ||
| 90 | + | ||
| 91 | + ``x1`` is the 1x128-quantized LHS, ``x2`` the 128x128-quantized RHS | ||
| 92 | + (contract dim first), ``scale``/``pertoken_scale`` their reciprocal scales. | ||
| 93 | + """ | ||
| 94 | + out = torch_npu.npu_quant_matmul( | ||
| 95 | + x1, | ||
| 96 | + x2, | ||
| 97 | + scale, | ||
| 98 | + pertoken_scale=pertoken_scale, | ||
| 99 | + output_dtype=output_dtype, | ||
| 100 | + group_sizes=list(GROUP_SIZES), | ||
| 101 | + ) | ||
| 102 | + if bias is not None: | ||
| 103 | + out = out + bias.to(device=out.device, dtype=out.dtype) | ||
| 104 | + return out | ||
| 105 | + | ||
| 106 | + | ||
| 107 | +def _group_slices(offs: torch.Tensor) -> list[tuple[int, int]]: | ||
| 108 | + """Cumulative end offsets (int32) -> per-group ``(start, end)`` pairs.""" | ||
| 109 | + ends = offs.tolist() | ||
| 110 | + starts = [0] + ends[:-1] | ||
| 111 | + return list(zip(starts, ends)) | ||
| 112 | + | ||
| 113 | + | ||
| 114 | +def _per_expert_grouped_quant( | ||
| 115 | + tensor: torch.Tensor, | ||
| 116 | + group_list: torch.Tensor, | ||
| 117 | + *, | ||
| 118 | + dst_type: torch.dtype, | ||
| 119 | + row_block_size: int, | ||
| 120 | + col_block_size: int, | ||
| 121 | +) -> tuple[torch.Tensor, torch.Tensor]: | ||
| 122 | + """Tier-2 grouped block quant: quantize each group slice separately. | ||
| 123 | + | ||
| 124 | + Returns ``(q, scale)`` concatenated along dim 0 (groups may have different | ||
| 125 | + first-dim lengths, e.g. ``(tokens_e, D)``). | ||
| 126 | + """ | ||
| 127 | + parts_q, parts_s = [], [] | ||
| 128 | + for start, end in _group_slices(group_list): | ||
| 129 | + size = end - start | ||
| 130 | + if size == 0: | ||
| 131 | + continue | ||
| 132 | + q, s = block_quant( | ||
| 133 | + tensor[start:end], | ||
| 134 | + dst_type=dst_type, | ||
| 135 | + row_block_size=row_block_size, | ||
| 136 | + col_block_size=col_block_size, | ||
| 137 | + ) | ||
| 138 | + parts_q.append(q) | ||
| 139 | + parts_s.append(s) | ||
| 140 | + device = tensor.device | ||
| 141 | + q_out = ( | ||
| 142 | + torch.cat(parts_q, dim=0) | ||
| 143 | + if parts_q | ||
| 144 | + else tensor.new_empty((0, *tensor.shape[1:]), dtype=dst_type) | ||
| 145 | + ) | ||
| 146 | + if parts_s: | ||
| 147 | + s_out = torch.cat(parts_s, dim=0) | ||
| 148 | + else: | ||
| 149 | + s_out = torch.empty( | ||
| 150 | + (0, tensor.shape[-1] // col_block_size), | ||
| 151 | + dtype=torch.float32, | ||
| 152 | + device=device, | ||
| 153 | + ) | ||
| 154 | + return q_out, s_out | ||
| 155 | + | ||
| 156 | + | ||
| 157 | +def grouped_block_quant( | ||
| 158 | + tensor: torch.Tensor, | ||
| 159 | + group_list: torch.Tensor, | ||
| 160 | + *, | ||
| 161 | + dst_type: torch.dtype, | ||
| 162 | + row_block_size: int, | ||
| 163 | + col_block_size: int, | ||
| 164 | +) -> tuple[torch.Tensor, torch.Tensor]: | ||
| 165 | + """Grouped block quantization over token groups (``group_list`` = cumsum). | ||
| 166 | + | ||
| 167 | + Numerics are identical across the fused/per-expert paths (SNR asserted by | ||
| 168 | + the L1 contract test); the fused kernel's scale layout differs (it appends | ||
| 169 | + per-group rows — asserted as ``s1.shape[0] == s2.shape[0] + len(ends)`` by | ||
| 170 | + the same test). | ||
| 171 | + """ | ||
| 172 | + if HAS_GROUPED_BLOCK_QUANT: | ||
| 173 | + return torch_npu.npu_grouped_dynamic_block_quant( | ||
| 174 | + tensor, | ||
| 175 | + group_list, | ||
| 176 | + dst_type=dst_type, | ||
| 177 | + row_block_size=row_block_size, | ||
| 178 | + col_block_size=col_block_size, | ||
| 179 | + ) | ||
🟡 Medium Priority
证据链:
失败模式:调用方按 修复方向:二选一——(a) Tier-1 分支把 padding 行 gather 掉,使 建议:让 Tier-1 返回值与 Tier-2 的公开形状对齐(去掉每组 padding 行),或在契约中显式声明两种布局并在 grouped_block_quant_matmul 中做行数校验,避免环境变量静默改变输出形状。 ![]() ![]() Incorrect? | |||
| 180 | + q, s = _per_expert_grouped_quant( | ||
| 181 | + tensor, | ||
| 182 | + group_list, | ||
| 183 | + dst_type=dst_type, | ||
| 184 | + row_block_size=row_block_size, | ||
| 185 | + col_block_size=col_block_size, | ||
| 186 | + ) | ||
| 187 | + return q, s | ||
| 188 | + | ||
| 189 | + | ||
| 190 | +def grouped_block_quant_matmul( | ||
| 191 | + a: torch.Tensor, | ||
| 192 | + b: torch.Tensor, | ||
| 193 | + a_s: torch.Tensor, | ||
| 194 | + b_s: torch.Tensor, | ||
| 195 | + offs: torch.Tensor, | ||
| 196 | + out_dtype: torch.dtype, | ||
| 197 | +) -> torch.Tensor: | ||
| 198 | + """Grouped block-scaled GEMM ``out = A @ B`` per expert group. | ||
| 199 | + | ||
| 200 | + ``a``: ``(M, K)`` fp8 row-major; ``b``: ``(E, K, N)`` fp8 (column-major | ||
| 201 | + accepted); ``a_s``: ``(M, K/128)``; ``b_s``: ``(E, K/128, N/128)``; | ||
| 202 | + ``offs``: int32 cumulative end offsets. | ||
| 203 | + | ||
| 204 | + The grouped kernel (aclnnGroupedMatmulV4 on CANN 9.2.0 / Ascend 950) | ||
| 205 | + accepts the per-expert column-major pair exactly as produced by the | ||
| 206 | + upstream frontend: weight ``(E, K, N)`` col-major views + scale | ||
| 207 | + ``(E, K/128, N/128)`` col-major views. Both operands must be passed | ||
| 208 | + *unmodified*; re-orienting either one (e.g. to a contiguous | ||
| 209 | + ``(E, N, K)`` + ``(E, N/128, K/128)`` pair) makes the kernel silently | ||
| 210 | + misread the layout, and mixing orientations is rejected outright. | ||
| 211 | + ``group_list`` must be int64 on current builds. | ||
| 212 | + """ | ||
| 213 | + if HAS_GROUPED_BLOCK_QUANT: | ||
| 214 | + return torch_npu.npu_grouped_matmul( | ||
| 215 | + [a], | ||
| 216 | + [b], | ||
| 217 | + scale=[b_s], | ||
| 218 | + per_token_scale=[a_s], | ||
| 219 | + group_list=offs.to(torch.int64), | ||
| 220 | + group_type=0, | ||
| 221 | + group_list_type=0, | ||
| 222 | + scale_dtype=torch.float32, | ||
| 223 | + per_token_scale_dtype=torch.float32, | ||
| 224 | + output_dtype=out_dtype, | ||
| 225 | + split_item=3, | ||
| 226 | + )[0] | ||
| 227 | + | ||
| 228 | + outs: list[torch.Tensor] = [] | ||
| 229 | + for expert, (start, end) in enumerate(_group_slices(offs)): | ||
| 230 | + if end == start: | ||
| 231 | + continue # zero-token expert contributes no rows | ||
| 232 | + outs.append( | ||
| 233 | + block_quant_matmul( | ||
| 234 | + a[start:end], | ||
| 235 | + b[expert], | ||
| 236 | + b_s[expert], | ||
| 237 | + pertoken_scale=a_s[start:end], | ||
| 238 | + output_dtype=out_dtype, | ||
| 239 | + ) | ||
| 240 | + ) | ||
| 241 | + if not outs: | ||
| 242 | + return a.new_empty((0, b.shape[-1]), dtype=out_dtype) | ||
| 243 | + return torch.cat(outs, dim=0) | ||
| @@ -0,0 +1,385 @@ | |||
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 2 | +# All rights reserved. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD 3-Clause license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | +# | ||
| 7 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||
| 8 | + | ||
| 9 | +"""NPU backend for MoE blockwise FP8 grouped GEMM training. | ||
| 10 | + | ||
| 11 | +Upstream original (BSD-3-Clause, adapted here): | ||
| 12 | + torchao/prototype/moe_training/blockwise_fp8/grouped_mm_backend.py | ||
| 13 | + — https://github.com/pytorch/ao/blob/main/torchao/prototype/moe_training/blockwise_fp8/grouped_mm_backend.py | ||
| 14 | + | ||
| 15 | +Upstream ``torchao.prototype.moe_training.blockwise_fp8`` selects a grouped-GEMM | ||
| 16 | +backend through ``_select_fp8_blockwise_grouped_mm_backend`` (DeepGEMM is the | ||
| 17 | +in-tree precedent). This patch registers an NPU backend built on the verified | ||
| 18 | +blockwise primitives in :mod:`torchao_ascend.ops.npu.fp8_block_ops`: | ||
| 19 | + | ||
| 20 | +* RHS quantization (fwd/dgrad): per-expert ``npu_dynamic_block_quant`` with | ||
| 21 | + 128x128 blocks, written in the exact layouts upstream expects | ||
| 22 | + (fwd: ``(E, K, N)`` column-major + ``(E, K/128, N/128)``; | ||
| 23 | + dgrad: contiguous ``(E, N, K)`` + ``(E, N/128, K/128)``). | ||
| 24 | +* grouped GEMM: ``npu_quant_matmul`` group-block (``[0, 128, 128]``) per expert. | ||
| 25 | + The one-shot grouped kernel is opt-in (see ``fp8_block_ops``) until verified. | ||
| 26 | +* wgrad: per-expert ``npu_quant_matmul`` because the LHS is ``grad_outputᵀ`` | ||
| 27 | + and requires 1x128 blocks; the grouped 2D+2D form is not used on NPU. An | ||
| 28 | + HP BF16 grouped-mm fallback (``npu_grouped_matmul`` group_type=2) is | ||
| 29 | + selectable via ``grouped_mm_backend.WGRAD_HP = True``. | ||
| 30 | + | ||
| 31 | +Rebinding notes: ``grouped_mm.py`` imports its collaborators *by value*, so the | ||
| 32 | +backend selector must be rebound in both ``grouped_mm`` and | ||
| 33 | +``grouped_mm_backend``, and the frontend activation quantizer | ||
| 34 | +(``triton_fp8_blockwise_act_quant_lhs``) must be swapped for the NPU one. | ||
| 35 | +The frontend entry itself is also rebound: the upstream entry only accepts | ||
| 36 | +AUTO/EMULATED, so the NPU path is reached via an explicit | ||
| 37 | +``kernel_preference=KernelPreference.NPU`` gate on a rebound wrapper that | ||
| 38 | +dispatches straight into the upstream autograd Function (mirroring the mxfp8 | ||
| 39 | +patch's entry convention; AUTO keeps its upstream semantics — no AUTO@NPU | ||
| 40 | +auto-probing). | ||
| 41 | +Import prerequisite: triton-ascend must be present (it ships with NPU | ||
| 42 | +deployments); triton-less environments degrade via the patch registry's | ||
| 43 | +defensive warnings, consistent with the mxfp8/rowwise patches. | ||
| 44 | +""" | ||
| 45 | +from __future__ import annotations | ||
| 46 | + | ||
| 47 | +from typing import Optional | ||
| 48 | + | ||
| 49 | +import torch | ||
| 50 | +import torch_npu # noqa: F401 # HP wgrad grouped-mm path (NPU-only patch file) | ||
| 51 | +from torchao.float8.config import e4m3_dtype | ||
| 52 | +from torchao.quantization.quantize_.common import KernelPreference | ||
| 53 | + | ||
| 54 | +from torchao_ascend.ops.npu import ( | ||
| 55 | + block_quant, | ||
| 56 | + block_quant_matmul, | ||
| 57 | + grouped_block_quant_matmul, | ||
| 58 | +) | ||
| 59 | +from torchao_ascend.ops.npu.fp8_block_ops import _group_slices # plugin 内复用,避免双份实现 | ||
| 60 | +from torchao_ascend.patches.registry import register_patch | ||
| 61 | + | ||
| 62 | +_ORIG: dict = {"select": None, "entry": None, "fn": None} | ||
| 63 | +_applied = False | ||
| 64 | + | ||
| 65 | +_BLOCK_SIZE = 128 | ||
| 66 | + | ||
| 67 | +# HP wgrad opt-in switch (M0 increment C2-inc2): BF16 grouped mm instead of | ||
| 68 | +# the fp8 blockwise wgrad. Unset/0 = upstream fp8 recipe semantics (default). | ||
| 69 | +WGRAD_HP: bool = False # BF16 high-precision wgrad instead of fp8 blockwise | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +def _npu_act_quant_lhs( | ||
| 73 | + x: torch.Tensor, | ||
| 74 | + block_size: int = _BLOCK_SIZE, | ||
| 75 | + dtype: torch.dtype = torch.float8_e4m3fn, | ||
| 76 | +) -> tuple[torch.Tensor, torch.Tensor]: | ||
| 77 | + """Upstream ``triton_fp8_blockwise_act_quant_lhs`` replacement (1x128).""" | ||
| 78 | + return block_quant( | ||
| 79 | + x.contiguous(), | ||
| 80 | + dst_type=dtype, | ||
| 81 | + row_block_size=1, | ||
| 82 | + col_block_size=block_size, | ||
| 83 | + ) | ||
| 84 | + | ||
| 85 | + | ||
| 86 | +class _NPUGroupedMMBackend: | ||
| 87 | + """Grouped blockwise-FP8 backend on Ascend NPU. | ||
| 88 | + | ||
| 89 | + Instantiated **per forward** by the patched selector (one instance per | ||
| 90 | + fwd+bwd pair) so the batched weight quantization from | ||
| 91 | + ``quantize_forward_rhs`` is reused by ``quantize_dgrad_rhs`` within the | ||
| 92 | + same autograd operation: both directions quantize the identical (N, K) | ||
| 93 | + weight with the identical 128x128 block grid — only the memory layout | ||
| 94 | + differs, which is a view. Per-call instances keep the cache always fresh | ||
| 95 | + (a shared singleton would serve stale fp8 weights to the next layer/step, | ||
| 96 | + because training updates weights between steps). Memory trade: the cache | ||
| 97 | + holds (E, N, K) fp8 weights (~1.6 GB per layer at Qwen3.5 expert dims) | ||
| 98 | + from forward until backward; disable via | ||
| 99 | + ``grouped_mm_backend.WQ_CACHE = False`` (backward then re-quantizes, still | ||
| 100 | + batched single-launch). | ||
| 101 | + """ | ||
| 102 | + | ||
| 103 | + kind = "npu" | ||
| 104 | + | ||
| 105 | + def __init__(self): | ||
| 106 | + # (E, N, K) fp8 data + (E, Nb, Kb) fp32 scales from the first weight | ||
| 107 | + # quant in this autograd operation; None until then. | ||
| 108 | + self._q_cache = None | ||
| 109 | + | ||
| 110 | + def quantize_forward_rhs( | ||
| 111 | + self, | ||
| 112 | + B_t: torch.Tensor, | ||
| 113 | + block_size: int, | ||
| 114 | + dtype: torch.dtype, | ||
| 115 | + ) -> tuple[torch.Tensor, torch.Tensor]: | ||
| 116 | + # B_t[e] is (K, N) column-major, i.e. the transpose of a contiguous | ||
| 117 | + # (N, K) weight. One batched quant over the flattened (E*N, K) storage | ||
| 118 | + # covers all experts in a single launch — the 128x128 block grid over | ||
| 119 | + # (N, K) is identical per expert (N % block_size == 0 upstream), so the | ||
| 120 | + # quantized values match the per-expert loop exactly, minus the E | ||
| 121 | + # launches and per-expert transpose copies. Returns the layouts | ||
| 122 | + # upstream expects: (E, K, N) col-major + (E, K/128, N/128) — views of | ||
| 123 | + # the (E, N, K) contiguous quant. | ||
| 124 | + if self._q_cache is None: | ||
| 125 | + q_data, q_scale = self._quantize_weight_flat(B_t, block_size, dtype) | ||
| 126 | + if WQ_CACHE: | ||
| 127 | + self._q_cache = (q_data, q_scale) | ||
| 128 | + return q_data.transpose(1, 2), q_scale.transpose(1, 2) | ||
| 129 | + return self._q_cache[0].transpose(1, 2), self._q_cache[1].transpose(1, 2) | ||
| 130 | + | ||
| 131 | + def quantize_dgrad_rhs( | ||
| 132 | + self, | ||
| 133 | + B_t: torch.Tensor, | ||
| 134 | + block_size: int, | ||
| 135 | + dtype: torch.dtype, | ||
| 136 | + ) -> tuple[torch.Tensor, torch.Tensor]: | ||
| 137 | + # dgrad consumes RHS as (E, N, K) with K contiguous + (E, N/128, K/128) | ||
| 138 | + # — the same quantized values forward produced (identical 128x128 grid | ||
| 139 | + # over (N, K)). Normal autograd always runs forward first (ctx.backend | ||
| 140 | + # reuses the same instance), so this is a cache hit; with | ||
| 141 | + # WQ_CACHE = False (or direct out-of-autograd calls) | ||
| 142 | + # the cache is empty and dgrad re-quantizes on the spot — same values, | ||
| 143 | + # same (E, N, K) orientation, fresh storage. | ||
| 144 | + if self._q_cache is not None: | ||
| 145 | + return self._q_cache | ||
| 146 | + return self._quantize_weight_flat(B_t, block_size, dtype) | ||
| 147 | + | ||
| 148 | + def _quantize_weight_flat(self, B_t, block_size, dtype): | ||
| 149 | + """Batched weight quantization: one launch over all experts. | ||
| 150 | + | ||
| 151 | + ``B_t`` (E, K, N) is col-major views of contiguous (E, N, K) weights, | ||
| 152 | + so ``B_t.transpose(-2, -1).reshape(E * N, K)`` is a zero-copy flatten. | ||
| 153 | + Requires ``N % block_size == 0`` (upstream asserts) so the 128x128 row | ||
| 154 | + tiles align with expert boundaries and the quantized values match the | ||
| 155 | + per-expert loop exactly. | ||
| 156 | + """ | ||
| 157 | + E, K, N = B_t.shape | ||
| 158 | + weight_flat = B_t.transpose(-2, -1).reshape(E * N, K) | ||
| 159 | + q, s = block_quant( | ||
| 160 | + weight_flat, | ||
| 161 | + dst_type=dtype, | ||
| 162 | + row_block_size=block_size, | ||
| 163 | + col_block_size=block_size, | ||
| 164 | + ) | ||
| 165 | + q_data = q.view(E, N, K) | ||
| 166 | + q_scale = s.view(E, N // block_size, K // block_size) | ||
| 167 | + return q_data, q_scale | ||
| 168 | + | ||
| 169 | + def grouped_mm( | ||
| 170 | + self, | ||
| 171 | + a: torch.Tensor, | ||
| 172 | + b: torch.Tensor, | ||
| 173 | + a_s: torch.Tensor, | ||
| 174 | + scale_recipe_a: int, | ||
| 175 | + b_s: torch.Tensor, | ||
| 176 | + scale_recipe_b: int, | ||
| 177 | + offs: torch.Tensor, | ||
| 178 | + out_dtype: torch.dtype, | ||
| 179 | + block_size: int, | ||
| 180 | + ) -> torch.Tensor: | ||
| 181 | + del scale_recipe_a, scale_recipe_b # 1x128 / 128x128 are implied by the NPU op | ||
| 182 | + return grouped_block_quant_matmul(a, b, a_s, b_s, offs, out_dtype) | ||
| 183 | + | ||
| 184 | + def wgrad( | ||
| 185 | + self, | ||
| 186 | + padded_grad_output: torch.Tensor, | ||
| 187 | + padded_a: torch.Tensor, | ||
| 188 | + group_end_offsets: torch.Tensor, | ||
| 189 | + out_dtype: torch.dtype, | ||
| 190 | + block_size: int, | ||
| 191 | + dtype: torch.dtype, | ||
| 192 | + ) -> torch.Tensor: | ||
| 193 | + # grad_B_t[e] = (grad_out_eᵀ @ A_e)ᵀ; both operands are block-quantized | ||
| 194 | + # on the token axis, so every group must be block-aligned (upstream pads). | ||
| 195 | + if WGRAD_HP: | ||
| 196 | + # HP wgrad (opt-in): BF16 grouped mm on the HP operands via | ||
| 197 | + # npu_grouped_matmul group_type=2 K-split/dW layout — the same | ||
| 198 | + # implementation as the rowwise patch's wgrad_with_hp path. | ||
| 199 | + # Granularity-independent and needs no block alignment. Zero-token | ||
| 200 | + # groups are handled natively by the grouped kernel (empirically | ||
| 201 | + # verified: an empty middle group returns finite output; the fp8 | ||
| 202 | + # path below needs explicit zero blocks only because its | ||
| 203 | + # per-expert dense loop cannot run a 0-row GEMM). | ||
| 204 | + # npu_grouped_matmul returns [E, K, N]; the fp8 path below returns | ||
| 205 | + # [E, N, K] and upstream backward applies a uniform | ||
| 206 | + # transpose(-2, -1), so transpose here to keep the contract. | ||
| 207 | + hp_grad = torch_npu.npu_grouped_matmul( | ||
| 208 | + [padded_a.transpose(0, 1)], | ||
| 209 | + [padded_grad_output], | ||
| 210 | + group_list=group_end_offsets.to(torch.int64), | ||
| 211 | + group_type=2, | ||
| 212 | + group_list_type=0, | ||
| 213 | + split_item=3, | ||
| 214 | + output_dtype=out_dtype, | ||
| 215 | + )[0] | ||
| 216 | + return hp_grad.transpose(-2, -1) | ||
🟡 Medium Priority 变更行:torchao_ascend/patches/torchao/prototype/moe_training/blockwise_fp8/grouped_mm_backend.py:196-213( 证据链: 失败模式: 建议:HP wgrad 分支补齐零 token 组的显式处理(跳过该组或输出后按零组置零),与 fp8 分支契约对齐,并新增 HP + 零组用例。 ![]() ![]() Incorrect? | |||
| 217 | + N = padded_grad_output.shape[-1] | ||
| 218 | + K = padded_a.shape[-1] | ||
| 219 | + grad_blocks: list[torch.Tensor] = [] | ||
| 220 | + for start, end in _group_slices(group_end_offsets): | ||
| 221 | + size = end - start | ||
| 222 | + if size == 0: | ||
| 223 | + grad_blocks.append( | ||
| 224 | + torch.zeros((N, K), dtype=out_dtype, device=padded_a.device) | ||
| 225 | + ) | ||
| 226 | + continue | ||
| 227 | + if size % block_size != 0: | ||
| 228 | + raise ValueError( | ||
| 229 | + "NPU blockwise wgrad requires block-aligned token groups, got " | ||
| 230 | + f"group size {size} (enable pad_token_groups_for_grouped_mm)" | ||
| 231 | + ) | ||
| 232 | + go_t = padded_grad_output[start:end].t().contiguous() # (N, Me) | ||
| 233 | + lhs_q, lhs_s = block_quant( | ||
| 234 | + go_t, | ||
| 235 | + dst_type=dtype, | ||
| 236 | + row_block_size=1, | ||
| 237 | + col_block_size=block_size, | ||
| 238 | + ) | ||
| 239 | + a_e = padded_a[start:end].contiguous() # (Me, K) | ||
| 240 | + rhs_q, rhs_s = block_quant( | ||
| 241 | + a_e, | ||
| 242 | + dst_type=dtype, | ||
| 243 | + row_block_size=block_size, | ||
| 244 | + col_block_size=block_size, | ||
| 245 | + ) | ||
| 246 | + grad_blocks.append( | ||
| 247 | + block_quant_matmul( | ||
| 248 | + lhs_q, | ||
| 249 | + rhs_q, | ||
| 250 | + rhs_s, | ||
| 251 | + pertoken_scale=lhs_s, | ||
| 252 | + output_dtype=out_dtype, | ||
| 253 | + ) | ||
| 254 | + ) | ||
| 255 | + return torch.stack(grad_blocks, dim=0) # (E, N, K) | ||
| 256 | + | ||
| 257 | + | ||
| 258 | +# Direct/test access only — the framework path returns per-call instances from | ||
| 259 | +# the selector (see _select_fp8_blockwise_grouped_mm_backend) so the weight | ||
| 260 | +# quant cache never goes stale across layers/steps. | ||
| 261 | +_NPU_BACKEND = _NPUGroupedMMBackend() | ||
| 262 | + | ||
| 263 | +# Weight-quant cache kill-switch (default on): the cache holds (E, N, K) fp8 | ||
| 264 | +# weights per layer between forward and backward (~1.6 GB/layer at Qwen3.5 | ||
| 265 | +# expert dims). Set =0 for very deep models where the held memory outweighs | ||
| 266 | +# the saved re-quant; backward then re-quantizes batched single-launch. | ||
| 267 | +WQ_CACHE: bool = True # stash the forward weight quant for the dgrad reuse | ||
| 268 | + | ||
| 269 | + | ||
| 270 | +def _to_fp8_blockwise_then_scaled_grouped_mm( | ||
| 271 | + A: torch.Tensor, | ||
| 272 | + B_t: torch.Tensor, | ||
| 273 | + offs: Optional[torch.Tensor] = None, | ||
| 274 | + out_dtype: Optional[torch.dtype] = torch.bfloat16, | ||
| 275 | + float8_dtype: torch.dtype = e4m3_dtype, | ||
| 276 | + block_size: int = 128, | ||
| 277 | + pad_token_groups_for_grouped_mm: bool = True, | ||
| 278 | + kernel_preference: KernelPreference = KernelPreference.AUTO, | ||
| 279 | +) -> torch.Tensor: | ||
| 280 | + """Rebound frontend entry: add the explicit-NPU branch. | ||
| 281 | + | ||
| 282 | + The upstream entry asserts ``kernel_preference in (AUTO, EMULATED)``, so | ||
| 283 | + ``KernelPreference.NPU`` cannot reach the selector through it. This | ||
| 284 | + wrapper validates the NPU preconditions and dispatches straight into the | ||
| 285 | + upstream autograd Function — the frontend's by-value selector and | ||
| 286 | + activation-quantizer seams are already rebound to the NPU | ||
| 287 | + implementations, and the Function forwards ``kernel_preference`` to the | ||
| 288 | + selector, which dispatches on the explicit gate. ``AUTO``/``EMULATED`` | ||
| 289 | + delegate to the original entry unchanged (CUDA DeepGEMM / torch | ||
| 290 | + emulation; AUTO@NPU auto-probing is tracked as follow-up work, mirroring | ||
| 291 | + the mxfp8 patch). | ||
| 292 | + """ | ||
| 293 | + if kernel_preference == KernelPreference.NPU: | ||
| 294 | + if block_size != _BLOCK_SIZE: | ||
| 295 | + raise ValueError( | ||
| 296 | + f"NPU fp8 blockwise requires block_size=128, got {block_size}" | ||
| 297 | + ) | ||
| 298 | + if A.device.type != "npu": | ||
| 299 | + raise ValueError( | ||
| 300 | + f"torchao_ascend _Float8BlockwiseGroupedMM requires NPU tensors " | ||
| 301 | + f"(kernel_preference={kernel_preference}), got device {A.device.type}" | ||
| 302 | + ) | ||
| 303 | + return _ORIG["fn"].apply( | ||
| 304 | + A, B_t, offs, out_dtype, float8_dtype, block_size, | ||
| 305 | + pad_token_groups_for_grouped_mm, kernel_preference, | ||
| 306 | + ) | ||
| 307 | + return _ORIG["entry"]( | ||
| 308 | + A, B_t, offs, out_dtype, float8_dtype, block_size, | ||
| 309 | + pad_token_groups_for_grouped_mm, kernel_preference, | ||
| 310 | + ) | ||
| 311 | + | ||
这个变量是对外的,需要补齐资料; _menu_environment_variable.md ![]() ![]() | |||
| 312 | + | ||
| 313 | +def _select_fp8_blockwise_grouped_mm_backend( | ||
| 314 | + kernel_preference: KernelPreference, | ||
| 315 | + A: torch.Tensor, | ||
| 316 | + out_dtype: torch.dtype, | ||
| 317 | + block_size: int, | ||
| 318 | + group_end_offsets: torch.Tensor, | ||
| 319 | + *, | ||
| 320 | + original_group_end_offsets: torch.Tensor | None = None, | ||
| 321 | + padded_group_start_offsets: torch.Tensor | None = None, | ||
| 322 | + num_rows: int | None = None, | ||
| 323 | +): | ||
| 324 | + """NPU dispatch on the explicit ``KernelPreference.NPU`` gate; AUTO and | ||
| 325 | + EMULATED flow past to the upstream selector (CUDA DeepGEMM / torch | ||
| 326 | + emulation semantics preserved). Device validation mirrors the mxfp8 | ||
| 327 | + patch.""" | ||
| 328 | + if kernel_preference == KernelPreference.NPU: | ||
| 329 | + if A.device.type != "npu": | ||
| 330 | + raise ValueError( | ||
| 331 | + f"torchao_ascend _Float8BlockwiseGroupedMM requires NPU tensors " | ||
| 332 | + f"(kernel_preference={kernel_preference}), got device {A.device.type}" | ||
| 333 | + ) | ||
| 334 | + if block_size != _BLOCK_SIZE: | ||
| 335 | + raise AssertionError( | ||
| 336 | + f"NPU blockwise grouped GEMM only supports block_size=128, got {block_size}" | ||
| 337 | + ) | ||
| 338 | + # per-call instance: the weight-quant cache must be scoped to exactly | ||
| 339 | + # one fwd+bwd pair — training updates weights between steps, so a | ||
| 340 | + # shared singleton would serve stale fp8 weights to the next | ||
| 341 | + # layer/step. _NPU_BACKEND stays module-level for direct/test access. | ||
| 342 | + return _NPUGroupedMMBackend() | ||
| 343 | + return _ORIG["select"]( | ||
| 344 | + kernel_preference, | ||
| 345 | + A, | ||
| 346 | + out_dtype, | ||
| 347 | + block_size, | ||
| 348 | + group_end_offsets, | ||
| 349 | + original_group_end_offsets=original_group_end_offsets, | ||
| 350 | + padded_group_start_offsets=padded_group_start_offsets, | ||
| 351 | + num_rows=num_rows, | ||
| 352 | + ) | ||
| 353 | + | ||
| 354 | + | ||
| 355 | +@register_patch(group="blockwise", order=10) | ||
| 356 | +def apply() -> None: | ||
| 357 | + """Install the NPU backend for MoE blockwise FP8 grouped GEMM.""" | ||
| 358 | + global _applied | ||
| 359 | + if _applied: | ||
| 360 | + return | ||
| 361 | + | ||
| 362 | + import torchao.prototype.moe_training.blockwise_fp8.grouped_mm as grouped_mm_mod | ||
| 363 | + import torchao.prototype.moe_training.blockwise_fp8.grouped_mm_backend as backend_mod | ||
| 364 | + | ||
| 365 | + _ORIG["select"] = backend_mod._select_fp8_blockwise_grouped_mm_backend | ||
| 366 | + _ORIG["entry"] = grouped_mm_mod._to_fp8_blockwise_then_scaled_grouped_mm | ||
| 367 | + _ORIG["fn"] = grouped_mm_mod._Float8BlockwiseGroupedMM | ||
| 368 | + | ||
| 369 | + # Both modules hold their own by-value reference to the selector. | ||
| 370 | + backend_mod._select_fp8_blockwise_grouped_mm_backend = ( | ||
| 371 | + _select_fp8_blockwise_grouped_mm_backend | ||
| 372 | + ) | ||
| 373 | + grouped_mm_mod._select_fp8_blockwise_grouped_mm_backend = ( | ||
| 374 | + _select_fp8_blockwise_grouped_mm_backend | ||
| 375 | + ) | ||
| 376 | + | ||
| 377 | + # Frontend entry: NPU branch + upstream delegation (see the wrapper). | ||
| 378 | + grouped_mm_mod._to_fp8_blockwise_then_scaled_grouped_mm = ( | ||
| 379 | + _to_fp8_blockwise_then_scaled_grouped_mm | ||
| 380 | + ) | ||
| 381 | + | ||
| 382 | + # Frontend activation quantization runs through the module-level binding. | ||
| 383 | + grouped_mm_mod.triton_fp8_blockwise_act_quant_lhs = _npu_act_quant_lhs | ||
| 384 | + | ||
| 385 | + _applied = True | ||


16384是指batchsize4、seq_len4096乘出来的吗