Skip to content

Commit 8a4ad5f

Browse files
yhl-amdclaude
andcommitted
perf(dsv41): FFN seam writes the shared expert's MXFP8 input, no quantize launch before shared_in
On a DeepSeek-V4.1 target layer whose routed MegaMoE call computes the shared expert (AITER shared_in, #3894), the call still launched quantize_fp8(x) on every fused decode step to make the shared expert's MXFP8 input. x is the FFN seam's normed output, and the FFN seam's Mega-MHC launch can already write that pair next to the BF16 rows (mega_mhc(out_dtype="mxfp8"), what the attention seam uses for wqkv_a). - mhc_pre_delayed: pre_delayed / v41_mhc_pre_delayed take ffn_pair. When set, on the HIP backend with row-major scales and for rows up to AITER's small-input ceiling (SMALL_M_MAX_MTPR, the only route that fuses the shared expert), the seam asks mega_mhc for MXFP8 output and leaves (fp8, e8m0) in a one-entry slot. Its return value is unchanged (BF16 only), so the op signature and fake shapes stay as they are. Every other seam clears the slot; take_ffn_pair(x) takes it and hands it out only for those very rows. - Block: hc_ffn_pair is set where the FFN is a shared_in layer (draft layers never are) and passed by prepare_ffn. - flydsl_mega_experts: the shared_in input takes the seam's pair when there is one; otherwise x is quantized lazily as before. The pair is bit for bit quantize_fp8 of the BF16 norm (E4M3, one E8M0 ceil scale per 32 columns), and the BF16 outputs are bit for bit the BF16-only seam's. No new switch or environment variable. Tests: tests/model_ops/test_mhc_pre_delayed_backend.py (when the seam writes the pair, only for its own rows, cleared by other seams), tests/test_mega_shared_in.py (the pair replaces the quantize launch). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 9330287 commit 8a4ad5f

6 files changed

Lines changed: 198 additions & 7 deletions

File tree

‎atom/model_ops/deepseek_v41/mhc_pre_delayed.py‎

Lines changed: 64 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@
1212
stay on Triton. ATOM_DSV41_MHC_BACKEND=triton forces Triton everywhere.
1313
1414
The norm is the sublayer's own. Attention can request HIP's fused MXFP8
15-
output alongside BF16 for its other readers; FFN keeps the BF16 interface.
15+
output alongside BF16 for its other readers; FFN keeps the BF16 interface and
16+
can leave the same MXFP8 pair beside it for the shared expert (`ffn_pair`,
17+
`take_ffn_pair`).
1618
Its consumers (wqkv_a's group32 GEMM, the bounded-replay row gather) read
1719
row-major (T, H/32) E8M0 scales. gfx950 writes those; gfx1250 writes its
1820
m32k4 GEMM A-scale layout unless asked for `scale_row_major`, which ATOM
@@ -65,6 +67,47 @@ def fuse_quant_supported() -> bool:
6567
return _row_major_scale_options() is not None
6668

6769

70+
# The FFN seam's MXFP8 pair of its normed rows, for the shared expert that
71+
# reads the same rows: today the routed MegaMoE call that computes it
72+
# (shared_in), which otherwise launches quantize_fp8(x) itself. The MoE custom
73+
# op takes only the BF16 rows, so the pair goes beside it in one slot: set by
74+
# an FFN seam asked for it, cleared by every other seam, taken (and cleared) by
75+
# the next reader, and handed out only when that reader's input is this very
76+
# tensor. The pair is bit for bit quantize_fp8 of the normed rows (E4M3 with
77+
# one E8M0 scale per 32 columns, row-major).
78+
_FFN_PAIR = [None]
79+
80+
81+
@cache
82+
def _ffn_pair_max_rows() -> int:
83+
"""Rows up to which a shared_in call can fuse the shared expert (AITER's
84+
small-input route); above it the dense shared expert quantizes x itself,
85+
so the seam keeps its BF16-only output."""
86+
try:
87+
from aiter.ops.flydsl.kernels.mega_moe.mega_moe_config import SMALL_M_MAX_MTPR
88+
except ImportError:
89+
return 0
90+
return int(SMALL_M_MAX_MTPR)
91+
92+
93+
def take_ffn_pair(x: torch.Tensor):
94+
"""The ``(fp8 (T, H), e8m0 (T, H/32))`` pair of ``x`` (rows ``T`` once its
95+
leading dims are flattened) if the last FFN seam wrote it for these very
96+
rows, else None. Clears the slot either way."""
97+
pair, _FFN_PAIR[0] = _FFN_PAIR[0], None
98+
if pair is None:
99+
return None
100+
normed, quant, scale = pair
101+
if (
102+
not x.is_contiguous()
103+
or x.data_ptr() != normed.data_ptr()
104+
or x.dtype != normed.dtype
105+
or x.reshape(-1, x.shape[-1]).shape != normed.shape
106+
):
107+
return None
108+
return quant, scale
109+
110+
68111
def pack_mhc_fn(fn):
69112
"""Select the backend and pack once after checkpoint loading, like V4."""
70113
backend = envs.ATOM_DSV41_MHC_BACKEND
@@ -109,6 +152,7 @@ def pre_delayed(
109152
sublayer_output=None,
110153
post_mix=None,
111154
combination=None,
155+
ffn_pair=False,
112156
):
113157
"""One sublayer seam: optional post, the delayed pre, the input RMSNorm.
114158
@@ -137,6 +181,7 @@ def pre_delayed(
137181
sublayer_output=sublayer_output,
138182
post_mix=post_mix,
139183
combination=combination,
184+
ffn_pair=ffn_pair,
140185
)
141186
# Keep the guarded op's outputs flat and preserve the no-post input alias
142187
# outside it. Only the attention-facing wrapper groups the norm outputs.
@@ -198,6 +243,7 @@ def v41_mhc_pre_delayed(
198243
sublayer_output: torch.Tensor | None = None,
199244
post_mix: torch.Tensor | None = None,
200245
combination: torch.Tensor | None = None,
246+
ffn_pair: bool = False,
201247
) -> list[torch.Tensor]:
202248
"""The seam as one guarded op, so Dynamo treats the launches as opaque."""
203249
*outer, hc_mult, hidden = residual.shape
@@ -214,12 +260,23 @@ def v41_mhc_pre_delayed(
214260
# mega_mhc for a packed BF16 fn (HIP, gfx950/gfx1250), or for a raw FP32 fn
215261
# on gfx942 where it runs AITER's ASM seam and RMSNorm. fuse_quant implies
216262
# w_preshuffle_bf16, so the ASM branch always resolves to BF16.
263+
# ffn_pair: the BF16 interface stays; the same launch also writes the
264+
# normed rows' MXFP8 pair, which goes to `take_ffn_pair`.
265+
pair = (
266+
ffn_pair
267+
and not fuse_quant
268+
and w_preshuffle_bf16
269+
and rows <= _ffn_pair_max_rows()
270+
and fuse_quant_supported()
271+
)
272+
if not pair:
273+
_FFN_PAIR[0] = None
217274
if w_preshuffle_bf16 or (with_post and use_asm_seam(hc_mult, hidden)):
218275
kernel = mega_mhc
219-
options["out_dtype"] = "mxfp8" if fuse_quant else "bf16"
276+
options["out_dtype"] = "mxfp8" if fuse_quant or pair else "bf16"
220277
if w_preshuffle_bf16:
221278
options["w_preshuffle_bf16"] = True
222-
if fuse_quant:
279+
if fuse_quant or pair:
223280
options.update(_row_major_scale_options())
224281
new_residual, post, comb, normed, pre = kernel(
225282
residual.view(rows, hc_mult, hidden),
@@ -241,8 +298,11 @@ def v41_mhc_pre_delayed(
241298
norm_eps=norm_eps,
242299
**options,
243300
)
244-
if fuse_quant:
301+
if fuse_quant or pair:
245302
normed, quant, scale = normed
303+
if pair:
304+
# (T, H) rows, (T, H) E4M3, (T, H/32) E8M0: what quantize_fp8 returns.
305+
_FFN_PAIR[0] = (normed, quant, scale.view(torch.float8_e8m0fnu))
246306
outputs = [
247307
normed.view(*outer, hidden),
248308
pre.view(*outer, hc_mult),

‎atom/model_ops/fused_moe/flydsl_mega_experts.py‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -210,8 +210,11 @@ def _shared_expert_input_cls():
210210
from atom.model_ops.blockscale import quantize_fp8
211211

212212
class LazySharedExpertInput(base):
213-
def __init__(self, x, gate_up, gate_up_scale, down, down_scale, dense):
214-
self._x, self._x_mxfp8 = x, None
213+
def __init__(
214+
self, x, gate_up, gate_up_scale, down, down_scale, dense, x_mxfp8=None
215+
):
216+
# x_mxfp8: x's pair made already (the V4.1 FFN seam writes it).
217+
self._x, self._x_mxfp8 = x, x_mxfp8
215218
super().__init__(
216219
None, None, gate_up, gate_up_scale, down, down_scale, dense
217220
)
@@ -259,6 +262,8 @@ def attach_mega_shared_expert(layer, shared_expert) -> bool:
259262

260263

261264
def _shared_expert_input(shared_expert, x: torch.Tensor):
265+
from atom.model_ops.deepseek_v41.mhc_pre_delayed import take_ffn_pair
266+
262267
gate_up, down = shared_expert.gate_up_proj, shared_expert.w2
263268
return _shared_expert_input_cls()(
264269
x,
@@ -267,6 +272,9 @@ def _shared_expert_input(shared_expert, x: torch.Tensor):
267272
down.weight,
268273
down.weight_scale,
269274
dense=lambda: shared_expert(x),
275+
# The MXFP8 pair the V4.1 FFN seam wrote of x, bit for bit
276+
# quantize_fp8(x): when present, no quantize launch at all.
277+
x_mxfp8=take_ffn_pair(x),
270278
)
271279

272280

‎atom/models/deepseek_v41/model.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,8 @@ def __init__(
9696
# Set with the packs: attention's fused MXFP8 norm output, where the
9797
# HIP kernel can write row-major scales (`fuse_quant_supported`).
9898
self.hc_fuse_quant = False
99+
# Set with the packs: the FFN seam's MXFP8 pair for the shared expert.
100+
self.hc_ffn_pair = False
99101
self.engram = None
100102
if spec.layer_id in config.engram_layer_ids:
101103
width = (
@@ -129,6 +131,14 @@ def process_weights_after_loading(self):
129131
and self.attn.wqkv_a.native_a8_group_rows is not None
130132
and not self.attn.wqkv_a.runs_bf16
131133
)
134+
# A routed MegaMoE call that computes the shared expert (shared_in)
135+
# reads the FFN input's MXFP8 pair: the FFN seam writes it with the
136+
# norm instead of a quantize launch before the MoE (`take_ffn_pair`).
137+
self.hc_ffn_pair = (
138+
self.hc_ffn_fn_packed is not None
139+
and fuse_quant_supported()
140+
and bool(getattr(self.ffn, "_shared_in_routed", False))
141+
)
132142

133143
def attention_forward(self, normed, cache, step, rope):
134144
"""Keep BF16 for auxiliary readers and reuse the optional QKV quant."""
@@ -188,6 +198,7 @@ def prepare_ffn(self, output, residual, pre, post, comb):
188198
**self.hc_options,
189199
norm_eps=self.ffn_norm.eps,
190200
w_preshuffle_bf16=hc_fn is not None,
201+
ffn_pair=self.hc_ffn_pair,
191202
sublayer_output=output,
192203
post_mix=post,
193204
combination=comb,

‎tests/model_ops/test_mhc_pre_delayed_backend.py‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,3 +96,87 @@ def kernel(residual, *args, **kwargs):
9696
**post_kw,
9797
)
9898
assert calls == [expected]
99+
100+
101+
@pytest.mark.parametrize(
102+
"rows, ffn_pair, fuse_quant_ok, expect_pair",
103+
[
104+
(6, True, True, True), # a shared_in FFN seam on the small-input route
105+
(512, True, True, True), # the route's ceiling
106+
(513, True, True, False), # above it nothing fuses the shared expert
107+
(6, False, True, False), # not asked: the BF16-only seam
108+
(6, True, False, False), # no row-major MXFP8 scales on this arch
109+
],
110+
)
111+
def test_ffn_seam_leaves_the_mxfp8_pair_for_its_own_rows(
112+
rows, ffn_pair, fuse_quant_ok, expect_pair, monkeypatch, mhc
113+
):
114+
"""An FFN seam asked for the pair runs the same mega_mhc launch with MXFP8
115+
output, returns only the BF16 outputs, and hands the pair to the next reader
116+
of those very rows; any other seam clears it."""
117+
hc, hidden = 4, 128
118+
calls = []
119+
120+
def mega_mhc(residual, *args, **kwargs):
121+
calls.append(kwargs)
122+
normed = torch.randn(rows, hidden).to(torch.bfloat16)
123+
if kwargs.get("out_dtype") == "mxfp8":
124+
normed = (
125+
normed,
126+
torch.zeros(rows, hidden, dtype=torch.uint8),
127+
torch.zeros(rows, hidden // 32, dtype=torch.uint8),
128+
)
129+
return (
130+
residual.clone(),
131+
torch.zeros(rows, hc),
132+
torch.zeros(rows, hc, hc),
133+
normed,
134+
torch.zeros(rows, hc),
135+
)
136+
137+
monkeypatch.setattr(mhc, "mega_mhc", mega_mhc)
138+
monkeypatch.setattr(mhc, "fuse_quant_supported", lambda: fuse_quant_ok)
139+
monkeypatch.setattr(mhc, "_row_major_scale_options", dict)
140+
monkeypatch.setattr(mhc, "_ffn_pair_max_rows", lambda: 512)
141+
seam = getattr(mhc.v41_mhc_pre_delayed, "__wrapped__", mhc.v41_mhc_pre_delayed)
142+
143+
def run(**kwargs):
144+
pre = torch.full((rows, hc), 1 / hc)
145+
return seam(
146+
torch.randn(rows, hc, hidden),
147+
pre,
148+
torch.randn(24, hc * hidden),
149+
torch.ones(3),
150+
torch.zeros(24),
151+
torch.ones(hidden),
152+
rms_eps=1e-6,
153+
hc_eps=1e-6,
154+
sinkhorn_iters=20,
155+
post_mult=2.0,
156+
norm_eps=1e-6,
157+
w_preshuffle_bf16=True,
158+
sublayer_output=torch.randn(rows, hidden),
159+
post_mix=torch.ones_like(pre),
160+
combination=torch.eye(hc).expand(rows, hc, hc).contiguous(),
161+
**kwargs,
162+
)
163+
164+
mhc._FFN_PAIR[0] = ("stale",) # a pair nobody took is never handed on
165+
outputs = run(ffn_pair=ffn_pair)
166+
assert len(outputs) == 5 # residual, normed, pre, post, comb: no pair outputs
167+
assert calls[-1]["out_dtype"] == ("mxfp8" if expect_pair else "bf16")
168+
normed = outputs[1]
169+
pair = mhc.take_ffn_pair(normed)
170+
assert (pair is not None) == expect_pair
171+
if expect_pair:
172+
quant, scale = pair
173+
assert quant.shape == (rows, hidden) and scale.shape == (rows, hidden // 32)
174+
assert scale.dtype == torch.float8_e8m0fnu
175+
assert mhc.take_ffn_pair(normed) is None # taken once
176+
177+
# Only for these very rows: a copy or another seam's output gets nothing.
178+
run(ffn_pair=ffn_pair)
179+
assert mhc.take_ffn_pair(normed.clone()) is None
180+
run(ffn_pair=ffn_pair)
181+
run() # the next (attention) seam clears it
182+
assert mhc._FFN_PAIR[0] is None

‎tests/test_mega_decode_capacity.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -699,7 +699,9 @@ def test_an_attached_shared_expert_goes_into_the_routed_call(runtime, monkeypatc
699699
passes none."""
700700

701701
class SharedExpertInput:
702-
def __init__(self, x, gate_up, gate_up_scale, down, down_scale, dense):
702+
def __init__(
703+
self, x, gate_up, gate_up_scale, down, down_scale, dense, x_mxfp8=None
704+
):
703705
self.weights = (gate_up, gate_up_scale, down, down_scale)
704706
self.dense = dense
705707

‎tests/test_mega_shared_in.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,17 @@ def quantize_fp8(x):
5959
state.quantized += 1
6060
return x.to(torch.float8_e4m3fn), torch.zeros(x.shape[0], x.shape[1] // 32)
6161

62+
# The V4.1 FFN seam's pair slot (mhc_pre_delayed.take_ffn_pair).
63+
state.seam_pair = None
64+
seam = ModuleType("atom.model_ops.deepseek_v41.mhc_pre_delayed")
65+
66+
def take_ffn_pair(x):
67+
pair, state.seam_pair = state.seam_pair, None
68+
return pair
69+
70+
seam.take_ffn_pair = take_ffn_pair
71+
monkeypatch.setitem(sys.modules, seam.__name__, seam)
72+
6273
blockscale = ModuleType("atom.model_ops.blockscale")
6374
blockscale.quantize_fp8 = quantize_fp8
6475
monkeypatch.setitem(sys.modules, "atom.model_ops.blockscale", blockscale)
@@ -107,6 +118,21 @@ def test_x_is_quantized_only_when_the_kernel_reads_it(aiter_weights):
107118
assert aiter_weights.quantized == 1
108119

109120

121+
def test_the_ffn_seams_pair_replaces_the_quantize_launch(aiter_weights):
122+
aiter_weights.install()
123+
expert, x = _Expert(), torch.randn(6, 64)
124+
seam_pair = (x.to(torch.float8_e4m3fn), torch.zeros(6, 2))
125+
aiter_weights.seam_pair = seam_pair
126+
127+
fused = mega._shared_expert_input(expert, x)
128+
assert fused.x_fp8 is seam_pair[0] and fused.x_scale is seam_pair[1]
129+
assert aiter_weights.quantized == 0 and aiter_weights.seam_pair is None
130+
131+
# The next call has no pair left and quantizes x itself.
132+
other = mega._shared_expert_input(expert, x)
133+
assert other.x_fp8 is not seam_pair[0] and aiter_weights.quantized == 1
134+
135+
110136
def test_attached_only_on_a_mega_layer_every_routed_call_reaches(aiter_weights):
111137
aiter_weights.install()
112138
expert = _Expert()

0 commit comments

Comments
 (0)