Merged
[fix] 迁移 DeepEP MXFP8 通信量化到 TorchTitan 0.4.0 #1465
zx1029Add on 2 days ago
[fix] 迁移 DeepEP MXFP8 通信量化到 TorchTitan 0.4.0 #1465
Merged
Total: 17 files changed+876-51
| @@ -224,9 +224,35 @@ attention 等 dense 权重仍使用 FP8。专家在 `[E, N, K]` 布局下沿 K | |||
| 224 | 该功能基于 FSDP2,当前不支持 FSDP1 低精度通信。`EFSDP=1` 时不发生 all-gather;开启该开关后,post-all-gather 仍会按 | 224 | 该功能基于 FSDP2,当前不支持 FSDP1 低精度通信。`EFSDP=1` 时不发生 all-gather;开启该开关后,post-all-gather 仍会按 |
| 225 | `fsdp-prequantize-dtype` 量化反分片权重,使单卡与多卡路径保存相同的权重格式。 | 225 | `fsdp-prequantize-dtype` 量化反分片权重,使单卡与多卡路径保存相同的权重格式。 |
| 226 | 226 | ||
| 227 | +## MoE 专家激活 MXFP8 通信 | ||
| 228 | + | ||
| 229 | +Python 字段 `config.extension.quantization.all_to_all_quant_format` 控制 EP token 通信的量化格式,默认 `None`,关闭通信量化。通信后端由模型 recipe 选择。当前 `mxfp8` 适用于 CANN DeepEP,Standard AllToAll 暂未接入。 | ||
| 230 | + | ||
| 231 | +### DeepEP 启用方式 | ||
| 232 | + | ||
| 233 | +例如,基于已选择 DeepEP 和 `all_block_fp8` 的 DeepSeek-V4 A5 recipe,只设置通信开关。 | ||
| 234 | + | ||
| 235 | +```python | ||
| 236 | +from torchtitan_npu_recipes.models.deepseek_v4 import deepseek_v4_flash_cpt_4k_a5 | ||
| 237 | + | ||
| 238 | + | ||
| 239 | +def deepseek_v4_flash_cpt_4k_a5_mxfp8(): | ||
| 240 | + config = deepseek_v4_flash_cpt_4k_a5() | ||
| 241 | + config.extension.quantization.all_to_all_quant_format = "mxfp8" | ||
| 242 | + return config | ||
| 243 | +``` | ||
| 244 | + | ||
| 245 | +启用条件 | ||
| 246 | + | ||
| 247 | +- 模型的 routed experts 统一使用 DeepEP。converter 自动选择 MXFP8 CANN DeepEP,已有的 `asc_deepep` override 可保留。其他 dispatcher 或混用 dispatcher 家族时,转换报错。 | ||
| 248 | +- 设置 `enable_quantized_training=True`,`recipe` 为 `all_block_fp8` 或 `mix`(两者都预量化 routed experts)。专家的 `w13` 和 `w2` 须使用相同的 E4M3 激活量化配置,块大小为 32。 | ||
| 249 | +- 使用 eager 训练和 `expert_parallel_degree > 1`。`num_max_tokens_per_rank` 须覆盖每个 EP rank 的输入 token 数。CANN wheel 须支持普通和 cached 两种 `(qdata, scale)` dispatch。 | ||
| 250 | + | ||
| 251 | +dispatch 前向和 combine 反向传输 MXFP8(E4M3 数据与 E8M0 scale)。combine 前向和 dispatch 反向使用高精度。启动日志中 `Installed torchao-npu MXFP8 communication on N dispatcher node(s)` 的 `N > 0` 表示已完成 dispatcher 配置替换。 | ||
| 252 | + | ||
| 227 | ## 配置与生效检查 | 253 | ## 配置与生效检查 |
| 228 | 254 | ||
| 229 | -以下字段均位于 `--extension.quantization` 下,表中省略公共前缀: | 255 | +以下字段均位于 `--extension.quantization` 下,表中省略公共前缀。EP 通信量化的 Python 字段见 [MoE 专家激活 MXFP8 通信](#moe-专家激活-mxfp8-通信)。 |
| 230 | 256 | ||
| 231 | | 参数 | 默认值 | 说明 | | 257 | | 参数 | 默认值 | 说明 | |
| 232 | | --- | --- | --- | | 258 | | --- | --- | --- | |
| @@ -239,6 +265,7 @@ attention 等 dense 权重仍使用 FP8。专家在 `[E, N, K]` 布局下沿 K | |||
| 239 | | `enable-fsdp-prequantize` | `False` | 启用 FSDP 参数 all-gather 前预量化 | | 265 | | `enable-fsdp-prequantize` | `False` | 启用 FSDP 参数 all-gather 前预量化 | |
| 240 | | `fsdp-prequantize-dtype` | `fp8` | Routed experts 的预量化通信格式;`mxfp4` 要求专家启用 MXFP4 QAT。`all_block_fp8` 下 attention 等 dense 权重仍使用 FP8 通信,启用范围由白名单决定 | | 266 | | `fsdp-prequantize-dtype` | `fp8` | Routed experts 的预量化通信格式;`mxfp4` 要求专家启用 MXFP4 QAT。`all_block_fp8` 下 attention 等 dense 权重仍使用 FP8 通信,启用范围由白名单决定 | |
| 241 | | `fsdp-prequantize-fqns` | `None` | 预量化权重 FQN 后缀白名单,多个模式写在同一参数内并以英文逗号分隔(如 `.attention.wq_b,.attention.wo_a`);`None` 用 recipe 默认白名单(按 dim 0 分片、不含 stacked gate/up 的 Block FP8 投影),显式空表与开关同开报 `ValueError`,命中但对齐失败的权重启动即报错 | | 267 | | `fsdp-prequantize-fqns` | `None` | 预量化权重 FQN 后缀白名单,多个模式写在同一参数内并以英文逗号分隔(如 `.attention.wq_b,.attention.wo_a`);`None` 用 recipe 默认白名单(按 dim 0 分片、不含 stacked gate/up 的 Block FP8 投影),显式空表与开关同开报 `ValueError`,命中但对齐失败的权重启动即报错 | |
| 268 | +| `all-to-all-quant-format` | `None` | EP token 通信量化格式;`mxfp8` 仅支持 CANN DeepEP,需 `enable-quantized-training` 与 Block MX 专家配置 | | ||
| 242 | | `kv-norm-quantization.format` | 未设置 | V4 nope KV Cache 量化格式,目前为 `mxfp8`(8 bit E4M3) | | 269 | | `kv-norm-quantization.format` | 未设置 | V4 nope KV Cache 量化格式,目前为 `mxfp8`(8 bit E4M3) | |
| 243 | | `kv-norm-quantization.fqns` | 空列表 | V4 的量化插入位置,脚本使用 `.attention.kv_norm,.attention.compressor.norm,.attention.compressor_128.norm` | | 270 | | `kv-norm-quantization.fqns` | 空列表 | V4 的量化插入位置,脚本使用 `.attention.kv_norm,.attention.compressor.norm,.attention.compressor_128.norm` | |
| 244 | | `kv-norm-quantization.block-size` | `32` | V4 KV Cache MXFP8 的 block size;A5 脚本使用 `64` | | 271 | | `kv-norm-quantization.block-size` | `32` | V4 KV Cache MXFP8 的 block size;A5 脚本使用 `64` | |
| @@ -0,0 +1,75 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 2 | +# | ||
| 3 | +# This source code is licensed under the BSD-style license found in the | ||
| 4 | +# LICENSE file in the root directory of this source tree. | ||
| 5 | + | ||
| 6 | +"""CPU checks for the DeepEP MXFP8 payload layout and tensor reconstruction.""" | ||
| 7 | + | ||
| 8 | +import pytest | ||
| 9 | + | ||
| 10 | +# TorchAO-NPU is an optional dependency and only CI hosts with it installed can | ||
| 11 | +# import the payload module; skip at collection before the import below. | ||
| 12 | +pytest.importorskip("torch_npu") | ||
| 13 | +pytest.importorskip("torchao_npu") | ||
| 14 | + | ||
| 15 | +import torch | ||
| 16 | +from torchao_npu.ops.mxfp8_deepep_payload import quantize_payload, wire_tensor | ||
| 17 | +from torchao_npu.quantization.quant_configs import MXQuantizeConfig | ||
| 18 | + | ||
| 19 | +_MXFP8_CONFIG = MXQuantizeConfig() | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def test_quantize_payload_rejects_rank_three_activation(): | ||
| 23 | + with pytest.raises(ValueError, match="2D BF16/FP16/FP32 activation"): | ||
| 24 | + quantize_payload(torch.empty(4, 2, 128, dtype=torch.bfloat16), _MXFP8_CONFIG) | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +def test_quantize_payload_rejects_non_32_block_size(): | ||
| 28 | + with pytest.raises(ValueError, match="block_size=32"): | ||
| 29 | + quantize_payload(torch.empty(4, 128, dtype=torch.bfloat16), MXQuantizeConfig(block_size=64)) | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def test_wire_tensor_reuses_activation_config(): | ||
| 33 | + qdata = torch.zeros((2, 128), dtype=torch.float8_e4m3fn) | ||
| 34 | + scale = torch.arange(8, dtype=torch.uint8).reshape(2, 4) | ||
| 35 | + | ||
| 36 | + received = wire_tensor(qdata, scale, torch.bfloat16, _MXFP8_CONFIG, False) | ||
| 37 | + | ||
| 38 | + assert received.quant_config is _MXFP8_CONFIG | ||
| 39 | + assert received.qdata is qdata | ||
| 40 | + assert torch.equal(received.scale, torch.tensor([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=torch.uint8)) | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +def test_wire_tensor_rejects_rank_one_payloads(): | ||
| 44 | + with pytest.raises(ValueError, match="rank-2 qdata and scale"): | ||
| 45 | + wire_tensor( | ||
| 46 | + torch.empty(128, dtype=torch.uint8), | ||
| 47 | + torch.empty(4, 4, dtype=torch.uint8), | ||
| 48 | + torch.bfloat16, | ||
| 49 | + _MXFP8_CONFIG, | ||
| 50 | + False, | ||
| 51 | + ) | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +def test_wire_tensor_rejects_row_mismatch(): | ||
| 55 | + with pytest.raises(ValueError, match="payload row mismatch: qdata has 4 rows, scale has 3 rows"): | ||
| 56 | + wire_tensor( | ||
| 57 | + torch.empty(4, 128, dtype=torch.uint8), | ||
| 58 | + torch.empty(3, 4, dtype=torch.uint8), | ||
| 59 | + torch.bfloat16, | ||
| 60 | + _MXFP8_CONFIG, | ||
| 61 | + False, | ||
| 62 | + ) | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +def test_wire_tensor_rejects_odd_packed_scale_width(): | ||
| 66 | + # 128 hidden / 32 block_size = 4 scales, packed as two uint8 bytes each, so | ||
| 67 | + # any odd byte count cannot be reshaped back into the (rows, pairs, 2) layout. | ||
| 68 | + with pytest.raises(ValueError, match="packed scale width must be even, got 5"): | ||
| 69 | + wire_tensor( | ||
| 70 | + torch.empty(4, 128, dtype=torch.uint8), | ||
| 71 | + torch.empty(4, 5, dtype=torch.uint8), | ||
| 72 | + torch.bfloat16, | ||
| 73 | + _MXFP8_CONFIG, | ||
| 74 | + False, | ||
| 75 | + ) | ||
| @@ -168,6 +168,9 @@ def test_resolve_pack_axis_requires_fp4(shape): | |||
| 168 | (256, (-1,), (256,)), | 168 | (256, (-1,), (256,)), |
| 169 | (256, (-1, 64), (4, 64)), | 169 | (256, (-1, 64), (4, 64)), |
| 170 | (256, (4, -1, 4), (4, 16, 4)), | 170 | (256, (4, -1, 4), (4, 16, 4)), |
| 171 | + (0, (0, 5120), (0, 5120)), | ||
| 172 | + (0, (0,), (0,)), | ||
| 173 | + (0, (-1,), (0,)), | ||
| 171 | ], | 174 | ], |
| 172 | ) | 175 | ) |
| 173 | def test_resolve_view_shape_accounts_for_the_elements(elem_num, new_shape, expected): | 176 | def test_resolve_view_shape_accounts_for_the_elements(elem_num, new_shape, expected): |
| @@ -183,9 +186,11 @@ def test_resolve_view_shape_accounts_for_the_elements(elem_num, new_shape, expec | |||
| 183 | "elem_num, new_shape, message", | 186 | "elem_num, new_shape, message", |
| 184 | [ | 187 | [ |
| 185 | (256, (-1, -1), "Only one dimension can be inferred"), | 188 | (256, (-1, -1), "Only one dimension can be inferred"), |
| 186 | - (256, (4, 0), "only -1 and positive dims are allowed"), | 189 | + (256, (4, 0), "invalid for input of size 256"), |
| 187 | (256, (7, 37), "invalid for input of size 256"), | 190 | (256, (7, 37), "invalid for input of size 256"), |
| 188 | (256, (3, -1), "the -1 dim is not divisible"), | 191 | (256, (3, -1), "the -1 dim is not divisible"), |
| 192 | + (0, (0, -1), "the -1 dim is ambiguous"), | ||
| 193 | + (256, (-2, 4), "only -1 and non-negative dims are allowed"), | ||
| 189 | ], | 194 | ], |
| 190 | ) | 195 | ) |
| 191 | def test_resolve_view_shape_rejects_every_other_shape(elem_num, new_shape, message): | 196 | def test_resolve_view_shape_rejects_every_other_shape(elem_num, new_shape, message): |
| @@ -12,5 +12,6 @@ public surface via ``__all__``: | |||
| 12 | - :mod:`torchao_npu.ops.float8_ops` — FP8 row-wise fake quantization | 12 | - :mod:`torchao_npu.ops.float8_ops` — FP8 row-wise fake quantization |
| 13 | - :mod:`torchao_npu.ops.hif8_ops` — Per-tensor HiF8 matmul ops (current/constant tensor scaling) | 13 | - :mod:`torchao_npu.ops.hif8_ops` — Per-tensor HiF8 matmul ops (current/constant tensor scaling) |
| 14 | - :mod:`torchao_npu.ops.mx_ops` — MX (FP8/FP4) matmul and (de)quantization ops | 14 | - :mod:`torchao_npu.ops.mx_ops` — MX (FP8/FP4) matmul and (de)quantization ops |
| 15 | -- :mod:`torchao_npu.ops.mxfp8_wire` — MXFP8 activation wire primitives (quantize / dequantize / wrap) | 15 | +- :mod:`torchao_npu.ops.mxfp8_deepep_payload` — MXFP8 DeepEP payload codec |
| 16 | +- :mod:`torchao_npu.ops.mxfp8_wire` — MXFP8 activation wire primitives (quantize/dequantize) | ||
| 16 | """ | 17 | """ |
| @@ -0,0 +1,77 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# | ||
| 3 | +# This source code is licensed under the BSD-style license found in the | ||
| 4 | +# LICENSE file in the root directory of this source tree. | ||
| 5 | + | ||
| 6 | +"""Encode and decode MXFP8 payloads for the CANN DeepEP wire layout.""" | ||
| 7 | + | ||
| 8 | +from __future__ import annotations | ||
| 9 | + | ||
| 10 | +__all__ = ["DequantizeGradient", "dequantize_if_mxfp8", "quantize_payload", "wire_tensor"] | ||
| 11 | + | ||
| 12 | +from typing import TYPE_CHECKING | ||
| 13 | + | ||
| 14 | +import torch | ||
| 15 | + | ||
| 16 | +from torchao_npu.ops.mxfp8_wire import _mxfp8_quantize_or_empty | ||
| 17 | +from torchao_npu.quantized_tensors.mx_tensor import MXTensor, _mxfp8_dequantize_tensor | ||
| 18 | + | ||
| 19 | +if TYPE_CHECKING: | ||
| 20 | + from torchao_npu.quantization.quant_configs import MXQuantizeConfig | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def quantize_payload(activation: torch.Tensor, config: MXQuantizeConfig) -> tuple[torch.Tensor, torch.Tensor]: | ||
| 24 | + """Use Standard's quantizer, then adapt its scale layout to CANN's ABI.""" | ||
| 25 | + if activation.ndim != 2 or activation.dtype not in (torch.bfloat16, torch.float16, torch.float32): | ||
| 26 | + raise ValueError("MXFP8 DeepEP expects a 2D BF16/FP16/FP32 activation") | ||
| 27 | + # CANN infers the number of MX scales from hidden / 32; there is no block-size argument. | ||
| 28 | + if config.block_size != 32 or config.elem_dtype is not torch.float8_e4m3fn: | ||
| 29 | + raise ValueError("MXFP8 DeepEP requires E4M3 and block_size=32 for ElasticBuffer's MX scale layout") | ||
| 30 | + activation = dequantize_if_mxfp8(activation) | ||
| 31 | + scale_alg = config.scale_alg | ||
| 32 | + if scale_alg is None: # MXQuantizeConfig.__post_init__ always resolves it. | ||
| 33 | + raise ValueError("MXFP8 DeepEP requires a resolved MX scale algorithm") | ||
| 34 | + qdata, scale = _mxfp8_quantize_or_empty( | ||
| 35 | + activation, config.block_size, config.round_mode, scale_alg, config.dst_type_max | ||
| 36 | + ) | ||
| 37 | + # A byte view preserves E8M0 bits. CANN's C++ adapter tags uint8 scales as ACL_FLOAT8_E8M0. | ||
| 38 | + # Explicit dimensions also work for zero rows; reshape(0, -1) would be ambiguous. | ||
| 39 | + return qdata, scale.view(torch.uint8).reshape(scale.shape[0], scale.shape[1] * 2) | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +def wire_tensor( | ||
| 43 | + qdata: torch.Tensor, | ||
| 44 | + scale: torch.Tensor, | ||
| 45 | + dtype: torch.dtype, | ||
| 46 | + config: MXQuantizeConfig, | ||
| 47 | + requires_grad: bool, | ||
| 48 | +) -> MXTensor: | ||
| 49 | + # ElasticBuffer returns expert-major rows for BOTH payloads, so no local reroute is needed. | ||
| 50 | + if qdata.ndim != 2 or scale.ndim != 2: | ||
| 51 | + raise ValueError("DeepEP MXFP8 payloads must be rank-2 qdata and scale tensors") | ||
| 52 | + if qdata.shape[0] != scale.shape[0]: | ||
| 53 | + raise ValueError( | ||
| 54 | + f"DeepEP MXFP8 payload row mismatch: qdata has {qdata.shape[0]} rows, scale has {scale.shape[0]} rows" | ||
| 55 | + ) | ||
| 56 | + if scale.shape[1] % 2 != 0: | ||
| 57 | + raise ValueError(f"DeepEP MXFP8 packed scale width must be even, got {scale.shape[1]}") | ||
| 58 | + scale = scale.reshape(scale.shape[0], scale.shape[1] // 2, 2) | ||
| 59 | + return MXTensor(qdata, scale, dtype, -1, config, requires_grad=requires_grad) | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +def dequantize_if_mxfp8(tensor: torch.Tensor) -> torch.Tensor: | ||
| 63 | + return _mxfp8_dequantize_tensor(tensor) if isinstance(tensor, MXTensor) else tensor | ||
| 64 | + | ||
| 65 | + | ||
| 66 | +class DequantizeGradient(torch.autograd.Function): | ||
| 67 | + """Let ordinary autograd consume a gradient returned as an MXTensor.""" | ||
| 68 | + | ||
| 69 | + @staticmethod | ||
| 70 | + def forward(ctx, tensor): # pyrefly: ignore [bad-override] | ||
| 71 | + return tensor | ||
| 72 | + | ||
| 73 | + @staticmethod | ||
| 74 | + def backward(ctx, grad_output): # pyrefly: ignore [bad-override] | ||
| 75 | + # This boundary changes representation only; MulBackward owns both | ||
| 76 | + # the expert-output gradient and the routing-score gradient. | ||
| 77 | + return dequantize_if_mxfp8(grad_output) | ||
| @@ -5,20 +5,15 @@ | |||
| 5 | 5 | ||
| 6 | """MXFP8 activation wire primitives shared by the all-to-all payload paths. | 6 | """MXFP8 activation wire primitives shared by the all-to-all payload paths. |
| 7 | 7 | ||
| 8 | -The quantization custom ops and the wire-tensor constructor live here so the | 8 | +The quantization custom ops use tensor and scalar arguments. Payload adapters |
| 9 | -Standard all-to-all and DeepEP payload adapters compose the same primitives: | 9 | +handle the wire layout and reconstruction of the received tensor. Every custom |
| 10 | -``mxfp8_deepep_payload`` builds the ``(qdata, scale)`` pair and wires it back | 10 | +op is NPU-only and exposes a fake kernel, so a compiled graph keeps the wire |
| 11 | -into an ``MXTensor``, and the enclosing autograd function in | 11 | +layout symbolic and an empty sender never reaches the NPU kernel. |
| 12 | -``torchtitan_npu.extensions.adaptor.torchao`` defines the VJP. Every custom op is | ||
| 13 | -NPU-only and exposes a fake kernel, so a compiled graph keeps the wire layout | ||
| 14 | -symbolic and an empty sender never reaches the NPU kernel. | ||
| 15 | """ | 12 | """ |
| 16 | 13 | ||
| 17 | __all__ = [ | 14 | __all__ = [ |
| 18 | - "MXFP8QuantParams", | ||
| 19 | "_mxfp8_dequantize_or_empty", | 15 | "_mxfp8_dequantize_or_empty", |
| 20 | "_mxfp8_quantize_or_empty", | 16 | "_mxfp8_quantize_or_empty", |
| 21 | - "_mxfp8_wire_tensor", | ||
| 22 | ] | 17 | ] |
| 23 | 18 | ||
| 24 | from collections.abc import Sequence | 19 | from collections.abc import Sequence |
| @@ -27,10 +22,6 @@ import torch | |||
| 27 | 22 | ||
| 28 | from torchao_npu.quantization.quant_configs import MXQuantizeConfig | 23 | from torchao_npu.quantization.quant_configs import MXQuantizeConfig |
| 29 | from torchao_npu.quantization.quant_primitives.mx import mx_dequantize, mx_quantize | 24 | from torchao_npu.quantization.quant_primitives.mx import mx_dequantize, mx_quantize |
| 30 | -from torchao_npu.quantized_tensors.mx_tensor import MXTensor | ||
| 31 | - | ||
| 32 | -# Primitive-only graph signature of the E4M3 activation quantizer. | ||
| 33 | -MXFP8QuantParams = tuple[int, str, int, float] | ||
| 34 | 25 | ||
| 35 | 26 | ||
| 36 | def _contiguous_strides(shape: Sequence[int]) -> tuple[int, ...]: | 27 | def _contiguous_strides(shape: Sequence[int]) -> tuple[int, ...]: |
| @@ -172,23 +163,3 @@ def _mxfp8_dequantize_or_empty_fake( | |||
| 172 | ) -> torch.Tensor: | 163 | ) -> torch.Tensor: |
| 173 | del scale, block_size | 164 | del scale, block_size |
| 174 | return torch.empty_like(qdata, dtype=output_dtype) | 165 | return torch.empty_like(qdata, dtype=output_dtype) |
| 175 | - | ||
| 176 | - | ||
| 177 | -def _mxfp8_wire_tensor( | ||
| 178 | - qdata: torch.Tensor, | ||
| 179 | - scale: torch.Tensor, | ||
| 180 | - dtype: torch.dtype, | ||
| 181 | - quant_params: MXFP8QuantParams, | ||
| 182 | - requires_grad: bool, | ||
| 183 | -) -> MXTensor: | ||
| 184 | - # Keep the Python config inside this constructor: the surrounding compiled | ||
| 185 | - # autograd path passes only primitive quantization metadata. | ||
| 186 | - block_size, round_mode, scale_alg, dst_type_max = quant_params | ||
| 187 | - config = MXQuantizeConfig( | ||
| 188 | - block_size=block_size, | ||
| 189 | - elem_dtype=torch.float8_e4m3fn, | ||
| 190 | - round_mode=round_mode, | ||
| 191 | - scale_alg=scale_alg, | ||
| 192 | - dst_type_max=dst_type_max, | ||
| 193 | - ) | ||
| 194 | - return MXTensor(qdata, scale, dtype, -1, config, requires_grad=requires_grad) | ||
| @@ -40,19 +40,19 @@ def resolve_view_shape(elem_num: int, new_shape: tuple[int, ...]) -> torch.Size: | |||
| 40 | dim. | 40 | dim. |
| 41 | 41 | ||
| 42 | Raises: | 42 | Raises: |
| 43 | - ValueError: If ``new_shape`` holds more than one ``-1``, holds a non-positive dim | 43 | + ValueError: If ``new_shape`` holds more than one ``-1``, holds a negative dim other |
| 44 | - other than ``-1``, does not multiply to ``elem_num``, or its inferred dim is not | 44 | + than ``-1``, does not multiply to ``elem_num``, or its inferred dim is not an |
| 45 | - an exact divisor of ``elem_num``. | 45 | + exact divisor of ``elem_num``. |
| 46 | """ | 46 | """ |
| 47 | infer_count = 0 | 47 | infer_count = 0 |
| 48 | known = 1 | 48 | known = 1 |
| 49 | for dim in new_shape: | 49 | for dim in new_shape: |
| 50 | if dim == -1: | 50 | if dim == -1: |
| 51 | infer_count += 1 | 51 | infer_count += 1 |
| 52 | - elif dim > 0: | 52 | + elif dim >= 0: |
| 53 | known *= dim | 53 | known *= dim |
| 54 | else: | 54 | else: |
| 55 | - raise ValueError(f"Shape {new_shape} is invalid, only -1 and positive dims are allowed.") | 55 | + raise ValueError(f"Shape {new_shape} is invalid, only -1 and non-negative dims are allowed.") |
| 56 | 56 | ||
| 57 | if infer_count == 0: | 57 | if infer_count == 0: |
| 58 | if known != elem_num: | 58 | if known != elem_num: |
| @@ -60,6 +60,8 @@ def resolve_view_shape(elem_num: int, new_shape: tuple[int, ...]) -> torch.Size: | |||
| 60 | return torch.Size(new_shape) | 60 | return torch.Size(new_shape) |
| 61 | 61 | ||
| 62 | elif infer_count == 1: | 62 | elif infer_count == 1: |
| 63 | + if known == 0: | ||
| 64 | + raise ValueError(f"Shape {new_shape} is invalid for input of size {elem_num}: the -1 dim is ambiguous.") | ||
| 63 | if elem_num % known != 0: | 65 | if elem_num % known != 0: |
| 64 | raise ValueError(f"Shape {new_shape} is invalid for input of size {elem_num}: the -1 dim is not divisible.") | 66 | raise ValueError(f"Shape {new_shape} is invalid for input of size {elem_num}: the -1 dim is not divisible.") |
| 65 | return torch.Size([elem_num // known if dim == -1 else dim for dim in new_shape]) | 67 | return torch.Size([elem_num // known if dim == -1 else dim for dim in new_shape]) |
| @@ -0,0 +1,150 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 2 | +# | ||
| 3 | +# This source code is licensed under the BSD-style license found in the | ||
| 4 | +# LICENSE file in the root directory of this source tree. | ||
| 5 | + | ||
| 6 | +"""CPU coverage for selecting the final CANN MXFP8 dispatcher before build.""" | ||
| 7 | + | ||
| 8 | +from dataclasses import dataclass | ||
| 9 | + | ||
| 10 | +import pytest | ||
| 11 | + | ||
| 12 | +# TorchAO-NPU is an optional dependency of the training plugin: skip at | ||
| 13 | +# collection before the adaptor imports below run. | ||
| 14 | +pytest.importorskip("torchao") | ||
| 15 | +pytest.importorskip("torchao_npu") | ||
| 16 | + | ||
| 17 | +from torchao_npu.configs import ParamSwapConfig | ||
| 18 | +from torchao_npu.quantization.quant_configs import BlockMXQuantizeConfig, MXQuantizeConfig | ||
| 19 | +from torchtitan.config import Configurable, OverrideConfig, apply_overrides | ||
| 20 | +from torchtitan.models.common.linear import GroupedLinear | ||
| 21 | + | ||
| 22 | +from torchtitan_npu.config.configs import QuantizationExtensionConfig | ||
| 23 | +from torchtitan_npu.extensions.adaptor.torchao import converter | ||
| 24 | +from torchtitan_npu.override.common.token_dispatcher import AscDeepEPTokenDispatcher | ||
| 25 | +from torchtitan_npu.patches.torchtitan.models.common.token_dispatcher import ( | ||
| 26 | + AllToAllTokenDispatcher, | ||
| 27 | + DeepEPTokenDispatcher, | ||
| 28 | +) | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +@dataclass(kw_only=True, slots=True) | ||
| 32 | +class _QuantizedGroupedLinearConfig(GroupedLinear.Config): | ||
| 33 | + _torchao_npu_config: ParamSwapConfig | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +@dataclass(kw_only=True, slots=True) | ||
| 37 | +class _ExpertStackConfig(Configurable.Config): | ||
| 38 | + layers: list[Configurable.Config] | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def _experts(): | ||
| 42 | + # Resolve RoutedExperts after torchtitan_npu has installed its patch. | ||
| 43 | + from torchtitan.models.common.moe import RoutedExperts | ||
| 44 | + | ||
| 45 | + # Start after the compute recipe; this test covers communication selection. | ||
| 46 | + param_swap = ParamSwapConfig(activation_config=MXQuantizeConfig(), weight_config=BlockMXQuantizeConfig()) | ||
| 47 | + return RoutedExperts.Config( | ||
| 48 | + token_dispatcher=DeepEPTokenDispatcher.Config( | ||
| 49 | + num_experts=8, | ||
| 50 | + top_k=2, | ||
| 51 | + num_max_tokens_per_rank=64, | ||
| 52 | + hidden_dim=128, | ||
| 53 | + absorb_router_scores=True, | ||
| 54 | + ), | ||
| 55 | + w13=_QuantizedGroupedLinearConfig( | ||
| 56 | + group_size=8, | ||
| 57 | + in_features=128, | ||
| 58 | + out_features=256, | ||
| 59 | + num_linears=2, | ||
| 60 | + _torchao_npu_config=param_swap, | ||
| 61 | + ), | ||
| 62 | + w2=_QuantizedGroupedLinearConfig( | ||
| 63 | + group_size=8, in_features=256, out_features=128, _torchao_npu_config=param_swap | ||
| 64 | + ), | ||
| 65 | + ) | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +@pytest.fixture | ||
| 69 | +def apply_mxfp8(monkeypatch): | ||
| 70 | + monkeypatch.setattr(converter, "_model_type_for_config", lambda cfg: "deepseek_v4") | ||
| 71 | + monkeypatch.setattr(converter, "_recipe_converters", lambda *args, **kwargs: []) | ||
| 72 | + quantization = QuantizationExtensionConfig( | ||
| 73 | + enable_quantized_training=True, recipe="all_block_fp8", all_to_all_quant_format="mxfp8" | ||
| 74 | + ) | ||
| 75 | + | ||
| 76 | + def apply(model, override=None): | ||
| 77 | + return converter.apply_quantization_converter( | ||
| 78 | + model, quantization, model_compile_enabled=False, override_config=override | ||
| 79 | + ) | ||
| 80 | + | ||
| 81 | + return apply | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +@pytest.mark.parametrize("include_override", [False, True], ids=["automatic-cann", "explicit-cann"]) | ||
| 85 | +def test_converter_selects_mxfp8_cann_for_plain_deepep(apply_mxfp8, include_override): | ||
| 86 | + experts = _experts() | ||
| 87 | + override = OverrideConfig( | ||
| 88 | + imports=["torchtitan_npu.override.common.token_dispatcher.asc_deepep"] if include_override else [] | ||
| 89 | + ) | ||
| 90 | + | ||
| 91 | + apply_mxfp8(experts, override) | ||
| 92 | + | ||
| 93 | + dispatcher = experts.token_dispatcher | ||
| 94 | + assert issubclass(type(dispatcher)._owner, AscDeepEPTokenDispatcher) | ||
| 95 | + assert type(dispatcher) is not AscDeepEPTokenDispatcher.Config | ||
| 96 | + assert dispatcher._activation_quant_config is experts.w13._torchao_npu_config.activation_config | ||
| 97 | + assert dispatcher.num_max_tokens_per_rank == 64 | ||
| 98 | + assert dispatcher.absorb_router_scores is True | ||
| 99 | + | ||
| 100 | + # The ordinary Trainer override pass must not discard the final config. | ||
| 101 | + apply_overrides(override, experts) | ||
| 102 | + assert experts.token_dispatcher is dispatcher | ||
| 103 | + | ||
| 104 | + | ||
| 105 | +def test_converter_keeps_already_quantized_dispatcher(apply_mxfp8): | ||
| 106 | + experts = _experts() | ||
| 107 | + apply_mxfp8(experts) | ||
| 108 | + dispatcher = experts.token_dispatcher | ||
| 109 | + | ||
| 110 | + apply_mxfp8(experts) | ||
| 111 | + | ||
| 112 | + assert experts.token_dispatcher is dispatcher | ||
| 113 | + | ||
| 114 | + | ||
| 115 | +def test_converter_rejects_standard_alltoall(apply_mxfp8): | ||
| 116 | + experts = _experts() | ||
| 117 | + experts.token_dispatcher = AllToAllTokenDispatcher.Config(num_experts=8, top_k=2) | ||
| 118 | + | ||
| 119 | + with pytest.raises(ValueError, match="Standard AllToAll is not supported"): | ||
| 120 | + apply_mxfp8(experts) | ||
| 121 | + | ||
| 122 | + | ||
| 123 | +def test_converter_rejects_mixed_dispatcher_families_before_replacing_deepep(apply_mxfp8): | ||
| 124 | + deepep_experts, standard_experts = _experts(), _experts() | ||
| 125 | + original_dispatcher = deepep_experts.token_dispatcher | ||
| 126 | + standard_experts.token_dispatcher = AllToAllTokenDispatcher.Config(num_experts=8, top_k=2) | ||
| 127 | + model = _ExpertStackConfig(layers=[deepep_experts, standard_experts]) | ||
| 128 | + | ||
| 129 | + with pytest.raises(ValueError, match=r"one dispatcher family.*model\.layers\.1\.token_dispatcher"): | ||
| 130 | + apply_mxfp8(model) | ||
| 131 | + | ||
| 132 | + assert deepep_experts.token_dispatcher is original_dispatcher | ||
| 133 | + | ||
| 134 | + | ||
| 135 | +def test_converter_rejects_w2_without_block_mx_compute(apply_mxfp8): | ||
| 136 | + experts = _experts() | ||
| 137 | + experts.w2 = GroupedLinear.Config(group_size=8, in_features=256, out_features=128) | ||
| 138 | + | ||
| 139 | + with pytest.raises(ValueError, match=r"model\.w2: .*Block MX grouped expert compute"): | ||
| 140 | + apply_mxfp8(experts) | ||
| 141 | + | ||
| 142 | + | ||
| 143 | +def test_converter_rejects_a_different_w2_scale_algorithm(apply_mxfp8): | ||
| 144 | + experts = _experts() | ||
| 145 | + experts.w2._torchao_npu_config = ParamSwapConfig( | ||
| 146 | + activation_config=MXQuantizeConfig(scale_alg=0), weight_config=BlockMXQuantizeConfig() | ||
| 147 | + ) | ||
| 148 | + | ||
| 149 | + with pytest.raises(ValueError, match=r"model\.w2 must use the same MXFP8 activation quantizer as w13"): | ||
| 150 | + apply_mxfp8(experts) | ||
| @@ -0,0 +1,72 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 2 | +# | ||
| 3 | +# This source code is licensed under the BSD-style license found in the | ||
| 4 | +# LICENSE file in the root directory of this source tree. | ||
| 5 | + | ||
| 6 | +"""CPU coverage for the high-precision CANN DeepEP override.""" | ||
| 7 | + | ||
| 8 | +from __future__ import annotations | ||
| 9 | + | ||
| 10 | +import pytest | ||
| 11 | + | ||
| 12 | +from torchtitan_npu.config.configs import QuantizationExtensionConfig | ||
| 13 | +from torchtitan_npu.override.common import token_dispatcher as npu_token_dispatcher | ||
| 14 | +from torchtitan_npu.override.common.token_dispatcher import AscDeepEPTokenDispatcher | ||
| 15 | +from torchtitan_npu.patches.torchtitan.models.common.token_dispatcher import ( | ||
| 16 | + DeepEPTokenDispatcher, | ||
| 17 | +) | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def _deep_ep_config() -> DeepEPTokenDispatcher.Config: | ||
| 21 | + return DeepEPTokenDispatcher.Config( | ||
| 22 | + num_experts=8, | ||
| 23 | + top_k=2, | ||
| 24 | + num_max_tokens_per_rank=64, | ||
| 25 | + hidden_dim=128, | ||
| 26 | + ) | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def test_quantization_config_accepts_mxfp8_all_to_all_format(): | ||
| 30 | + config = QuantizationExtensionConfig( | ||
| 31 | + enable_quantized_training=True, | ||
| 32 | + recipe="all_block_fp8", | ||
| 33 | + all_to_all_quant_format="mxfp8", | ||
| 34 | + ) | ||
| 35 | + | ||
| 36 | + config.validate() | ||
| 37 | + | ||
| 38 | + assert config.all_to_all_quant_format == "mxfp8" | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def test_quantization_config_defaults_to_high_precision_all_to_all(): | ||
| 42 | + config = QuantizationExtensionConfig() | ||
| 43 | + | ||
| 44 | + config.validate() | ||
| 45 | + | ||
| 46 | + assert config.all_to_all_quant_format is None | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +def test_quantization_config_rejects_unknown_all_to_all_format(): | ||
| 50 | + config = QuantizationExtensionConfig(all_to_all_quant_format="fp8") # type: ignore[arg-type] | ||
| 51 | + | ||
| 52 | + with pytest.raises(ValueError, match="all_to_all_quant_format must be None or 'mxfp8'"): | ||
| 53 | + config.validate() | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +def test_asc_deepep_keeps_high_precision_dispatch(): | ||
| 57 | + ported = npu_token_dispatcher.asc_deepep(_deep_ep_config()) | ||
| 58 | + | ||
| 59 | + assert type(ported) is AscDeepEPTokenDispatcher.Config | ||
| 60 | + assert not hasattr(ported, "_activation_quant_config") | ||
| 61 | + assert ported._owner is AscDeepEPTokenDispatcher | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +def test_asc_deepep_keeps_an_already_adapted_config(): | ||
| 65 | + adapted = AscDeepEPTokenDispatcher.Config( | ||
| 66 | + num_experts=8, | ||
| 67 | + top_k=2, | ||
| 68 | + num_max_tokens_per_rank=64, | ||
| 69 | + hidden_dim=128, | ||
| 70 | + ) | ||
| 71 | + | ||
| 72 | + assert npu_token_dispatcher.asc_deepep(adapted) is adapted | ||
| @@ -15,7 +15,7 @@ from torch._inductor.custom_graph_pass import get_custom_graph_passes | |||
| 15 | from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode | 15 | from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode |
| 16 | from torchtitan.training_engine import TrainingEngine | 16 | from torchtitan.training_engine import TrainingEngine |
| 17 | 17 | ||
| 18 | -from torchtitan_npu.config.configs import CompileConfig, ModelCompileConfig | 18 | +from torchtitan_npu.config.configs import CompileConfig, ExtensionConfig, ModelCompileConfig |
| 19 | from torchtitan_npu.extensions.compile import sdc_checksum | 19 | from torchtitan_npu.extensions.compile import sdc_checksum |
| 20 | from torchtitan_npu.extensions.components.sdc.sdc import SDC | 20 | from torchtitan_npu.extensions.components.sdc.sdc import SDC |
| 21 | from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx, TrainingEngineEx | 21 | from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx, TrainingEngineEx |
| @@ -410,7 +410,7 @@ def _patch_trainer_sdc_flow(monkeypatch) -> tuple[list[object], TrainerEx.Config | |||
| 410 | compile=None, | 410 | compile=None, |
| 411 | sdc=SimpleNamespace(build=build_sdc), | 411 | sdc=SimpleNamespace(build=build_sdc), |
| 412 | anticipatory=SimpleNamespace(enable=False), | 412 | anticipatory=SimpleNamespace(enable=False), |
| 413 | - extension=SimpleNamespace(quantization=SimpleNamespace(enable_quantized_training=False)), | 413 | + extension=ExtensionConfig(), |
| 414 | training=SimpleNamespace(extension=SimpleNamespace(allow_hf32=True)), | 414 | training=SimpleNamespace(extension=SimpleNamespace(allow_hf32=True)), |
| 415 | ), | 415 | ), |
| 416 | ) | 416 | ) |
| @@ -19,6 +19,7 @@ from torchtitan.observability.profiler import Profiler as _BaseProfiler | |||
| 19 | QuantizationRecipe = Literal["all_mxfp8", "all_hif8", "mix", "all_block_fp8"] | 19 | QuantizationRecipe = Literal["all_mxfp8", "all_hif8", "mix", "all_block_fp8"] |
| 20 | LIQuantization = Literal["mxfp4", "mxfp8", "fp8", "hif8"] | 20 | LIQuantization = Literal["mxfp4", "mxfp8", "fp8", "hif8"] |
| 21 | KVNormQuantization = Literal["mxfp8"] | 21 | KVNormQuantization = Literal["mxfp8"] |
| 22 | +AllToAllQuantFormat = Literal["mxfp8"] | ||
| 22 | 23 | ||
| 23 | 24 | ||
| 24 | @dataclass(kw_only=True, slots=True) | 25 | @dataclass(kw_only=True, slots=True) |
| @@ -136,12 +137,16 @@ class QuantizationExtensionConfig: | |||
| 136 | save_block_ops_level: int = 0 | 137 | save_block_ops_level: int = 0 |
| 137 | """Add attention/mHC/MoE-routing NPU ops to the selective-AC MUST_SAVE | 138 | """Add attention/mHC/MoE-routing NPU ops to the selective-AC MUST_SAVE |
| 138 | list (1-3, cumulative; recipe-independent). Off (0) by default.""" | 139 | list (1-3, cumulative; recipe-independent). Off (0) by default.""" |
| 140 | + all_to_all_quant_format: AllToAllQuantFormat | None = None | ||
| 141 | + """Optional DeepEP activation wire format; ``None`` preserves BF16 communication.""" | ||
| 139 | 142 | ||
| 140 | def validate(self) -> None: | 143 | def validate(self) -> None: |
| 141 | if self.fsdp_prequantize_dtype not in ("fp8", "mxfp4"): | 144 | if self.fsdp_prequantize_dtype not in ("fp8", "mxfp4"): |
| 142 | raise ValueError("fsdp_prequantize_dtype must be fp8 or mxfp4") | 145 | raise ValueError("fsdp_prequantize_dtype must be fp8 or mxfp4") |
| 143 | if self.li_quantization not in (None, "mxfp4", "mxfp8", "fp8", "hif8"): | 146 | if self.li_quantization not in (None, "mxfp4", "mxfp8", "fp8", "hif8"): |
| 144 | raise ValueError("li_quantization must be None or one of: mxfp4, mxfp8, fp8, hif8") | 147 | raise ValueError("li_quantization must be None or one of: mxfp4, mxfp8, fp8, hif8") |
| 148 | + if self.all_to_all_quant_format not in (None, "mxfp8"): | ||
| 149 | + raise ValueError("all_to_all_quant_format must be None or 'mxfp8'") | ||
| 145 | if self.enable_fsdp_prequantize and self.fsdp_prequantize_fqns is not None and not self.fsdp_prequantize_fqns: | 150 | if self.enable_fsdp_prequantize and self.fsdp_prequantize_fqns is not None and not self.fsdp_prequantize_fqns: |
| 146 | raise ValueError( | 151 | raise ValueError( |
| 147 | "fsdp_prequantize_fqns is explicitly empty while enable_fsdp_prequantize is enabled; " | 152 | "fsdp_prequantize_fqns is explicitly empty while enable_fsdp_prequantize is enabled; " |
| @@ -60,6 +60,7 @@ from .filters import ( # noqa: F401 | |||
| 60 | ) | 60 | ) |
| 61 | from .param_swaps import block_fp8_param_swap, mxfp8_param_swap | 61 | from .param_swaps import block_fp8_param_swap, mxfp8_param_swap |
| 62 | from .recipes import ( | 62 | from .recipes import ( |
| 63 | + NpuAllToAllQuantizeConverter, | ||
| 63 | NpuQuantizeConverter, | 64 | NpuQuantizeConverter, |
| 64 | _npu_quantized_module_cache, # noqa: F401 (re-exported for tests) | 65 | _npu_quantized_module_cache, # noqa: F401 (re-exported for tests) |
| 65 | _recipe_converters, | 66 | _recipe_converters, |
| @@ -185,6 +186,9 @@ def apply_quantization_converter( | |||
| 185 | model_config=model_config, | 186 | model_config=model_config, |
| 186 | override_config=override_config, | 187 | override_config=override_config, |
| 187 | ) | 188 | ) |
| 189 | + if quantization_config.all_to_all_quant_format == "mxfp8": | ||
| 190 | + # Communication uses the quantizers installed by the expert compute recipe. | ||
| 191 | + converter_configs = [*converter_configs, NpuAllToAllQuantizeConverter.Config()] | ||
| 188 | validate_converter_compatibility(list(converter_configs)) | 192 | validate_converter_compatibility(list(converter_configs)) |
| 189 | 193 | ||
| 190 | built_converters: list[object] = [] | 194 | built_converters: list[object] = [] |
| @@ -19,9 +19,12 @@ import logging | |||
| 19 | from dataclasses import dataclass, field | 19 | from dataclasses import dataclass, field |
| 20 | from typing import TYPE_CHECKING, Annotated, Literal, TypedDict, cast | 20 | from typing import TYPE_CHECKING, Annotated, Literal, TypedDict, cast |
| 21 | 21 | ||
| 22 | +import torch | ||
| 22 | import tyro | 23 | import tyro |
| 23 | from torchao.core.config import AOBaseConfig # noqa: TC002 | 24 | from torchao.core.config import AOBaseConfig # noqa: TC002 |
| 24 | from torchao.quantization.quant_api import quantize_ | 25 | from torchao.quantization.quant_api import quantize_ |
| 26 | +from torchao_npu.configs import ParamSwapConfig | ||
| 27 | +from torchao_npu.quantization.quant_configs import BlockMXQuantizeConfig, MXQuantizeConfig | ||
| 25 | from torchtitan.config import derive | 28 | from torchtitan.config import derive |
| 26 | from torchtitan.config.transform.quantization import QuantizationConverter | 29 | from torchtitan.config.transform.quantization import QuantizationConverter |
| 27 | 30 | ||
| @@ -32,7 +35,6 @@ from .param_swaps import _is_prequantizing_block_mx, _param_swap_without_prequan | |||
| 32 | logger = logging.getLogger(__name__) | 35 | logger = logging.getLogger(__name__) |
| 33 | 36 | ||
| 34 | if TYPE_CHECKING: | 37 | if TYPE_CHECKING: |
| 35 | - from torchao_npu.configs import ParamSwapConfig | ||
| 36 | from torchtitan.models.base.module import Module | 38 | from torchtitan.models.base.module import Module |
| 37 | 39 | ||
| 38 | from torchtitan_npu.config.configs import KVNormQuantizationConfig, LIQuantization | 40 | from torchtitan_npu.config.configs import KVNormQuantizationConfig, LIQuantization |
| @@ -306,6 +308,110 @@ class NpuQuantizeConverter(QuantizationConverter): | |||
| 306 | return model_config | 308 | return model_config |
| 307 | 309 | ||
| 308 | 310 | ||
| 311 | +class NpuAllToAllQuantizeConverter(QuantizationConverter): | ||
| 312 | + """Replace only the EP dispatcher; routed experts keep their own quantizer. | ||
| 313 | + | ||
| 314 | + The wire format is the experts' activation quantizer, so this converter runs | ||
| 315 | + after the recipe has quantized ``w13``/``w2``. Only the DeepEP backend is | ||
| 316 | + ported on this branch; a Standard all-to-all dispatcher fails fast instead of | ||
| 317 | + silently falling back to a high-precision exchange. | ||
| 318 | + """ | ||
| 319 | + | ||
| 320 | + @dataclass(kw_only=True, slots=True) | ||
| 321 | + class Config(QuantizationConverter.Config): | ||
| 322 | + pass | ||
| 323 | + | ||
| 324 | + def __init__(self, config: Config) -> None: | ||
| 325 | + self.config = config | ||
| 326 | + | ||
| 327 | + @staticmethod | ||
| 328 | + def _resolve_dispatcher_factory(routed_config, fqn): | ||
| 329 | + from torchtitan.models.common.moe.token_dispatcher import AllToAllTokenDispatcher, DeepEPTokenDispatcher | ||
| 330 | + | ||
| 331 | + dispatcher_config = routed_config.token_dispatcher | ||
| 332 | + if isinstance(dispatcher_config, DeepEPTokenDispatcher.Config): | ||
| 333 | + from .token_dispatcher import resolve_mxfp8_deepep_dispatcher_factory | ||
| 334 | + | ||
| 335 | + return DeepEPTokenDispatcher.Config, resolve_mxfp8_deepep_dispatcher_factory(routed_config) | ||
| 336 | + if isinstance(dispatcher_config, AllToAllTokenDispatcher.Config): | ||
| 337 | + raise ValueError(f"MXFP8 communication for Standard AllToAll is not supported at {fqn}.token_dispatcher") | ||
| 338 | + raise ValueError( | ||
| 339 | + f"MXFP8 communication does not support {type(dispatcher_config).__qualname__} at {fqn}.token_dispatcher" | ||
| 340 | + ) | ||
| 341 | + | ||
| 342 | + @staticmethod | ||
| 343 | + def _expert_activation_config(param_swap: ParamSwapConfig | None, path: str) -> MXQuantizeConfig: | ||
| 344 | + if not isinstance(param_swap, ParamSwapConfig) or not isinstance( | ||
| 345 | + param_swap.weight_config, BlockMXQuantizeConfig | ||
| 346 | + ): | ||
| 347 | + raise ValueError(f"{path}: MXFP8 all-to-all requires Block MX grouped expert compute") | ||
| 348 | + config = param_swap.activation_config | ||
| 349 | + if not isinstance(config, MXQuantizeConfig) or config.elem_dtype is not torch.float8_e4m3fn: | ||
| 350 | + raise ValueError(f"{path}: MXFP8 all-to-all requires an E4M3 MX activation config on the experts") | ||
| 351 | + return config | ||
| 352 | + | ||
| 353 | + def convert(self, model_config): | ||
| 354 | + from torchtitan.models.common.moe import RoutedExperts | ||
| 355 | + | ||
| 356 | + routed_configs = list(model_config.traverse(RoutedExperts.Config)) | ||
| 357 | + if not routed_configs: | ||
| 358 | + raise ValueError("all_to_all_quant_format='mxfp8' requires RoutedExperts nodes") | ||
| 359 | + | ||
| 360 | + first_fqn, first_routed_config, _, _ = routed_configs[0] | ||
| 361 | + dispatcher_family, dispatcher_factory = self._resolve_dispatcher_factory( | ||
| 362 | + first_routed_config, f"model.{first_fqn}" if first_fqn else "model" | ||
| 363 | + ) | ||
| 364 | + replacements = [] | ||
| 365 | + for fqn, routed_config, _, _ in routed_configs: | ||
| 366 | + expert_path = f"model.{fqn}" if fqn else "model" | ||
| 367 | + dispatcher_config = routed_config.token_dispatcher | ||
| 368 | + if not isinstance(dispatcher_config, dispatcher_family): | ||
| 369 | + raise ValueError( | ||
| 370 | + "MXFP8 communication requires one dispatcher family per model; " | ||
| 371 | + f"{expert_path}.token_dispatcher is {type(dispatcher_config).__qualname__}, " | ||
| 372 | + f"expected {dispatcher_family.__qualname__}" | ||
| 373 | + ) | ||
| 374 | + try: | ||
| 375 | + quantized_dispatcher = dispatcher_factory(type(dispatcher_config)._owner) | ||
| 376 | + except ValueError as error: | ||
| 377 | + raise ValueError(f"{expert_path}.token_dispatcher: {error}") from error | ||
| 378 | + | ||
| 379 | + w13_swap = getattr(routed_config.w13, "_torchao_npu_config", None) | ||
| 380 | + w2_swap = getattr(routed_config.w2, "_torchao_npu_config", None) | ||
| 381 | + activation_config = self._expert_activation_config(w13_swap, f"{expert_path}.w13") | ||
| 382 | + if w2_swap is not w13_swap: | ||
| 383 | + w2_activation_config = self._expert_activation_config(w2_swap, f"{expert_path}.w2") | ||
| 384 | + # Dataclass equality excludes rounding and the scale algorithm. | ||
| 385 | + if w2_activation_config is not activation_config and ( | ||
| 386 | + w2_activation_config != activation_config | ||
| 387 | + or w2_activation_config.round_mode != activation_config.round_mode | ||
| 388 | + or w2_activation_config.scale_alg != activation_config.scale_alg | ||
| 389 | + ): | ||
| 390 | + raise ValueError(f"{expert_path}.w2 must use the same MXFP8 activation quantizer as w13") | ||
| 391 | + | ||
| 392 | + if ( | ||
| 393 | + type(dispatcher_config) is quantized_dispatcher.Config | ||
| 394 | + and getattr(dispatcher_config, "_activation_quant_config", None) is activation_config | ||
| 395 | + ): | ||
| 396 | + continue | ||
| 397 | + replacement = derive( | ||
| 398 | + dispatcher_config, quantized_dispatcher.Config, _activation_quant_config=activation_config | ||
| 399 | + ) | ||
| 400 | + replacements.append((expert_path, routed_config, dispatcher_config, replacement)) | ||
| 401 | + | ||
| 402 | + replacement_logger = GroupedConverterLogger(self) | ||
| 403 | + for expert_path, routed_config, dispatcher_config, replacement in replacements: | ||
| 404 | + routed_config.token_dispatcher = replacement | ||
| 405 | + replacement_logger.record( | ||
| 406 | + f"{type(dispatcher_config).__qualname__} -> {type(replacement).__qualname__}", | ||
| 407 | + f"{expert_path}.token_dispatcher", | ||
| 408 | + ) | ||
| 409 | + | ||
| 410 | + replacement_logger.flush() | ||
| 411 | + logger.info("Installed torchao-npu MXFP8 communication on %d dispatcher node(s)", len(replacements)) | ||
| 412 | + return model_config | ||
| 413 | + | ||
| 414 | + | ||
| 309 | def _get_configs(modules_dict): | 415 | def _get_configs(modules_dict): |
| 310 | configs = set() | 416 | configs = set() |
| 311 | for cls in modules_dict.values(): | 417 | for cls in modules_dict.values(): |
| @@ -0,0 +1,215 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# | ||
| 3 | +# This source code is licensed under the BSD-style license found in the | ||
| 4 | +# LICENSE file in the root directory of this source tree. | ||
| 5 | + | ||
| 6 | +"""Adapt TorchAO-NPU communication quantization to EP token dispatchers.""" | ||
| 7 | + | ||
| 8 | +from __future__ import annotations | ||
| 9 | + | ||
| 10 | +__all__ = ["get_mxfp8_deepep_dispatcher_cls", "resolve_mxfp8_deepep_dispatcher_factory"] | ||
| 11 | + | ||
| 12 | +from copy import copy | ||
| 13 | +from dataclasses import dataclass | ||
| 14 | +from typing import TYPE_CHECKING, cast | ||
| 15 | + | ||
| 16 | +import torch | ||
| 17 | +from torchao_npu.ops.mxfp8_deepep_payload import ( | ||
| 18 | + DequantizeGradient, | ||
| 19 | + dequantize_if_mxfp8, | ||
| 20 | + quantize_payload, | ||
| 21 | + wire_tensor, | ||
| 22 | +) | ||
| 23 | +from torchtitan.config import OverrideConfig, apply_overrides, derive | ||
| 24 | + | ||
| 25 | +if TYPE_CHECKING: | ||
| 26 | + from torchao_npu.quantization.quant_configs import MXQuantizeConfig | ||
| 27 | + from torchtitan.models.common.moe.token_dispatcher import DeepEPTokenDispatcher | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def resolve_mxfp8_deepep_dispatcher_factory(routed_config): | ||
| 31 | + """Resolve CANN once through the public override without mutating the model tree.""" | ||
| 32 | + from torchtitan.models.common.moe.token_dispatcher import DeepEPTokenDispatcher | ||
| 33 | + | ||
| 34 | + probe = copy(routed_config) | ||
| 35 | + if type(probe.token_dispatcher) is not DeepEPTokenDispatcher.Config: | ||
| 36 | + probe.token_dispatcher = derive(probe.token_dispatcher, DeepEPTokenDispatcher.Config) | ||
| 37 | + apply_overrides( | ||
| 38 | + OverrideConfig(imports=["torchtitan_npu.override.common.token_dispatcher.asc_deepep"]), | ||
| 39 | + probe, | ||
| 40 | + ) | ||
| 41 | + owner = type(probe.token_dispatcher)._owner | ||
| 42 | + if owner is None or owner is DeepEPTokenDispatcher: | ||
| 43 | + raise ValueError("Could not resolve the CANN DeepEP dispatcher for MXFP8 communication") | ||
| 44 | + cann_cls = cast("type[DeepEPTokenDispatcher]", owner) | ||
| 45 | + | ||
| 46 | + def factory(parent_cls: type | None) -> type[DeepEPTokenDispatcher]: | ||
| 47 | + if parent_cls is DeepEPTokenDispatcher: | ||
| 48 | + parent_cls = cann_cls | ||
| 49 | + if parent_cls is None or not issubclass(parent_cls, cann_cls): | ||
| 50 | + raise ValueError(f"MXFP8 DeepEP requires a CANN DeepEP dispatcher, got {parent_cls}") | ||
| 51 | + # ``get_mxfp8_deepep_dispatcher_cls`` already caches one class per dispatcher. | ||
| 52 | + return get_mxfp8_deepep_dispatcher_cls(parent_cls) | ||
| 53 | + | ||
| 54 | + return factory | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +class _MXFP8DeepEPDispatch(torch.autograd.Function): | ||
| 58 | + """Communicate FP8 activations forward and high-precision input gradients backward.""" | ||
| 59 | + | ||
| 60 | + @staticmethod | ||
| 61 | + def forward( # pyrefly: ignore [bad-override] | ||
| 62 | + ctx, | ||
| 63 | + activation, | ||
| 64 | + recv_qdata, | ||
| 65 | + recv_scale, | ||
| 66 | + recv_scores, | ||
| 67 | + counts, | ||
| 68 | + topk_idx, | ||
| 69 | + topk_scores, | ||
| 70 | + handle, | ||
| 71 | + buffer, | ||
| 72 | + quant_config, | ||
| 73 | + ): | ||
| 74 | + ctx.save_for_backward(topk_idx) | ||
| 75 | + ctx.handle, ctx.buffer = handle, buffer | ||
| 76 | + ctx.input_dtype, ctx.hidden = activation.dtype, activation.shape[1] | ||
| 77 | + ctx.set_materialize_grads(False) | ||
| 78 | + ctx.mark_non_differentiable(counts) | ||
| 79 | + routed = wire_tensor( | ||
| 80 | + recv_qdata, | ||
| 81 | + recv_scale, | ||
| 82 | + activation.dtype, | ||
| 83 | + quant_config, | ||
| 84 | + activation.requires_grad, | ||
| 85 | + ) | ||
| 86 | + return routed, recv_scores, counts | ||
| 87 | + | ||
| 88 | + @staticmethod | ||
| 89 | + def backward(ctx, grad_routed, grad_scores, grad_counts): # pyrefly: ignore [bad-override] | ||
| 90 | + if grad_routed is None and grad_scores is None: | ||
| 91 | + return (None,) * 10 | ||
| 92 | + | ||
| 93 | + has_grad_routed = grad_routed is not None | ||
| 94 | + has_grad_scores = grad_scores is not None | ||
| 95 | + if grad_routed is None: | ||
| 96 | + grad_routed = grad_scores.new_zeros((grad_scores.numel(), ctx.hidden), dtype=ctx.input_dtype) | ||
| 97 | + else: | ||
| 98 | + grad_routed = dequantize_if_mxfp8(grad_routed) | ||
| 99 | + if grad_scores is None: | ||
| 100 | + grad_scores = grad_routed.new_empty((0,), dtype=torch.float32) | ||
| 101 | + (topk_idx,) = ctx.saved_tensors | ||
| 102 | + grad_x, grad_topk_weights = torch.ops.deepep.dispatch_backward( | ||
| 103 | + grad_routed, grad_scores, has_grad_scores, topk_idx, ctx.handle, ctx.buffer | ||
| 104 | + ) | ||
| 105 | + # qdata/scale/received-score/counts are communication outputs; their VJP is | ||
| 106 | + # consumed here, while the input router score receives the routed gradient. | ||
| 107 | + return ( | ||
| 108 | + grad_x.to(ctx.input_dtype) if has_grad_routed else None, | ||
| 109 | + None, | ||
| 110 | + None, | ||
| 111 | + None, | ||
| 112 | + None, | ||
| 113 | + None, | ||
| 114 | + grad_topk_weights if has_grad_scores else None, | ||
| 115 | + None, | ||
| 116 | + None, | ||
| 117 | + None, | ||
| 118 | + ) | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +class _MXFP8DeepEPCombine(torch.autograd.Function): | ||
| 122 | + """Keep forward reduction in BF16/FP16; use a cached FP8 dispatch for its VJP.""" | ||
| 123 | + | ||
| 124 | + @staticmethod | ||
| 125 | + def forward( # pyrefly: ignore [bad-override] | ||
| 126 | + ctx, activation, num_permuted_tokens_src, handle, num_tokens, buffer, quant_config | ||
| 127 | + ): | ||
| 128 | + activation = dequantize_if_mxfp8(activation) | ||
| 129 | + ctx.handle, ctx.buffer, ctx.quant_config = handle, buffer, quant_config | ||
| 130 | + # Only the dispatch-produced row count is needed in compiled backward. | ||
| 131 | + # Score multiplication and its saved tensors belong to the caller's graph. | ||
| 132 | + ctx.save_for_backward(num_permuted_tokens_src) | ||
| 133 | + return torch.ops.deepep.combine(activation, handle, num_tokens, num_permuted_tokens_src, buffer) | ||
| 134 | + | ||
| 135 | + @staticmethod | ||
| 136 | + def backward(ctx, grad_output): # pyrefly: ignore [bad-override] | ||
| 137 | + (num_permuted_tokens_src,) = ctx.saved_tensors | ||
| 138 | + qdata, scale = quantize_payload(grad_output, ctx.quant_config) | ||
| 139 | + recv_qdata, recv_scale = torch.ops.deepep.dispatch_quantized_cached( | ||
| 140 | + qdata, scale, ctx.handle, num_permuted_tokens_src.shape[0], ctx.buffer | ||
| 141 | + ) | ||
| 142 | + grad_input = wire_tensor(recv_qdata, recv_scale, grad_output.dtype, ctx.quant_config, grad_output.requires_grad) | ||
| 143 | + # The row-count source is metadata, not a differentiable combine operand. | ||
| 144 | + return grad_input, None, None, None, None, None | ||
| 145 | + | ||
| 146 | + | ||
| 147 | +_mxfp8_deepep_dispatchers: dict[type[DeepEPTokenDispatcher], type[DeepEPTokenDispatcher]] = {} | ||
| 148 | + | ||
| 149 | + | ||
| 150 | +def get_mxfp8_deepep_dispatcher_cls(parent_cls: type[DeepEPTokenDispatcher]) -> type[DeepEPTokenDispatcher]: | ||
| 151 | + """Specialize the CANN dispatcher selected by the high-precision override.""" | ||
| 152 | + if parent_cls in _mxfp8_deepep_dispatchers: | ||
| 153 | + return _mxfp8_deepep_dispatchers[parent_cls] | ||
| 154 | + parent_config_cls = parent_cls.Config | ||
| 155 | + | ||
| 156 | + class MXFP8DeepEPTokenDispatcher(parent_cls): # type: ignore[valid-type, misc] | ||
| 157 | + @dataclass(kw_only=True, slots=True) | ||
| 158 | + class Config(parent_config_cls): # type: ignore[valid-type, misc] | ||
| 159 | + _activation_quant_config: MXQuantizeConfig | ||
| 160 | + | ||
| 161 | + def __init__(self, config: Config) -> None: | ||
| 162 | + super().__init__(config) | ||
| 163 | + self.activation_quant_config = config._activation_quant_config | ||
| 164 | + | ||
| 165 | + def dispatch_activation_exchange( | ||
| 166 | + self, x_td, topk_expert_ids_tk, topk_scores_tk, num_experts: int, num_local_experts: int, buffer | ||
| 167 | + ): | ||
| 168 | + # Transport produces detached payloads; the Function below owns the | ||
| 169 | + # logical activation/score VJP. Keep the original x and scores for apply. | ||
| 170 | + # This also avoids requiring autograd formulas on raw FP8/uint8 ops. | ||
| 171 | + with torch.no_grad(): | ||
| 172 | + qdata, scale = quantize_payload(x_td, self.activation_quant_config) | ||
| 173 | + recv_qdata, recv_scale, recv_scores, counts, handle = torch.ops.deepep.dispatch_quantized( | ||
| 174 | + qdata, | ||
| 175 | + scale, | ||
| 176 | + topk_expert_ids_tk, | ||
| 177 | + topk_scores_tk, | ||
| 178 | + num_experts, | ||
| 179 | + num_local_experts, | ||
| 180 | + buffer, | ||
| 181 | + ) | ||
| 182 | + routed, recv_scores, counts = _MXFP8DeepEPDispatch.apply( | ||
| 183 | + x_td, | ||
| 184 | + recv_qdata, | ||
| 185 | + recv_scale, | ||
| 186 | + recv_scores, | ||
| 187 | + counts, | ||
| 188 | + topk_expert_ids_tk, | ||
| 189 | + topk_scores_tk, | ||
| 190 | + handle, | ||
| 191 | + buffer, | ||
| 192 | + self.activation_quant_config, | ||
| 193 | + ) | ||
| 194 | + return routed, recv_scores, counts, handle | ||
| 195 | + | ||
| 196 | + def combine_activation_exchange(self, routed_output_rd, metadata, num_tokens, buffer): | ||
| 197 | + # The parent combine already applied scores using ordinary autograd. | ||
| 198 | + # MulBackward needs a plain tensor; experts with pre-W2 absorption | ||
| 199 | + # can consume the MXTensor gradient directly and reuse its FP8 data. | ||
| 200 | + if not self.absorb_router_scores: # pyrefly: ignore [missing-attribute] | ||
| 201 | + routed_output_rd = DequantizeGradient.apply(routed_output_rd) | ||
| 202 | + return _MXFP8DeepEPCombine.apply( | ||
| 203 | + routed_output_rd, | ||
| 204 | + metadata.recv_scores, | ||
| 205 | + metadata.handle, | ||
| 206 | + num_tokens, | ||
| 207 | + buffer, | ||
| 208 | + self.activation_quant_config, | ||
| 209 | + ) | ||
| 210 | + | ||
| 211 | + MXFP8DeepEPTokenDispatcher.__name__ = f"MXFP8{parent_cls.__name__}" | ||
| 212 | + MXFP8DeepEPTokenDispatcher.__qualname__ = f"MXFP8{parent_cls.__qualname__}" | ||
| 213 | + _mxfp8_deepep_dispatchers[parent_cls] = MXFP8DeepEPTokenDispatcher | ||
| 214 | + _mxfp8_deepep_dispatchers[MXFP8DeepEPTokenDispatcher] = MXFP8DeepEPTokenDispatcher | ||
| 215 | + return MXFP8DeepEPTokenDispatcher | ||
| @@ -231,6 +231,8 @@ class TrainerEx(Trainer): | |||
| 231 | config = copy(config) | 231 | config = copy(config) |
| 232 | config.activation_remat = policy | 232 | config.activation_remat = policy |
| 233 | self.activation_offload = policy.manager | 233 | self.activation_offload = policy.manager |
| 234 | + if config.extension.quantization.all_to_all_quant_format is not None and config._supports_graph_compile: | ||
| 235 | + raise NotImplementedError("MXFP8 all-to-all requires eager training; GraphTrainer is unsupported") | ||
| 234 | quantization_config = config.extension.quantization | 236 | quantization_config = config.extension.quantization |
| 235 | if quantization_config.enable_quantized_training: | 237 | if quantization_config.enable_quantized_training: |
| 236 | from torchtitan_npu.extensions.adaptor.torchao.converter import apply_quantization_converter | 238 | from torchtitan_npu.extensions.adaptor.torchao.converter import apply_quantization_converter |
| @@ -120,6 +120,93 @@ def _dispatch_fake( | |||
| 120 | ) | 120 | ) |
| 121 | 121 | ||
| 122 | 122 | ||
| 123 | +@torch.library.custom_op("deepep::dispatch_quantized", mutates_args=(), device_types="npu") | ||
| 124 | +def _dispatch_quantized_op_impl( | ||
| 125 | + qdata: torch.Tensor, | ||
| 126 | + scale: torch.Tensor, | ||
| 127 | + topk_idx: torch.Tensor, | ||
| 128 | + topk_weights: torch.Tensor, | ||
| 129 | + num_experts: int, | ||
| 130 | + num_local_experts: int, | ||
| 131 | + buffer: ElasticBufferHandle, | ||
| 132 | +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, DispatchHandle]: | ||
| 133 | + """Transport a pre-quantized payload; the caller owns its autograd.""" | ||
| 134 | + recv_payload, _, recv_scores, handle = buffer.value.dispatch( | ||
| 135 | + (qdata.contiguous(), scale.contiguous()), | ||
| 136 | + topk_idx=topk_idx.contiguous(), | ||
| 137 | + topk_weights=topk_weights.contiguous(), | ||
| 138 | + num_experts=num_experts, | ||
| 139 | + # Non-cached dispatch needs the exact receive count before allocating outputs. | ||
| 140 | + do_cpu_sync=True, | ||
| 141 | + ) | ||
| 142 | + if not isinstance(recv_payload, tuple) or len(recv_payload) != 2: | ||
| 143 | + raise RuntimeError("ElasticBuffer must support tuple (qdata, scale) dispatch; rebuild the CANN ops and wheel") | ||
| 144 | + recv_qdata, recv_scale = recv_payload | ||
| 145 | + return ( | ||
| 146 | + recv_qdata, | ||
| 147 | + recv_scale, | ||
| 148 | + cast("torch.Tensor", recv_scores), | ||
| 149 | + handle.num_recv_tokens_per_expert, | ||
| 150 | + DispatchHandle(value=handle), | ||
| 151 | + ) | ||
| 152 | + | ||
| 153 | + | ||
| 154 | +@_dispatch_quantized_op_impl.register_fake | ||
| 155 | +def _dispatch_quantized_fake( | ||
| 156 | + qdata: torch.Tensor, | ||
| 157 | + scale: torch.Tensor, | ||
| 158 | + topk_idx: torch.Tensor, | ||
| 159 | + topk_weights: torch.Tensor, | ||
| 160 | + num_experts: int, | ||
| 161 | + num_local_experts: int, | ||
| 162 | + buffer: ElasticBufferHandle, | ||
| 163 | +): | ||
| 164 | + # Payload tensors and scores all follow the same data-dependent route. | ||
| 165 | + num_recv = torch.library.get_ctx().new_dynamic_size() | ||
| 166 | + return ( | ||
| 167 | + qdata.new_empty((num_recv, qdata.shape[1])), | ||
| 168 | + scale.new_empty((num_recv, scale.shape[1])), | ||
| 169 | + qdata.new_empty((num_recv,), dtype=torch.float32), | ||
| 170 | + qdata.new_empty((num_local_experts,), dtype=torch.int64), | ||
| 171 | + DispatchHandle(), | ||
| 172 | + ) | ||
| 173 | + | ||
| 174 | + | ||
| 175 | +@torch.library.custom_op("deepep::dispatch_quantized_cached", mutates_args=(), device_types="npu") | ||
| 176 | +def _dispatch_quantized_cached_op_impl( | ||
| 177 | + qdata: torch.Tensor, | ||
| 178 | + scale: torch.Tensor, | ||
| 179 | + handle: DispatchHandle, | ||
| 180 | + num_permuted_tokens: int, | ||
| 181 | + buffer: ElasticBufferHandle, | ||
| 182 | +) -> tuple[torch.Tensor, torch.Tensor]: | ||
| 183 | + """Reuse routing inside combine's first-order VJP; no payload autograd.""" | ||
| 184 | + recv_payload, _, _, _ = buffer.value.dispatch( | ||
| 185 | + (qdata.contiguous(), scale.contiguous()), | ||
| 186 | + handle=handle.value, | ||
| 187 | + # Both payloads follow the original route, with no new count synchronization. | ||
| 188 | + do_cpu_sync=False, | ||
| 189 | + ) | ||
| 190 | + if not isinstance(recv_payload, tuple) or len(recv_payload) != 2: | ||
| 191 | + raise RuntimeError("ElasticBuffer cached dispatch must return (qdata, scale)") | ||
| 192 | + return recv_payload | ||
| 193 | + | ||
| 194 | + | ||
| 195 | +@_dispatch_quantized_cached_op_impl.register_fake | ||
| 196 | +def _dispatch_quantized_cached_fake( | ||
| 197 | + qdata: torch.Tensor, | ||
| 198 | + scale: torch.Tensor, | ||
| 199 | + handle: DispatchHandle, | ||
| 200 | + num_permuted_tokens: int, | ||
| 201 | + buffer: ElasticBufferHandle, | ||
| 202 | +): | ||
| 203 | + # Use the saved dispatch score tensor's row count, as the BF16 path does. | ||
| 204 | + return ( | ||
| 205 | + qdata.new_empty((num_permuted_tokens, qdata.shape[1])), | ||
| 206 | + scale.new_empty((num_permuted_tokens, scale.shape[1])), | ||
| 207 | + ) | ||
| 208 | + | ||
| 209 | + | ||
| 123 | @torch.library.custom_op("deepep::combine", mutates_args=(), device_types="npu") | 210 | @torch.library.custom_op("deepep::combine", mutates_args=(), device_types="npu") |
| 124 | def _combine_op_impl( | 211 | def _combine_op_impl( |
| 125 | x: torch.Tensor, | 212 | x: torch.Tensor, |
| @@ -446,7 +446,7 @@ class AscDeepEPTokenDispatcher(DeepEPTokenDispatcher): | |||
| 446 | recv_scores, | 446 | recv_scores, |
| 447 | num_global_tokens_per_local_expert_e, | 447 | num_global_tokens_per_local_expert_e, |
| 448 | handle, | 448 | handle, |
| 449 | - ) = torch.ops.deepep.dispatch( | 449 | + ) = self.dispatch_activation_exchange( |
| 450 | x_TD, | 450 | x_TD, |
| 451 | topk_expert_ids_TK, | 451 | topk_expert_ids_TK, |
| 452 | topk_scores_TK, | 452 | topk_scores_TK, |
| @@ -464,6 +464,25 @@ class AscDeepEPTokenDispatcher(DeepEPTokenDispatcher): | |||
| 464 | ), | 464 | ), |
| 465 | ) | 465 | ) |
| 466 | 466 | ||
| 467 | + def dispatch_activation_exchange( | ||
| 468 | + self, | ||
| 469 | + x_td: torch.Tensor, | ||
| 470 | + topk_expert_ids_tk: torch.Tensor, | ||
| 471 | + topk_scores_tk: torch.Tensor, | ||
| 472 | + num_experts: int, | ||
| 473 | + num_local_experts: int, | ||
| 474 | + buffer: "ElasticBufferHandle", | ||
| 475 | + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, "DispatchHandle"]: | ||
| 476 | + """Exchange activations and routing metadata on the DeepEP group.""" | ||
| 477 | + return torch.ops.deepep.dispatch( | ||
| 478 | + x_td, | ||
| 479 | + topk_expert_ids_tk, | ||
| 480 | + topk_scores_tk, | ||
| 481 | + num_experts, | ||
| 482 | + num_local_experts, | ||
| 483 | + buffer, | ||
| 484 | + ) | ||
| 485 | + | ||
| 467 | # pyrefly: ignore [bad-override] | 486 | # pyrefly: ignore [bad-override] |
| 468 | def combine( | 487 | def combine( |
| 469 | self, | 488 | self, |
| @@ -480,15 +499,20 @@ class AscDeepEPTokenDispatcher(DeepEPTokenDispatcher): | |||
| 480 | weighted_states = routed_output_RD | 499 | weighted_states = routed_output_RD |
| 481 | if not self.absorb_router_scores: | 500 | if not self.absorb_router_scores: |
| 482 | weighted_states = routed_output_RD * metadata.recv_scores.to(routed_output_RD.dtype).reshape(-1, 1) | 501 | weighted_states = routed_output_RD * metadata.recv_scores.to(routed_output_RD.dtype).reshape(-1, 1) |
| 483 | - combined_TD = torch.ops.deepep.combine( | 502 | + return self.combine_activation_exchange(weighted_states, metadata, x_TD.shape[0], self._deepep_buffer_handle) |
| 484 | - weighted_states, | 503 | + |
| 504 | + def combine_activation_exchange( | ||
| 505 | + self, routed_output_rd: torch.Tensor, metadata: DispatchState, num_tokens: int, buffer: "ElasticBufferHandle" | ||
| 506 | + ) -> torch.Tensor: | ||
| 507 | + """Combine routed activations after any router score weighting.""" | ||
| 508 | + return torch.ops.deepep.combine( | ||
| 509 | + routed_output_rd, | ||
| 485 | metadata.handle, | 510 | metadata.handle, |
| 486 | - x_TD.shape[0], | 511 | + num_tokens, |
| 487 | # Preserve the dispatch row-count source for compiled backward. | 512 | # Preserve the dispatch row-count source for compiled backward. |
| 488 | metadata.recv_scores, | 513 | metadata.recv_scores, |
| 489 | - self._deepep_buffer_handle, | 514 | + buffer, |
| 490 | ) | 515 | ) |
| 491 | - return combined_TD | ||
| 492 | 516 | ||
| 493 | 517 | ||
| 494 | @override( | 518 | @override( |
| @@ -509,5 +533,7 @@ def asc( | |||
| 509 | def asc_deepep( | 533 | def asc_deepep( |
| 510 | cfg: DeepEPTokenDispatcher.Config, | 534 | cfg: DeepEPTokenDispatcher.Config, |
| 511 | ) -> AscDeepEPTokenDispatcher.Config: | 535 | ) -> AscDeepEPTokenDispatcher.Config: |
| 512 | - """Select the CANN implementation for a DeepEP config.""" | 536 | + """Select the CANN implementation without replacing an already adapted config.""" |
| 537 | + if isinstance(cfg, AscDeepEPTokenDispatcher.Config): | ||
| 538 | + return cfg | ||
| 513 | return derive(cfg, AscDeepEPTokenDispatcher.Config) | 539 | return derive(cfg, AscDeepEPTokenDispatcher.Config) |