Repository navigation
[FlyDSL] Work around gfx1250 LDS-to-TDM store corruption - #8737
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
WAITING ON AUTHORPR Self-ReviewRevision Waiting for the PR author. The readiness report will appear after the self-review answers are complete for this revision. Questions to answer in the PR description
Edit the Missing or invalid answers
Shadow mode reports what would block but keeps the status successful. Set |
Reproducer: concurrent graph replay of real fused MoE outputsThis adapts Xiaobing's two-stream graph reproducer to check fused MoE outputs themselves. The original script checks standalone GEMM while MoE supplies concurrent background work. Fresh matched result on one gfx1250 GPU, Torch
Main's first latched mismatch: foreground launch 6, row 1, column 3312, actual -17792 vs expected -19968. Maximum absolute difference: 7768. No NaN/Inf. The scalar mismatch and cumulative counters are preserved across subsequent replays. RunSave the complete script below outside the source tree as # From the aiter source tree under test; run each revision separately.
# Use the GPU only when available. gpu-lock must not be nested.
REV=$(git rev-parse --short HEAD)
OUT="/tmp/moe-lds-repro-${REV}-$(date +%Y%m%d_%H%M%S)"
mkdir -p "$OUT"
set -o pipefail
unset DEBUG_HIP_FORCE_GRAPH_QUEUES
gpu-lock env \
PYTHONPATH="$PWD" \
AITER_CONFIG_GROUPED_FMOE="$PWD/aiter/configs/model_configs/dsv41_flash_tuned_grouped_fmoe.csv" \
AITER_FLYDSL_DISABLE_GEMM1_ACT=0 \
AITER_FLYDSL_DISABLE_GEMM1_REQUANT=0 \
AITER_LOG_MORE=0 FLYDSL_DUMP_IR=0 \
FLYDSL_RUNTIME_CACHE_DIR="$OUT/cache" \
python -u /tmp/repro_fused_moe_tdm_race.py \
--tokens 8 --data-init uniform --sets 2 \
--na 8 --nb 8 --batch 10 \
--single-seconds 15 --seconds 300 --output-dir "$OUT" \
2>&1 | tee "$OUT/run.log"Shape: non-EP A4W4, E96/topk6, D5120/I2304, SiLU, no bias, balanced routing, fused GEMM1 activation/requantization; random uniform data and auto scales. There are two distinct operand allocations. Every concurrent replay forks eight background T8 MoE calls onto a second stream, runs eight foreground calls with separate outputs, joins the streams, and checks all foreground outputs. Background outputs are not checked by this script. Interpretation and controls
Additional check: Xiaobing's unmodified standalone GEMM scriptAlso reran the original script extracted directly from the linked comment, with
Each M ran for 150 seconds per revision. This standalone run did not reproduce the error on main. The fresh discriminating main-BAD / flush-lds-fix-CLEAN evidence is the MoE test above; the two experiments must not be conflated. Both fixed standalone tests completed cleanly. The failure is timing-sensitive. Complete repro_fused_moe_tdm_race.py (the script used for this experiment)#!/usr/bin/env python3
"""Stress real fused_moe outputs with serial/concurrent HIP graph replays.
Shape, initializers, balanced routing and fusion match run_dsv41_flash.sh.
Method follows PR #8486's GEMM reproducer: distinct operands, NaN outputs,
clean eager references, graph fork/join and persistent GPU mismatch counters.
Unlike that reproducer, any bad replay exits nonzero. Time is PER CASE/MODE;
defaults sum to ten minutes (4 tokens x 2 initializations x (15 + 60) seconds),
excluding setup, reference validation and compilation. This is a local diagnostic,
not a timing benchmark. The graph checks every foreground MoE output.
"""
import argparse
import gc
import json
import time
from pathlib import Path
import flydsl
import torch
import aiter
from aiter import ActivationType, QuantType
from aiter.fused_moe import fused_moe
from aiter.jit.utils.chip_info import get_gfx_runtime
from aiter.ops.flydsl.moe_common import GateMode
from aiter.ops.shuffle import moe_shuffle_scale, moe_shuffle_weight
from aiter.utility import dtypes
from op_tests.flydsl_tests import test_flydsl_grouped_gemm as helpers
E, TOPK, D, I = 96, 6, 5120, 2304
def make_weights(mode, seed):
gen = helpers.bench_init.make_generator(seed)
w1 = helpers._pattern_packed(E, 2 * I, D // 2, data_init=mode, generator=gen)
w2 = helpers._pattern_packed(E, D, I // 2, data_init=mode, generator=gen)
scale_mode = "constant" if mode == "constant" else "auto"
s1 = helpers.init_weight_scales(
E, 2 * I, D // 32, scale_init=scale_mode, generator=gen
)
s2 = helpers.init_weight_scales(E, D, I // 32, scale_init=scale_mode, generator=gen)
logical = (w1, s1, w2, s2)
physical = (
moe_shuffle_weight(w1, experts_cnt=E, is_guinterleave=True, gate_up=True).view(
dtypes.fp4x2
),
moe_shuffle_weight(w2, experts_cnt=E).view(dtypes.fp4x2),
moe_shuffle_scale(s1, experts_cnt=E, is_guinterleave=True, gate_up=True),
moe_shuffle_scale(s2, experts_cnt=E),
)
return logical, physical
def make_call(tokens, mode, weights, seed):
gen = helpers.bench_init.make_generator(seed)
hidden = helpers._init_hidden((tokens, D), "a4w4", mode, gen)
# Match the script's balanced top-k routing through the actual fused_topk.
helpers.AITER_MOE_EXPERT_BALANCE = True
ids, probabilities = helpers._make_topk(hidden, E, TOPK)
w1, w2, s1, s2 = weights
def call(out):
result = fused_moe(
hidden,
w1,
w2,
probabilities,
ids,
activation=ActivationType.Silu,
quant_type=QuantType.per_1x32,
w1_scale=s1,
w2_scale=s2,
gate_mode=GateMode.INTERLEAVE.value,
dtype=dtypes.bf16,
swiglu_limit=7.0,
output=out,
)
assert result.data_ptr() == out.data_ptr()
return result
return call, (hidden, probabilities, ids)
def describe_case(call, tokens, init):
from aiter.ops.flydsl import grouped_moe_gfx1250 as grouped
records = []
grouped.kernel_bench_callable = records
try:
call(torch.empty(tokens, D, dtype=torch.bfloat16))
finally:
grouped.kernel_bench_callable = None
for name, function in records:
if name not in ("gemm1", "gemm2"):
continue
params = {
key: value
for key, value in function.keywords.items()
if isinstance(value, (int, float, str, bool))
}
print(
"KERNEL_CONFIG "
+ json.dumps(
{"tokens": tokens, "init": init, "stage": name, "parameters": params}
),
flush=True,
)
def validate_reference(call, inputs, logical):
hidden, probabilities, ids = inputs
w1, s1, w2, s2 = logical
out = call(torch.full((hidden.shape[0], D), float("nan"), dtype=torch.bfloat16))
ref = helpers._torch_moe_ref(
hidden,
w1,
s1,
torch.zeros(E, 2 * I),
w2,
s2,
torch.zeros(E, D),
probabilities,
ids,
data_format="a4w4",
activation=ActivationType.Silu,
swiglu_limit=7.0,
situ_beta=1.0,
situ_linear_beta=1.0,
)
torch.cuda.synchronize()
metric = helpers._logits_diff(out, ref)
finite = bool(torch.isfinite(out).all())
print(
json.dumps(
{
"independent_reference_tokens": hidden.shape[0],
"logits_diff": metric,
"tolerance": helpers.LOGITS_DIFF_TOL,
"finite": finite,
}
),
flush=True,
)
assert (
finite and metric < helpers.LOGITS_DIFF_TOL
), "Eager math/reference check failed"
def stress(tokens, init, calls, bg, args, mode, seconds, output_dir):
na = args.na
refs = torch.stack(
[
calls[i % len(calls)](torch.empty(tokens, D, dtype=torch.bfloat16))
for i in range(na)
]
)
assert bool(torch.isfinite(refs).all()), "Nonfinite eager reference"
outs = torch.empty_like(refs)
# Establish bitwise determinism before using exact comparison for races.
for _ in range(5):
outs.fill_(float("nan"))
for i in range(na):
calls[i % len(calls)](outs[i])
torch.cuda.synchronize()
if not torch.equal(outs, refs):
raise RuntimeError(
f"Eager results are not bitwise stable: T={tokens}, {init}"
)
bad_replays = torch.zeros((), dtype=torch.int64)
bad_launches = torch.zeros((), dtype=torch.int64)
bad_rows = torch.zeros(na, tokens, dtype=torch.int64)
nonfinite = torch.zeros((), dtype=torch.int64)
max_bad = torch.zeros((), dtype=torch.float32)
max_diff = torch.zeros((), dtype=torch.float32)
first_index = torch.full((1,), -1, dtype=torch.int64)
first_actual = torch.zeros(1, dtype=torch.float32)
first_expected = torch.zeros(1, dtype=torch.float32)
# Dedicated background output, never shared with the foreground.
bg_out = torch.empty(8, D, dtype=torch.bfloat16)
foreground, background = torch.cuda.Stream(), torch.cuda.Stream()
with torch.cuda.stream(foreground):
for i in range(na):
calls[i % len(calls)](outs[i])
bg(bg_out)
torch.cuda.synchronize()
def step():
outs.fill_(float("nan"))
if mode == "concurrent":
background.wait_stream(foreground)
with torch.cuda.stream(background):
for _ in range(args.nb):
bg(bg_out)
for i in range(na):
calls[i % len(calls)](outs[i])
if mode == "concurrent":
foreground.wait_stream(background)
differs = outs != refs
rows = differs.any(-1)
take_first = rows.any() & (bad_replays == 0)
index = differs.flatten().to(torch.int32).argmax().reshape(1)
actual = torch.gather(outs.flatten(), 0, index).float()
expected = torch.gather(refs.flatten(), 0, index).float()
torch.where(take_first, index, first_index, out=first_index)
torch.where(take_first, actual, first_actual, out=first_actual)
torch.where(take_first, expected, first_expected, out=first_expected)
bad_replays.add_(rows.any())
bad_launches.add_(rows.any(-1).sum())
bad_rows.add_(rows)
nonfinite.add_((~torch.isfinite(outs)).sum())
torch.maximum(
max_bad,
torch.where(differs, outs.float().abs(), 0).nan_to_num(3e38).amax(),
out=max_bad,
)
torch.maximum(
max_diff,
(outs.float() - refs.float()).abs().nan_to_num(3e38).amax(),
out=max_diff,
)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph, stream=foreground):
step()
torch.cuda.synchronize()
# Capture may execute differently across HIP versions; start counters at zero.
for counter in (bad_replays, bad_launches, bad_rows, nonfinite, max_bad, max_diff):
counter.zero_()
torch.cuda.synchronize()
first_index.fill_(-1)
first_actual.zero_()
first_expected.zero_()
torch.cuda.synchronize()
start, done, last_report = time.monotonic(), 0, 0.0
print(
f"START tokens={tokens} init={init} mode={mode} seconds={seconds}", flush=True
)
while time.monotonic() - start < seconds:
for _ in range(args.batch):
graph.replay()
done += 1
torch.cuda.synchronize()
elapsed = time.monotonic() - start
bad = int(bad_replays)
if elapsed - last_report >= 15 or bad:
print(
f"PROGRESS tokens={tokens} init={init} mode={mode} seconds={elapsed:.2f} replays={done} bad={bad}",
flush=True,
)
last_report = elapsed
if bad:
break
elapsed = time.monotonic() - start
result = {
"tokens": tokens,
"initialization": init,
"mode": mode,
"seconds": elapsed,
"replays": done,
"launches": done * na,
"bad_replays": int(bad_replays),
"bad_launches": int(bad_launches),
"nonfinite_elements": int(nonfinite),
"max_bad_magnitude": float(max_bad),
"max_abs_diff": float(max_diff),
}
if result["bad_replays"]:
# Counters cover EVERY replay; these are the last replay's outputs only.
flat = int(first_index.item())
result["first_bad_element"] = {
"launch": flat // (tokens * D),
"row": (flat // D) % tokens,
"column": flat % D,
"actual": float(first_actual.item()),
"expected": float(first_expected.item()),
}
result["affected_launch_rows"] = torch.nonzero(bad_rows).cpu().tolist()
torch.save(
{
"last_replay_output": outs.cpu(),
"reference": refs.cpu(),
"cumulative_bad_rows": bad_rows.cpu(),
"result": result,
},
output_dir / f"bad_t{tokens}_{init}_{mode}.pt",
)
print("RESULT " + json.dumps(result), flush=True)
with (output_dir / "results.jsonl").open("a") as f:
f.write(json.dumps(result) + "\n")
del graph
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--tokens", nargs="+", type=int, default=[8, 64, 512, 16384])
parser.add_argument(
"--data-init",
nargs="+",
choices=["constant", "uniform"],
default=["constant", "uniform"],
)
parser.add_argument("--seconds", type=float, default=60)
parser.add_argument("--single-seconds", type=float, default=15)
parser.add_argument("--sets", type=int, default=2)
parser.add_argument("--na", type=int, default=8)
parser.add_argument("--nb", type=int, default=8)
parser.add_argument("--batch", type=int, default=10)
parser.add_argument("--output-dir", type=Path, required=True)
args = parser.parse_args()
args.output_dir.mkdir(parents=True, exist_ok=True)
assert get_gfx_runtime() == "gfx1250"
print(
json.dumps(
{
"aiter": aiter.__file__,
"flydsl": flydsl.__version__,
"torch": torch.__version__,
"shape": [E, TOPK, D, I],
"args": {
k: str(v) if isinstance(v, Path) else v
for k, v in vars(args).items()
},
}
),
flush=True,
)
torch.manual_seed(0)
for init in args.data_init:
logical, weights = make_weights(init, 0)
small_call, small_inputs = make_call(8, init, weights, 0)
validate_reference(small_call, small_inputs, logical)
del logical, small_inputs
bg = small_call
# Each weight set has an independent allocation (cold model-layer traffic).
weight_sets = [weights]
other_weights = None
for seed in range(1, args.sets):
other_logical, other_weights = make_weights(init, seed)
del other_logical
weight_sets.append(other_weights)
for tokens in args.tokens:
calls = [
make_call(tokens, init, w, seed)[0]
for seed, w in enumerate(weight_sets)
]
describe_case(calls[0], tokens, init)
for mode, seconds in [
("single", args.single_seconds),
("concurrent", args.seconds),
]:
if seconds <= 0:
continue
result = stress(
tokens, init, calls, bg, args, mode, seconds, args.output_dir
)
if result["bad_replays"]:
raise SystemExit(1)
del calls
gc.collect()
del weight_sets, weights, other_weights, bg, small_call
gc.collect()
print("ALL CASES CLEAN", flush=True)
if __name__ == "__main__":
main()Standalone GEMM follow-up: doubled main budgetReran the exact, unmodified script in Xiaobing's comment, using its default background
Current standalone main did not reproduce in this run. The subsequent fixed-version workload was cancelled before launch to focus on reproducing main first. This is not discriminating evidence of a standalone fix. Historical standalone failures and the fresh MoE mismatch reported above are separate experiments. Standalone GEMM repeat: current main reproduced BADA second main-only run with the exact same original Xiaobing script and
M64 affected rows 48 and 49; maximum absolute bad output was Full log SHA256: Matched standalone GEMM validation: main BAD, flush-lds-fix CLEANAfter reproducing the main failure above, ran the same unmodified Xiaobing script on python -u repro_gemm_a8w8_tdm_race.py --m 8,64 --n 6144 --k 768 --seconds 300 --moe-t 8
Main: flush-lds-fix: This provides a main-BAD / fixed-CLEAN result for the original standalone GEMM reproducer. It is finite stress-test evidence, not proof that failures are impossible. The original script reports aggregate counters only; exact first-failure time is unknown. Background MoE outputs are not checked. Replay timings include concurrent background work and correctness checks and are not isolated GEMM performance measurements. The earlier clean main runs remain recorded above because the issue is intermittent. Full fixed-run summary: Log SHA256:
Additional compiler-version check: FlyDSL 0.5.0Retested unmodified main
Result: FlyDSL 0.5.0 follow-up: five-minute main testExtended the measured budget to 150 seconds each for M8/M64, five minutes total, keeping main
Final result: Isolation qualification: GPU lock remained occupied while no KFD processes were reported, so the queued launch was cancelled and the user-authorized direct launch after ten seconds of zero GPU/memory activity was used. One activity sample during the run contained two KFD PIDs (103307 and 98072); later samples contained one. Consequently, this run must not be described as isolated for its full duration. The idle helper's generic log wording “inside gpu-lock” does not apply to this direct launch. |
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.
Brings in #8246's merge of main (#8737: flush LDS before the TDM C store, ported to the fused split-K epilogue), its pinned untuned-fallback picks, the re-measured us of its rows and five faster rows (DSv4 4096x8192 M 16 / 32 / 64, K3 8448x7168 M 160, 1536x7168 M 544). Conflicts resolved: - Tuned tables, per row against 5a73f40: rows whose kernel this branch changed or added stay as here; rows whose kernel only #8246 changed, and rows with the same kernel and new us, take #8246's line. - test_gemm_a8w8_mxfp8_bpreshuffle.py: #8246's comment on the uneven splits; test_untuned_fallback_pick keeps the underfill check and the pinned picks.
#8978) * K3 TP1 a8w8 GEMM: compute N tail, underfilled tiles, aligned A-scale loads, retuned rows (#8778 @ ea7a5d8) #8778 (aoli26; base main; open) applied to k3-455-dev as its net change on its 19 files at head ea7a5d8 (2026-11-26T14:47:07Z), 3-way against the PR's main base adbb6ac. The 8 files k3-455-dev had changed (all only by #8246 @ 15808c7) take the PR's version, so all 19 files equal the PR head. It carries the newer #8246 (ccc4270), the table PRs #8579 / #8586 / #8601 and main's #8566 (its compute guard, which #8778 replaces); no other main change rides in. Validated in the K3 1P1D integration branch (aiter zejun/k3-455-dev 627e1eb) on 16 MI455X (wuhuikx/LLM-Booster#578). The PR head has moved on since (204ce9d: merges of #8246 @ 0d6cf15 and of main, which brings #8737); those can follow when #8778 lands. Co-authored-by: zejunchen-zejun <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> * Update K3 FP8 kernels to c997 and add exact-M tuning Preserve the existing dev wrappers and bucket tables. Add 162 accepted retuned exact configurations and 3 c997-default compatibility records, with CPU dispatch coverage for all 675 measured points. Backport the three kernel files from c99781c without merging main history. Integrated-head GPU validation remains outstanding. --------- Co-authored-by: aoli26 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Zhang <[email protected]>
| "v_add_nc_u32 $1, $3, $1\n" | ||
| "v_mov_b32 $2, 0\n" | ||
| "s_wait_alu depctr_va_vdst(0)\n" | ||
| "ds_store_b32 $1, $2\n" |
There was a problem hiding this comment.
We should build bank-conflict 5 addr here then submit the store into the lds write-queue to drain the in-flight lds requests
#8978) * K3 TP1 a8w8 GEMM: compute N tail, underfilled tiles, aligned A-scale loads, retuned rows (#8778 @ ea7a5d8) #8778 (aoli26; base main; open) applied to k3-455-dev as its net change on its 19 files at head ea7a5d8 (2026-11-26T14:47:07Z), 3-way against the PR's main base adbb6ac. The 8 files k3-455-dev had changed (all only by #8246 @ 15808c7) take the PR's version, so all 19 files equal the PR head. It carries the newer #8246 (ccc4270), the table PRs #8579 / #8586 / #8601 and main's #8566 (its compute guard, which #8778 replaces); no other main change rides in. Validated in the K3 1P1D integration branch (aiter zejun/k3-455-dev 627e1eb) on 16 MI455X (wuhuikx/LLM-Booster#578). The PR head has moved on since (204ce9d: merges of #8246 @ 0d6cf15 and of main, which brings #8737); those can follow when #8778 lands. Co-authored-by: zejunchen-zejun <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> * Update K3 FP8 kernels to c997 and add exact-M tuning Preserve the existing dev wrappers and bucket tables. Add 162 accepted retuned exact configurations and 3 c997-default compatibility records, with CPU dispatch coverage for all 675 measured points. Backport the three kernel files from c99781c without merging main history. Integrated-head GPU validation remains outstanding. --------- Co-authored-by: aoli26 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Zhang <[email protected]> (cherry picked from commit 1cc9d02) Rebase onto main 12-03: the 19 files keep this commit's content; only main's later changes are added: the AOT launcher factories of #8678 (mxfp8 / batched wrappers launch gemm_a8w8_launcher.lazy(), _gemm_a8w8_compute_bound_launcher.lazy(), splitk_reduce_launcher.lazy(); _lazy_import keeps _data_ptr), #7449's deferred split-K entry points and #8636's ragged-K fallback. gemm_a8w8_gfx1250.py: this commit's rank0 split-K epilogue and flush_addr (it already carries #8737's flush). gemm_op_a8w8.py: main's #8566 guard in get_mxscale_bpreshuffle_config (no padded row below a compute kernel's M tile) is removed, as on the #8778 head, because the c997 compute kernel serves underfilled tiles; test_gemm_host_dispatch_cache.py takes #8778's test_mxscale_compute_row_serves_underfilled_m_tile in place of main's two guard tests. kimik3 mxscale tuned CSV: this commit's rows (626 changed or added) replayed by key; the result equals this commit's table. Rebase onto main 12-03: main #7449 moved the bpreshuffle row lookup into _bpreshuffle_config(XQ, WQ); this commit's Kimi-K3 exact-row lookup there needs x_scale, w_scale and Y, so _bpreshuffle_config takes them (the deferred split-K path passes a meta tensor of the output's shape and dtype, so it picks the same row as gemm_a8w8_bpreshuffle). Rebase onto main 12-03: op_tests/test_gemm_a8w8_mxfp8_bpreshuffle.py counts reduce launches through splitk_reduce_launcher.lazy (main #8678 replaced _compile_splitk_reduce).
…DSpark draft head BF16 tuning, empty-row GEMM fix (#9096) * MegaMoE gfx1250: decode megakernel (dispatch, GEMM1, GEMM2 and combine in one launch), Kimi-K3 shapes (#7345 @ a559927, head 2026-12-01T13:13:28Z) Opt-in with AITER_MEGAKERNEL=1. Each step chooses by its receive bound: - "slots" (fixed per-expert slots) for bounds up to SLOTS_RECV (2048; with IOD-placed weights, 3072 for Kimi-K3's 3584 x 3072); - "compact" up to COMPACT_MAX_TOKENS per rank; - otherwise the staged path. Off by default, so nothing changes unless the variable is set. The PR's tests show the output bitwise equal to the staged path. Ported onto k3-455-dev as the squashed PR diff (merge base ce334d0). Four files conflicted: - s1f_ctl.py: kept k3-455-dev's receive caps (_S1F_MAX_RECV 4096 plus #8189's _S1F_MAX_RECV_BY_SHAPE) and its s1f_max_recv(); the PR's base had no cap. Both __init__ fields are kept (#8483's _plan_lds, the PR's _packed_sc). - s1f_stage1.py: added the PR's s1f_apre_* helpers. The stage-1 launch keeps #8483's SiTUv2 arguments and adds the PR's value_attrs. - gemm_common_gfx1250.py: kept k3-455-dev's prefetch_kernel_code(max_bytes=...), a superset of the PR's. - dsr1_tuned_grouped_fmoe.csv: kept k3-455-dev's DeepSeek-R1 rows and dropped the PR's two DSR1 rows (not Kimi-K3). Placement is detected from the GEMM builder's signature (BUILDER_LOC), so without IOD placement the placed paths stay off. Co-Authored-By: Claude Opus 5.5 <[email protected]> * MegaMoE gfx1250 compact plan: re-seal the hist row head from each issuing wave before its TDM store (#8880 @ 4214819, head 2026-11-28T16:07:47Z) Fixes the intermittent S1F spin trap (HSA_STATUS_ERROR_EXCEPTION 0x1016): the TDM that sends a hist row to rank w is issued by wave w and could read the row head before wave 0's LDS tag was visible to it. Every sending wave now re-seals the tag before its store. Kimi-K3's D runs this compact plan (dispatch=compact). (cherry picked from commit 4214819) Co-Authored-By: Claude Opus 5.5 <[email protected]> * bench_mega_moe: SiTUv2, a model-sized instance and a simulated EP size, for Kimi-K3's A/Bs --act situv2 (with --situ_beta / --situ_linear_beta), --max_tpr / --recv_bound and --sim_ep N (a rank of an EP-N group on fewer GPUs, e.g. EP8 on one tray with -e 448 --sim_ep 8), all opt-in. Same commit as on the IOD branch (zejun/k3-455-dev-1201-iod); here it is merged with #7345's bench: #7345's routing checks stay, and the step bounds come from resolve_step_bounds, which equals #7345's inline logic without --sim_ep. Co-Authored-By: Claude Opus 5.5 <[email protected]> * [Config] Kimi-K3 gfx1250 LM head and DSpark draft head BF16 rows (N 163840, K 7168), M 1-256 Neither head had a gfx1250 row, so both ran the default bandwidth-bound gemm_a16w16 at 3.4-4.3 TB/s (one D decode step at c192: 546-603 us for the target head, ~360-600 us for the draft head). A FlyDSL hgemm whose M tile covers every row reads the 2.35 GB weight once: per M bucket (32 / 64 / 96 / 128 / 160 / 192 / 256 rows) the best block_n / block_k / stages / waves of a tdm or ft sweep, measured with 2 weight copies alternated in a CUDA graph on one MI455X (bf16 error 3e-3, fp32 3e-6 against an f32 matmul): rows bf16 out fp32 out 1-32 1.04-1.16x 1.0-1.12x (rows <= 8 keep production) 33-64 1.25-1.37x 1.31-1.35x 65-128 1.43-1.62x 1.53-1.63x 129-160 2.04-2.44x 2.10-2.43x (c192's verify / draft rows) 161-192 2.33-2.49x 2.42-2.66x 193-256 2.10-2.72x 2.17-2.77x At c192 (133-175 rows) that is ~300-500 us a head, ~0.6 ms a D step. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tuned_gemm: an empty-row FlyDSL GEMM returns the empty product instead of launching An idle DP rank's dummy step runs its GEMMs with M = 0, and the lookup pads M = 0 into a tuned row: with a FlyDSL row there (Kimi-K3's head rows, the commit before) validate_gemm_gfx1250_config refused the empty dimension and the engine died at its first prefill ("dimensions, tiles, stages, wave counts and WMMA sizes must be positive integers"; DP4 one-tray D, 12-02). Return the [0, N] result (or the caller's buffer) without a launch, as the default kernel effectively did. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Honglie Yi <[email protected]> (cherry picked from commit 4c4e333) Rebase onto main 12-03: main since has #8189's final head, #8889 (packed A only where its stores fit storecnt, tdm_b_th from the tuned row) and #8737 (LDS-to-TDM flush, C staged at the arena tail). Resolved: s1f_ctl.py keeps main's _s1f_gemm_opts / _s1f_packed_a_ok / s1f_prefill_tile(config, ...) / _s1f_warps(config, ...) (this commit's same-purpose _gemm_opts method and (world_size, topk) helpers are dropped) and adds this commit's IOD placement next to main's tdm_b_th: _launcher / _precompile take both, the launcher key and the precompile keys carry (tdm_b_th, placed), make_s1f_stage1 gets tdm_b_th, b_placed, loc_group. s1f_stage1.py: the producer role is this commit's s1f_produce(_PCtx(...)) (its body is main's inline producer, packed A and WAIT_STEPS included); OP_STORES / the storecnt check use main's s1f_packed_a_op_stores / s1f_packed_a_fits (R is 8 there); make_s1f_stage1 takes tdm_b_th and b_placed / loc_group; imports both. dispatch_compact.py: main's 4-tuple _compact_gemm_tiles. mxfp4_preshuffle_gfx1250_tdm.py: main's single C_OFF staging (arena tail, flush scratch at the head) is kept; this commit's a/c cache modifiers, scatter cache policy and defer_ep_wait are added, defer_ep_wait moving C_OFF past the input stages (and growing the arena) instead of this commit's C_EP_OFF / C_Q_OFF; the kernel name carries both suffixes. kimik3_bf16_tuned_gemm.csv: the 504 LM / draft head rows replayed by key. Multi-GPU MegaMoE / megakernel not run on the rebased tree. Rebase onto main 12-03: after #8483 was updated to its PR head 21120ee (which adds its own bench_mega_moe flags --max_tokens_per_rank / --activation / --situ_beta), op_tests/multigpu_tests/bench_mega_moe.py keeps this commit's version (--max_tpr / --recv_bound / --act / --situ_beta / --sim_ep cover the same knobs); taking both would define --situ_beta twice.
Summary
Concurrent HIP graph replay can corrupt gfx1250 FlyDSL GEMM and grouped MoE outputs when LDS payload stores are followed by a TDM output store. Add a shared LDS flush workaround before the existing output barrier and TDM store.
Related investigation/reproducer: #8486.
Motivation
Using the concurrent replay method from #8486, unmodified main reproduced a MoE output mismatch after 23.277 seconds. Ordinary DS-load forwarding versus TDM visibility is a working hypothesis, not a confirmed hardware root cause. The first verified compiler fix version is currently unknown; keep a local placeholder for tracking it.
Changes
flush_lds_store: five active lanes write bank-conflicting scratch addresses at 256-byte strides, read them back, restore EXEC, and drain DS operations. Explicit ALU dependency waits protect the inline-assembly address calculation.get_flush_lds_size(num_waves)to reserve disjoint scratch addresses per wave.C_OFF >= FLUSH_BYTES.Performance
No material performance gap in combined GEMM time was observed between
main (baseline)andflush-lds-fixin this sweep. Across tokens 1..32768 and constant/random initialization, the median GEMM1+GEMM2 latency change is -0.73% to +0.88%. Prefill tokens 4096..32768 are +0.21% to +0.67%. These measurements support a small sub-1% combined cost; they do not establish exactly zero overhead.Configuration: one gfx1250 GPU (256 CUs), FlyDSL 0.5.3, E96/topk6, D5120/I2304, balanced routing, fused GEMM1 activation/requantization, warmup=5, iters=32, seed=0. Three interleaved runs per revision: main/fix/fix/main/main/fix. Same CSV and native
run_dsv41_flash.shper-kernel timing path; the local script copies replace its obsolete 0.5.0 pin with requirements-pinned 0.5.3. All 192/192 accuracy checks passed.9fe009c8c5a189a39f36a775acb57330d80a7e7a864c823c7a0e187b25c19ba547d510bfe732a6c6The tables below use random initialization:
--data-init uniform --scale-init auto --seed 0, with medians of three runs. BW is effective TB/s, computed from the benchmark byte-count model divided by kernel latency; it is not measured HBM traffic. Positive throughput change means faster. TFLOPS and BW have the same relative change for a fixed workload (subject to displayed rounding).GEMM1 — random (uniform / auto scales)
GEMM2 — random (uniform / auto scales)
Combined latency is the per-run sum of separately timed GEMM1 and GEMM2, not end-to-end MoE. Individual stages show more variation: for example, token512 constant GEMM2 is 37.51 -> 38.49 us (+2.62%), while its combined latency changes by +0.71%. Small differences overlap run-to-run variation; the raw stage results above are retained rather than claiming identical timings.
On gfx1250, the tested 256x256x256 prefill GEMM1/GEMM2 retain their 327680-byte LDS arena; smaller configurations may require additional LDS capacity. Replay throughput in the correctness tests below includes validation and is not a performance benchmark.
Testing
Hardware: gfx1250, 256 CUs. FlyDSL: 0.5.3. Baseline:
9e5e03626fa119f2429fa1c1578d5a715a6c2401.Matched MoE test: E96, topk6, D5120/I2304, T8, balanced routing, uniform data/auto scales, fused activation and requantization. After a clean 15-second serial control, replay two concurrent streams with eight foreground and eight background MoE calls per replay; check foreground outputs exactly against stable eager references and stop on first mismatch.
The baseline's first latched mismatch was row 7, column 2272: actual -9024 versus expected -8832. Both versions used identical CSV configurations and the same shared MoE extension binary.
Fresh confirmation against main
9fe009c8c5using the same MoE checker:Both 15-second serial controls passed. Main's first latched mismatch was launch 6, row 1, column 3312: actual -17792 versus expected -19968; maximum absolute difference 7768, with no NaN/Inf. Source revisions, script hashes, CSV bytes, runtime kernel parameters and shared MoE extension were checked. Fresh ISA confirms the flush precedes the existing barrier/TDM store in both grouped stages. This is a finite stress result, not proof of universal elimination.
Additional check: Xiaobing's unmodified standalone GEMM script
Also reran the original script extracted directly from the linked comment, with
--m 8,64 --n 6144 --k 768 --seconds 150 --moe-t 2:Each M ran for 150 seconds per revision. This standalone run did not reproduce the error on main. The fresh discriminating main-BAD / flush-lds-fix-CLEAN evidence is the MoE test above; the two experiments must not be conflated. Both fixed standalone tests completed cleanly. The failure is timing-sensitive.
Additional validation:
Eight independent quant-aware MoE reference checks: tokens 8/64/512/16384, constant/random initialization.
Four A4W4 checks covering activation without fused requantization and separate activation/requantization; two explicit A8W4 checks.
Standalone GEMM: 16 shapes each for BF16 and FP16, including output-boundary sentinel checks.
Original standalone concurrent GEMM reproducer: 150 seconds each for M8/M64; zero bad replays out of 351,800/281,000 (64 GEMM calls per replay).
Final-source fresh-cache correctness checks and ISA equivalence after localizing helper constants.
Ruff, Black, and
git diff --checkpassed.Unit tests added or updated
Performance benchmarks run
Tested on MI250X
Tested on MI300X
Documentation
Dependencies
Breaking Changes
None.
PR Self-Review
Reviewed revision
864c823c7a(local review; automated review has not run yet).Behavior and intent
Order LDS payload visibility before TDM output stores while keeping scratch disjoint from live output. Preserve the original barriers; the flush does not replace cross-wave synchronization.
Validation and unverified scope
The results above support the workaround under the tested conditions; finite clean runs do not prove universal elimination. Distributed EP and S1F persistent execution remain unverified. Diagnostic scripts and logs are local under
/workspace/experiments/pr8486/tail_c/and/workspace/experiments/pr8486/final_ab/; performance data is under/workspace/experiments/pr8486/perf_flash/; they are not included in this PR. This change targets gfx1250 only.PR-specific question
Pending automated review question.
Changed op tests
None. Validation used local reproduction and reference-check scripts.
Full runnable MoE reproducer and detection criteria: #8737 (comment)