Skip to content

[FlyDSL] [Bugfix] gfx1250 FP8 GEMM: store C from registers / LDS read-back, not a TDM store from LDS - #8486

Closed
XiaobingSuper wants to merge 3 commits into
ROCm:mainfrom
XiaobingSuper:xiaobingsuper/gfx1250-mxfp8-c-lds-readback
Closed

XiaobingSuper wants to merge 3 commits into
ROCm:mainfrom
XiaobingSuper:xiaobingsuper/gfx1250-mxfp8-c-lds-readback

Conversation

@XiaobingSuper

@XiaobingSuper XiaobingSuper commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

What

launch_gemm_a8w8 (gfx1250 FP8 / MXFP8 GEMM, gemm_a8w8_gfx1250.py) no longer writes C with a TDM store from LDS:

  • bf16 / f16 C without split-K is stored straight from the WMMA accumulators with global stores: no LDS staging, no barrier. The TDM-store code is removed.
  • Unfused split-K fp32 partials go LDS → barrier → ds_load read-back → global stores in 16-byte row chunks.
  • Rows past M are dropped, as the TDM extent dropped them. The fused-quant epilogue is unchanged.

Why

The old epilogue ds_stored the C tile over the last k-tile's operands, passed s_wait_dscnt 0 + s_barrier, and then each wave TDM-stored a box of whole rows. On gfx1250 that TDM store now and then reads a 16-byte piece as LDS held it before the ds_stores: the last k-tile's FP8 A operand, which read as bf16 is 1e24-1e38 and never NaN.

In MiniMax-M3.1-Flash TP4 decode on MI455X (shared-expert down_proj beside the routed MoE on another stream of the captured graph) the poisoned residual made RMSNorm output 0, the logits row all zero, and argmax token 0.

Validation

Reproducer: a standalone script, posted in this comment instead of committed. One CUDA graph: stream A runs 64 launches of the M3.1 shared-expert down_proj (N = 6144, K = 768, M = 8 and 64), stream B the M3.1 routed MXFP4 MoE; every output is compared with an eager run. 1x MI455X, bad replays:

Run main this PR
default, 2 min bad in 4 of 4 runs (22, 2, 17, 4) 0 / 930,100 (M = 8), 0 / 667,900 (M = 64), 10 min
split-K sk4 (M = 32) / sk8 (M = 64), N = 1536, K = 6144 15 / 122,200 and 5 / 114,900 0 / 120,700 and 0 / 113,100
controls: one graph queue (DEBUG_HIP_FORCE_GRAPH_QUEUES=1), nothing on stream B (--bg none) 0

The collision depends on timing. Reproduced again on two more nodes: with torch 2.11 / ROCm 10.1 / FlyDSL 0.5.0 the default command fires (main 30 / 649,300, this PR 0 / 637,000); with torch 2.13 / ROCm 10.3 / FlyDSL 0.5.3 the default 8 MoE tokens did not collide (main 0 / 4.9 M), but --moe-t 1 or 2 does (main 276 / 2.7 M, this PR 0 / 3.8 M).

Correctness: against torch, all 16 configs of the table below at full shape, rel err 1.6-1.7e-3 (the FP8 quantization error); nothing is written past M.

Kernel time vs main

M3.1 TP4 shapes with their tuned kernels, CUDA graph, 1x MI455X, median of 6 interleaved rounds, us:

M gate_up 1536 x 6144: main this PR down_proj 6144 x 768: main this PR
1 4.06 4.10 +1.0% 2.18 2.12 -2.8%
8 4.58 4.73 +3.2% 2.37 2.34 -1.1%
16 4.76 4.77 +0.1% 2.18 2.01 -7.9%
32 5.30 5.16 -2.6% 2.26 2.10 -7.0%
64 4.95 (sk8) 5.12 +3.3% 2.49 2.35 -5.7%
128 5.38 5.40 +0.4% 2.74 2.62 -4.5%
256 6.47 6.55 +1.2% 3.46 3.35 -3.2%
1024 10.21 10.58 +3.6% 6.81 6.85 +0.6%

gate_up M = 8 is within the run-to-run spread (main 4.32-4.88, this PR 4.48-5.02).

Open question for HW / compiler

Triton / Gluon lower the same handoff to the same ds_store → s_wait_dscnt → s_barrier → tensor_store_from_lds sequence, and gemm_a8w8_256x256 relies on it too (not changed here). The LLVM AMDGPU memory model leaves tensor ops out and documents no DS → TDM fence. Which fence, if any, orders a TDM store's LDS read after other waves' ds_stores at a workgroup barrier?

#8273 carries the earlier version of this fix and drops it once this lands.

PR Self-Review

Reviewed revision

fd44a48

Behavior and intent

On gfx1250, launch_gemm_a8w8 no longer TDM-stores C from LDS. bf16 / f16 C without split-K goes from registers straight to global memory; unfused split-K fp32 partials are read back from LDS with ds_load after the barrier; fused quant is unchanged. This removes stale-LDS bytes from C.

Validation and unverified scope

  • 1x MI455X (gfx1250), main vs this PR, reproducer script from this comment (python repro_gemm_a8w8_tdm_race.py): main bad in 4 of 4 runs (22, 2, 17, 4 bad replays in 2 min); this PR 0 / 930,100 (M = 8) and 0 / 667,900 (M = 64) in 10 min.
  • Same, split-K (--m 32,64 --n 1536 --k 6144 --kernel ...sk4...,...sk8...): main 15 / 122,200 and 5 / 114,900; this PR 0 / 120,700 and 0 / 113,100.
  • Two more nodes: torch 2.11 / FlyDSL 0.5.0 default command, main 30 / 649,300, this PR 0 / 637,000; torch 2.13 / FlyDSL 0.5.3 with --moe-t 1 and --moe-t 2, main 276 / 2.7 M, this PR 0 / 3.8 M.
  • Controls on main: DEBUG_HIP_FORCE_GRAPH_QUEUES=1 and --bg none both 0.
  • Eager check against torch: all 16 configs of "Kernel time vs main" at full shape, rel err 1.6-1.7e-3, nothing written past M.
  • Kernel time: "Kernel time vs main" table (CUDA graph, median of 6 interleaved rounds).
  • Unverified: the PTPC and MX128 variants that share this epilogue; an in-model run of this exact revision (the 8 / 40 -> 0 / 50 all-zero-logits-row result and GSM8K 0.956 / 0.953 were measured with the earlier, LDS-read-back-only version in [HIP] [FlyDSL] [gfx1250] Optimize native MXFP8 GEMM across M regimes #8273); CI execution (no gfx1250 runner runs this path).

PR-specific question

Most important boundary: the M edge of the last tile. The TDM store's tensor extent used to clip rows past M; both new store paths (bf16 / f16 from registers, split-K fp32 read back from LDS) now guard each row with row < M themselves, and a wrong guard would write past M into whatever follows C. Columns are unchanged: the old TDM box was also a full tile_n wide. Evidence: the eager check above writes nothing past M in all 16 configs, which include M = 1 and 8 (rows end inside a tile), plus the split-K sk4 / sk8 runs.

Changed op tests

None. The reproducer is not committed: it is a standalone two-stream CUDA-graph script (about 2 minutes a run) that no CI runner executes, so it lives in this comment.

🤖 Generated with Claude Code

@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter standard tests on MI35X
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the Radeon R9700 ROCm runner
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 8486 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.

…-back, not a TDM store from LDS

On gfx1250 the epilogue of launch_gemm_a8w8 ds_stored the C tile to LDS,
passed s_wait_dscnt 0 + s_barrier, and each wave TDM-stored a box of whole
rows. Now and then the TDM store's LDS read returned a 16-byte piece as LDS
held it before the ds_stores: the last k-tile's FP8 A operand, 1e24-1e38 as
bf16.

bf16 / f16 C without split-K is now stored straight from the accumulators
with global stores (no LDS staging, no barrier). Unfused split-K fp32
partials go LDS -> barrier -> ds_load read-back -> global stores. Rows past
M are dropped as before; the fused-quant epilogue is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@XiaobingSuper
XiaobingSuper force-pushed the xiaobingsuper/gfx1250-mxfp8-c-lds-readback branch from 6855131 to de1fa01 Compare November 23, 2026 10:23
@XiaobingSuper XiaobingSuper changed the title [FlyDSL] [Bugfix] gfx1250 FP8 GEMM: write C through an LDS read-back, not a TDM store [FlyDSL] [Bugfix] gfx1250 FP8 GEMM: store C from registers / LDS read-back, not a TDM store from LDS Nov 23, 2026
@XiaobingSuper
XiaobingSuper marked this pull request as ready for review November 23, 2026 10:25
@XiaobingSuper
XiaobingSuper requested a review from a team November 23, 2026 10:25
@XiaobingSuper

Copy link
Copy Markdown
Contributor Author

Head de1fa01 is the register-store / LDS-read-back fix: 0 bad replays in 10 min of the repro (main: bad in 4 of 4 runs) and in both split-K cases (main: 15 and 5); kernel time vs main -7.9% to +3.6% at the M3.1 shapes; rel err 1.6-1.7e-3 vs torch in all 16 configs. Ready for review.

Copilot AI balanced review requested due to automatic review settings November 23, 2026 10:25

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@aiter-bot

aiter-bot commented Nov 23, 2026 •

Copy link
Copy Markdown

NOT READY FOR HUMAN REVIEW

PR Self-Review

Revision fd44a48a7eb3 · mode shadow

Author self-review accepted. Readiness report:

Author answers

  • PASS — current-SHA answers are present and structurally specific
Show the author's self-review answers

Behavior and intent

On gfx1250, `launch_gemm_a8w8` no longer TDM-stores C from LDS. bf16 / f16 C without split-K goes from registers straight to global memory; unfused split-K fp32 partials are read back from LDS with `ds_load` after the barrier; fused quant is unchanged. This removes stale-LDS bytes from C.

Validation and unverified scope

- 1x MI455X (gfx1250), main vs this PR, reproducer script from [this comment](https://github.com/ROCm/aiter/pull/8486#issuecomment-7180368391) (`python repro_gemm_a8w8_tdm_race.py`): main bad in 4 of 4 runs (22, 2, 17, 4 bad replays in 2 min); this PR 0 / 930,100 (M = 8) and 0 / 667,900 (M = 64) in 10 min.
- Same, split-K (`--m 32,64 --n 1536 --k 6144 --kernel ...sk4...,...sk8...`): main 15 / 122,200 and 5 / 114,900; this PR 0 / 120,700 and 0 / 113,100.
- Two more nodes: torch 2.11 / FlyDSL 0.5.0 default command, main 30 / 649,300, this PR 0 / 637,000; torch 2.13 / FlyDSL 0.5.3 with `--moe-t 1` and `--moe-t 2`, main 276 / 2.7 M, this PR 0 / 3.8 M.
- Controls on main: `DEBUG_HIP_FORCE_GRAPH_QUEUES=1` and `--bg none` both 0.
- Eager check against torch: all 16 configs of "Kernel time vs main" at full shape, rel err 1.6-1.7e-3, nothing written past M.
- Kernel time: "Kernel time vs main" table (CUDA graph, median of 6 interleaved rounds).
- Unverified: the PTPC and MX128 variants that share this epilogue; an in-model run of this exact revision (the 8 / 40 -> 0 / 50 all-zero-logits-row result and GSM8K 0.956 / 0.953 were measured with the earlier, LDS-read-back-only version in #8273); CI execution (no gfx1250 runner runs this path).

PR-specific question

Most important boundary: the M edge of the last tile. The TDM store's tensor extent used to clip rows past M; both new store paths (bf16 / f16 from registers, split-K fp32 read back from LDS) now guard each row with `row < M` themselves, and a wrong guard would write past M into whatever follows C. Columns are unchanged: the old TDM box was also a full `tile_n` wide. Evidence: the eager check above writes nothing past M in all 16 configs, which include M = 1 and 8 (rows end inside a tile), plus the split-K sk4 / sk8 runs.

Changed op tests

None. The reproducer is not committed: it is a standalone two-stream CUDA-graph script (about 2 minutes a run) that no CI runner executes, so it lives in [this comment](https://github.com/ROCm/aiter/pull/8486#issuecomment-7180368391).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

PR state

  • PASS — pull request is marked ready for review

Copilot findings

  • PASS — no active Copilot finding lacks a substantive author reply
  • ADVISORY — Copilot could not review the current head (for example, quota or service failure)

Code and op-test hygiene

  • PASS — no committed artifact or conflict marker detected

Required CI

  • PASS — Black: passed
  • PASS — Ruff: passed
  • PASS — Repository dependency: passed
  • FAIL — Aiter Test Gate: failed
  • Required CI failed; fix it before requesting human review.

Shadow mode reports what would block but keeps the status successful. Set AITER_PR_SELF_REVIEW_MODE=enforce only after reviewing real false positives.

op_tests/flydsl_tests/repro_gemm_a8w8_tdm_race.py replays one CUDA graph with the
M3.1 shared-expert down_proj GEMMs on stream A beside the routed MXFP4 MoE on
stream B and counts outputs that differ from a clean eager run (main: bad > 0,
this PR: 0). Standalone script, not collected by pytest (~2 min a run).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 25, 2026 03:24

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

…thread

The reproducer is a standalone two-stream CUDA-graph script (about 2 minutes
a run) that no CI runner executes; it is posted on the PR instead of living
in op_tests/.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@XiaobingSuper

Copy link
Copy Markdown
Contributor Author

Reproducer for this PR, moved here from op_tests/flydsl_tests/ (it is a standalone two-stream CUDA-graph script, about 2 minutes a run, that no CI runner executes). One CUDA graph: stream A runs 64 launches of the M3.1 shared-expert down_proj (N = 6144, K = 768, M = 8 and 64), stream B the M3.1 routed MXFP4 MoE; every output is compared with an eager run. Run it in a gfx1250 aiter container with PYTHONPATH on the tree under test:

python repro_gemm_a8w8_tdm_race.py                                  # main: RESULT BAD, this PR: RESULT CLEAN
python repro_gemm_a8w8_tdm_race.py --moe-t 2                        # same, if the default 8 MoE tokens do not collide (see the PR description)
DEBUG_HIP_FORCE_GRAPH_QUEUES=1 python repro_gemm_a8w8_tdm_race.py   # control, one graph queue: CLEAN
python repro_gemm_a8w8_tdm_race.py --bg none                        # control, nothing on stream B: CLEAN
python repro_gemm_a8w8_tdm_race.py --m 32,64 --n 1536 --k 6144 \
  --kernel flydsl_mxfp8_32_bpreshuffle_wmma_t16x32x512_mw1_nw2_nb2_sk4_cm1_cn1_fsk,flydsl_mxfp8_32_bpreshuffle_wmma_t32x128x128_mw1_nw4_nb4_sk8_cm1_cn1   # split-K
repro_gemm_a8w8_tdm_race.py
#!/usr/bin/env python3
"""Reproducer: gfx1250 MXFP8 GEMM (aiter/ops/flydsl/kernels/gemm_a8w8_gfx1250.py) C-store race.

The kernel stages the bf16 C tile in LDS with ds_store (over the last k-tiles' FP8 A operand),
passes s_wait_dscnt 0 + s_barrier, and each wave TDM-stores (tensor_store_from_lds) a box of
whole rows. Now and then a 16-byte chunk leaves with what LDS held before the ds_store: FP8
activation bytes, which read as bf16 are 1e24..1e38 (never NaN/Inf). It shows up when another
kernel runs beside the GEMM on a second HIP graph queue (MiniMax-M3.1 TP4 shared-expert
down_proj next to the routed MoE).

Each graph replay marks the outputs, forks a background GEMM onto stream B, runs --na small
GEMMs (the M3.1 shared down_proj, N=6144 K=768) on stream A, joins, and counts outputs that
differ from a clean eager run. All scales are 1.0 and |A| is 64..448, so a stale A chunk is
unmistakable.
  python repro_gemm_a8w8_tdm_race.py                                  # unfixed: bad > 0
  DEBUG_HIP_FORCE_GRAPH_QUEUES=1 python repro_gemm_a8w8_tdm_race.py   # one graph queue: 0
  python repro_gemm_a8w8_tdm_race.py --bg none                        # nothing beside it: 0
"""

import argparse
import time

import torch
from aiter.utility import dtypes
from aiter.ops.shuffle import shuffle_weight
from aiter.ops.flydsl.batched_gemm_a8w8_gfx1250 import (
    pick_bmm_mx32_kernel_name,
    run_bmm_a8w8_mxfp8_32_gfx1250,
)
from aiter.ops.flydsl.mxfp8_bpreshuffle_gemm_gfx1250 import (
    run_gemm_a8w8_mxfp8_32_bpreshuffle_gfx1250,
)


def bmm(x8, wq, xs, ws, out, kernel_name=None):
    """[M,1,K] x [1,N,K] -> [M,1,N]; a flydsl_mxfp8_32_bpreshuffle_* name (e.g. split-K) runs the 2-D GEMM."""
    if kernel_name is None or kernel_name.startswith("flydsl_bmm"):
        return run_bmm_a8w8_mxfp8_32_gfx1250(
            x8, wq, xs, ws, out, kernel_name=kernel_name
        )
    e8m0 = dtypes.fp8_e8m0
    run_gemm_a8w8_mxfp8_32_bpreshuffle_gfx1250(
        x8[:, 0], wq[0], xs[:, 0].view(e8m0), ws[0].view(e8m0), out[:, 0], kernel_name
    )


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--m", default="8,64", help="GEMM rows (decode tokens)")
    p.add_argument("--n", type=int, default=6144)
    p.add_argument("--k", type=int, default=768)
    # per --m entry (or one for all): t16x64x128 is the M3.1 TP4 shared down_proj kernel at M=8 (the
    # one that fired in the model), t32x128x128 the one at M=128; "auto" = aiter's heuristic pick
    p.add_argument("--kernel", default="t16x64x128_mw1_nw4_nb4,t32x128x128_mw1_nw4_nb4")
    p.add_argument(
        "--bg",
        default="moe",
        choices=["moe", "gemm", "mm", "none"],
        help="kernel on stream B",
    )
    p.add_argument(
        "--moe-t", type=int, default=8, help="tokens of the routed MXFP4 MoE (--bg moe)"
    )
    p.add_argument("--bg-m", type=int, default=4096, help="rows of the background GEMM")
    p.add_argument("--bg-n", type=int, default=6144)
    p.add_argument("--bg-k", type=int, default=768)
    p.add_argument(
        "--bg-kernel",
        default="flydsl_bmm_mxfp8_32_wmma_t32x64x128_mw1_nw4_nb4_sk1_cm1_cn1",
    )
    p.add_argument("--na", type=int, default=64, help="small GEMM launches per replay")
    p.add_argument("--nb", type=int, default=6, help="background launches per replay")
    p.add_argument(
        "--nw",
        type=int,
        default=16,
        help="distinct A/W operand sets cycled over the launches",
    )
    p.add_argument("--replays", type=int, default=10**7)
    p.add_argument("--seconds", type=float, default=60.0, help="time cap per M")
    p.add_argument(
        "--eager", action="store_true", help="two plain streams instead of a CUDA graph"
    )
    a = p.parse_args()
    torch.manual_seed(0)
    dev = "cuda"

    def operands(m, n, k):
        mag = torch.empty(m, 1, k, device=dev).uniform_(
            64, 448
        )  # FP8 bytes 0x68..0x7e (+sign)
        x8 = (mag * (torch.randint(0, 2, mag.shape, device=dev) * 2 - 1)).to(dtypes.fp8)
        w8 = (torch.randn(1, n, k, device=dev) * 0.02).to(dtypes.fp8)
        xs = torch.full((m, 1, k // 32), 127, dtype=torch.uint8, device=dev)  # e8m0 2^0
        ws = torch.full((1, n, k // 32), 127, dtype=torch.uint8, device=dev)
        return x8, w8, shuffle_weight(w8), xs, ws

    def make_bg():
        if a.bg == "gemm":
            x8, _, wq, xs, ws = operands(a.bg_m, a.bg_n, a.bg_k)
            out = torch.empty(a.bg_m, 1, a.bg_n, dtype=torch.bfloat16, device=dev)
            return lambda: bmm(x8, wq, xs, ws, out, kernel_name=a.bg_kernel)
        if (
            a.bg == "moe"
        ):  # M3.1 TP4 routed MoE: 128 experts top-4, 6144 -> 768, a8w4 grouped TDM GEMMs
            from aiter import ActivationType, QuantType
            from aiter.fused_moe import fused_moe
            from aiter.ops.flydsl.moe_common import GateMode
            from aiter.ops.shuffle import moe_shuffle_scale, moe_shuffle_weight

            E, topk, D, I, T = 128, 4, 6144, 768, a.moe_t
            u8 = lambda *sh, lo=0, hi=256: torch.randint(
                lo, hi, sh, dtype=torch.uint8, device=dev
            )
            w1 = moe_shuffle_weight(
                u8(E, 2 * I, D // 2), experts_cnt=E, is_guinterleave=True, gate_up=True
            )
            w2 = moe_shuffle_weight(u8(E, D, I // 2), experts_cnt=E)
            s1 = moe_shuffle_scale(
                u8(E, 2 * I, D // 32, lo=118, hi=124),
                experts_cnt=E,
                is_guinterleave=True,
                gate_up=True,
            )
            s2 = moe_shuffle_scale(u8(E, D, I // 32, lo=118, hi=124), experts_cnt=E)
            h = torch.randn(T, D, dtype=torch.bfloat16, device=dev)
            ids = torch.stack(
                [torch.randperm(E, device=dev)[:topk] for _ in range(T)]
            ).int()
            wts = torch.full((T, topk), 1.0 / topk, device=dev)
            return lambda: fused_moe(
                h,
                w1,
                w2,
                wts,
                ids,
                activation=ActivationType.Swiglu,
                quant_type=QuantType.per_1x32,
                w1_scale=s1,
                w2_scale=s2,
                gate_mode=GateMode.INTERLEAVE.value,
                dtype=torch.bfloat16,
            )
        if a.bg == "mm":
            x = torch.randn(a.bg_m, 4096, dtype=torch.bfloat16, device=dev)
            w = torch.randn(4096, 4096, dtype=torch.bfloat16, device=dev)
            return lambda: torch.mm(x, w)
        return None

    bg = make_bg()
    print(
        f"bg={a.bg} ({a.bg_kernel if a.bg == 'gemm' else ''}) bg_mnk={a.bg_m}x{a.bg_n}x{a.bg_k} na={a.na} nb={a.nb} N={a.n} K={a.k}",
        flush=True,
    )
    total_bad = 0
    ms, kns = [int(v) for v in a.m.split(",")], a.kernel.split(",")
    for m, kn in zip(ms, kns * len(ms) if len(kns) == 1 else kns):
        kn = pick_bmm_mx32_kernel_name(1, m, a.n, a.k) if kn == "auto" else kn
        kn = (
            kn
            if kn.startswith("flydsl_")
            else f"flydsl_bmm_mxfp8_32_wmma_{kn}_sk1_cm1_cn1"
        )
        ops = [
            operands(m, a.n, a.k) for _ in range(a.nw)
        ]  # distinct weights per launch: cold like a model's layers
        refs = torch.empty(a.nw, m, 1, a.n, dtype=torch.bfloat16, device=dev)
        for j, (x8, w8, wq, xs, ws) in enumerate(ops):
            bmm(x8, wq, xs, ws, refs[j], kernel_name=kn)
        torch.cuda.synchronize()
        x8, w8 = ops[0][:2]
        exact = (x8.float()[:, 0] @ w8.float()[0].T)[:, None]
        rel = ((refs[0].float() - exact).norm() / exact.norm()).item()
        assert (
            rel < 1e-2 and refs.float().abs().max() < 1e5
        ), f"eager result wrong: rel {rel}"
        ops = [(x8, wq, xs, ws) for x8, _, wq, xs, ws in ops]
        ref = refs[torch.arange(a.na, device=dev) % a.nw]
        outs = torch.empty(a.na, m, 1, a.n, dtype=torch.bfloat16, device=dev)
        rep_bad = torch.zeros((), dtype=torch.int64, device=dev)
        launch_bad = torch.zeros((), dtype=torch.int64, device=dev)
        row_bad = torch.zeros(m, dtype=torch.int64, device=dev)
        vmax = torch.zeros((), dtype=torch.float32, device=dev)
        s0, s1 = torch.cuda.Stream(), torch.cuda.Stream()
        with torch.cuda.stream(s0):  # compile + warm up outside the capture
            for i in range(2):
                bmm(*ops[i % a.nw], outs[i], kernel_name=kn)
                if bg:
                    bg()
        torch.cuda.synchronize()

        def step():
            outs.fill_(float("nan"))  # an unwritten chunk counts as bad too
            s1.wait_stream(s0)
            with torch.cuda.stream(s1):
                for _ in range(a.nb if bg else 0):
                    bg()
            for i in range(a.na):
                bmm(*ops[i % a.nw], outs[i], kernel_name=kn)
            s0.wait_stream(s1)
            diff = (outs != ref).flatten(2).any(-1)  # [na, m]
            rep_bad.add_(diff.any())
            launch_bad.add_(diff.any(-1).sum())
            row_bad.add_(diff.sum(0))
            torch.maximum(
                vmax,
                torch.where(outs != ref, outs.float().abs(), 0).nan_to_num(3e38).amax(),
                out=vmax,
            )

        g = None if a.eager else torch.cuda.CUDAGraph()
        if g is not None:
            with torch.cuda.graph(g, stream=s0):
                step()
        torch.cuda.synchronize()
        t0, done = time.time(), 0
        while done < a.replays and time.time() - t0 < a.seconds:
            for _ in range(min(100, a.replays - done)):
                if g is not None:
                    g.replay()
                else:
                    with torch.cuda.stream(s0):
                        step()
                done += 1
            torch.cuda.synchronize()
        dt = time.time() - t0
        nb_rep = int(rep_bad)
        total_bad += nb_rep
        rows = {r: int(c) for r, c in enumerate(row_bad.tolist()) if c}
        print(
            f"M={m:4d} {kn}: bad replays: {nb_rep} / {done}  (bad launches {int(launch_bad)} / "
            f"{done * a.na}, rows hit {rows}, max |bad| {float(vmax):.3g}, {dt:.1f} s, "
            f"{dt / done * 1e6:.0f} us/replay, eager rel err {rel:.1e})",
            flush=True,
        )
        del g
    print("RESULT", "BAD" if total_bad else "CLEAN", f"total bad replays {total_bad}")


if __name__ == "__main__":
    main()

Copilot AI balanced review requested due to automatic review settings November 26, 2026 02:00

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@XiaobingSuper

Copy link
Copy Markdown
Contributor Author

Closing in favor of #8737, which keeps the TDM store and adds an LDS flush before it.

Checked on one gfx1250 GPU (256 CUs; image with torch 2.13 / ROCm 10.3, FlyDSL 0.5.3) with this PR's reproducer, unchanged, at M = 64 (t32x128x128_mw1_nw4_nb4) with 2 MoE tokens beside it (--moe-t 2), 5 minutes per arm:

Kernel Bad replays
main 264 / 760,900
#8737 0 / 752,900
#8737 with the flush removed (C still moved to the arena tail) 201 / 754,900

So the flush is what fixes it; moving C alone does not. With C moved, the stale values become tiny (about 1e-24), which would be harder to notice in a model. #8737 was also clean with 1 MoE token, a plain FP8 GEMM beside it, and the split-K kernels (sk4 / sk8).

XiaobingSuper added a commit to XiaobingSuper/aiter that referenced this pull request Nov 26, 2026
…DS_STORE

The C-tile LDS read-back and its environment gate move to ROCm#8486, which owns
that fix; the non-fused epilogue here is main's TDM store again. Also merge
the two fused split-K checks into one and drop the unused cur_kt argument
threaded through the k-tile helpers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
aoli26 added a commit that referenced this pull request Nov 30, 2026
Conflict resolved (from #8737, LDS flush before TDM stores):
- gemm_a8w8_gfx1250: keep this branch's rank0 epilogue (direct global
  stores, no LDS) ahead of main's C offset. The rotated fused split-K rows
  and the row-stripe epilogue use the C staging at c_base_ptr, like the
  plain TDM store.

Merged cleanly but needed changes:
- splitk_fused_epilogue_gfx1250: an optional flush_addr flushes the reduced
  rows before their LDS -> TDM store (split_k > 2). The generic kernel
  passes its flush scratch; the compute and a4w4 callers are unchanged.
  With the #8486 two-stream reproducer, a split_k 4 row-stripe kernel gave
  140 bad replays in 4 minutes without it and 0 with it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants