Skip to content

[HIP] [CK] [FlyDSL] [GEMM][gfx950] Tune narrow-N MXFP4 with CSV-selected preshuffle kernels - #7317

Merged
yifehuan merged 2 commits into
mainfrom
yifehuan/dispatch_smallm
Nov 4, 2026
Merged

yifehuan merged 2 commits into
mainfrom
yifehuan/dispatch_smallm

Conversation

@yifehuan

@yifehuan yifehuan commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Optimize the default aiter.gemm_a4w4 narrow-N dense MXFP4 path with CSV-selected Triton and FlyDSL kernels for preshuffled MXFP4 weights (B). The selected kernels consume the existing ATOM-compatible layout:

Input Layout used by this PR
Activation A Packed, row-major MXFP4 (apreshuffle=False)
Weight B Preshuffled MXFP4 (bpreshuffle=True)
A/B scales Existing shuffled per-1x32 scale storage (mfma_tile)

The adapter changes tensor views only. Weight preparation and dynamic activation quantization remain outside the GEMM dispatch call.

On MI355X, (M,N,K)=(128,512,7168) drops from approximately 22.9 µs on the default CK path to 7.84 µs on Triton with the same B-preshuffled inputs and scale storage.

Refs #7287. This addresses the dense Linear tuning/dispatch gap; related work is tracked in #6632, #6683 and #7117.

Motivation

The default gemm_a4w4 tune CSV selects CK/ASM kernels. Existing B-preshuffled Triton and FlyDSL kernels improve latency on the qualified narrow-N shapes while consuming the same operands and shuffled per-1x32 scales. This PR lets the existing tune CSV select those kernels for verified exact-M keys.

Changes

  • Keep the layout adapter in aiter/ops/gemm_op_a4w4.py. Triton rows call gemm_afp4wfp4_preshuffle; FlyDSL rows call flydsl_mxscale_preshuffle_gemm with per-1x32 mfma_tile scales. Both consume preshuffled B, row-major packed A and the existing scale storage; the adapter changes views only.
  • Extend the existing A4W4 tuner with --backends ck,asm,triton,flydsl; its default remains ck,asm. Filter foreign names out of CK codegen while registering their recorded CK fallbacks, and register the A4W4 blockscale table with main's runtime-replay FlyDSL AOT driver.
  • Install 43 explicit gfx950/256-CU BF16 rows in aiter/configs/model_configs/narrow_n_a4w4_blockscale_tuned_gemm.csv: 22 triton_preshuffle_* and 21 flydsl_mxpsh_* kernels. N is 256/512, K is 4096/7168/8192, and qualified M values lie from 32 through 256. This is not the full Cartesian product. Remove six overlapping canonical keys to keep the merged family collision-free. CSV latency is in µs and bw follows the existing tuner's GB/s convention.
  • Apply foreign rows only at exact M. Optional fallbackKernelName/fallbackSplitK preserve the old CK/ASM choice for padded M and unsupported calls. Missing FlyDSL falls back; malformed names and launch failures surface. AITER_LOG_TUNED_CONFIG=1 emits a cached fallback message identifying the configured and fallback kernels; the test table labels configuration as configured kernel.
  • Reuse op_tests/test_gemm_a4w4.py for tuned/baseline candidates and an untimed FP32 reference. The PR updates existing dispatch, tuning and benchmark owners, with no new Python modules or experimental report/test files.

Performance (if applicable)

Both performance rows below measure GEMM with preshuffled weights, using the dispatch implemented by this PR. The comparison uses the same quantized values, B layout and shuffled per-1x32 scale storage for the CK baseline and selected Triton kernel.

Hardware Workload/configuration Before After Change
MI355X / gfx950 / 256 CUs BF16, (128,512,7168), cold dense MXFP4 GEMM, CK → Triton; both use preshuffled B and the same A/scales 22.90–22.91 µs 7.8369–7.8401 µs 2.916–2.922× faster
Same Dynamic MXFP4 quantization + B-preshuffled cold GEMM 25.48–25.55 µs 10.40–10.42 µs 2.445–2.457× faster

Measurements used PyTorch 2.10.0 / ROCm 7.2.4, Triton 3.8.0 and FlyDSL 0.4.1 on crsuse2-m2m-264. Each finalist used two fresh seeds/passes, reversed capture order, and ten baseline-before/candidate/baseline-after HIP-graph samples per mode. Cold weights rotate through at least 512 MiB; GEMM timing excludes quantization, weight/layout preparation and JIT. The second row explicitly includes dynamic quantization.

The performance evidence above was collected before the review-only fixes, at the source represented by 66c3cec; kernel implementations and recorded launch parameters are unchanged. The review follow-up makes the measured Triton .cg setting explicit as _cmcg in the same 22 rows. Requalification covered all 43 installed shapes, 64,761 search records and 573 finalists (1,146 paired acceptance runs). The compatible FlyDSL catalog was fully scanned, including 7,956 successful compile jobs. Triton used a bounded tile/split/stage sweep plus main's actual default/tuned configurations. Rows select the lowest worst-pass cold latency among candidates passing numerical/graph checks, at least 1.05× speedup in all measured modes/passes and at most 3% within-pass baseline drift. These are stable winners within that search, not a claim of optimality over every possible Triton configuration or an end-to-end model speedup.

Testing

  • Unit tests added or updated
  • Performance benchmarks run
  • Tested on MI250X
  • Tested on MI300X

On the actual production CSV:

  • Profiler-confirmed kernel selection for 43 rows; 1,800 lookup cases (M=1…300 across six N/K combinations) preserve the original padded-M selection.
  • 344 structured input cases (43 shapes × two seeds × random/zero/signed/sparse) produce finite, byte-exact BF16 outputs versus the original path and FP32 relative L2 below 0.01. Dynamic-quantization graph replay passed; CK FP16 fallback is byte-exact, and original ASM FP16 rejection is preserved.
  • Existing op test passed 43 rows plus 12 large-N controls. Large-N configuration choices match the original choices; this is not a separate paired large-N timing regression sweep.
  • Real CK registry checks: 2 passed. python -m unittest op_tests.tuning_tests.test_config_shape_collision op_tests.tuning_tests.test_csv_validation -q: 49 passed in the ROCm container. CPU routing, fallback-log and CLI selection checks: 36 passed, one inapplicable skip.
  • Rebased onto main e4973c4bed57a615068089fa02c88c64d644fd42 on 2026-11-04. Main's nine AOT tables retain all 24,378 existing replay jobs. The new A4W4 table selects the 21 FlyDSL CSV rows by kernel name, and replays the public gemm_a4w4 call with 256-row-padded shuffled scales. All 21 row replays and 21 smaller-M probes passed both fresh AOT compilation and subsequent run-only --check. The existing AOT replay test file now checks that each installed FlyDSL row reaches a FlyDSL launcher; all six tests passed. The real configuration/CSV suite passed 50 tests without skips, and CPU routing/logging/CLI checks passed 36 tests with one inapplicable skip. This validation used a ROCm container with GPUs hidden (Torch 2.10.0, ROCm 7.2.4, Triton 3.8.0, FlyDSL 0.4.1); it verifies AOT compilation and routing, not new GPU numerical or performance results. Ruff, Black and git diff --check passed.
  • Repository skills: all 21 derived review rules and seven review gates passed, with independent refutation finding no unresolved issue. A temporary merge with main 3febddf6a1017549d3eef1ef02846a089fbe1c9c passed the 49 configuration/CSV checks, all 43 GPU op-test pairs and four profiler/byte/fixed-output/graph cases. The native local review validator could not establish an idle AMD GPU, so no complete deterministic validator PASS is claimed; remote MI355X evidence is reported separately.
  • Review follow-up validation on MI355X: the unmodified CI script entry point (python op_tests/test_gemm_a4w4.py) now expands to 110 default shapes including all 43 new CSV keys. The GPU probe verified the actual merged-CSV/default selection; python op_tests/test_gemm_a4w4.py --csv aiter/configs/model_configs/narrow_n_a4w4_blockscale_tuned_gemm.csv passed all 43 tuned/baseline comparisons.
  • bench_gemm_mixed_mxfp.py::_setup_a4w4 passed four cases spanning FlyDSL, Triton and the existing large-N CK path, with profiler-confirmed kernels, byte-exact output against the public API, fixed output-buffer identity and static/dynamic graph replay. Its direct-kernel benchmark now rejects an unavailable configured FlyDSL kernel explicitly instead of pretending to time it.
  • GitHub CI for the rebased head 94b97579b949c6785d38404976138eb35d1c76a8 passed on 2026-11-04: Python 3.12 wheel build and verification, all eight MI35X Standard Tests shards, OPUS MI35X, Tuned Op Bench, Standard Test Results, Aiter Test Gate and the code/dependency checks. All four required checks passed; the rollup contains 30 successful checks and 27 scope skips. The Python 3.10 wheel job skipped its build steps, and the dedicated Triton GPU workflow shards were skipped by scope. Aiter Test run.

Latest review/rebase validation is retained in evidence/review_followup and evidence/rebase_20261104 under the external artifact directory below.

Raw tuning/validation artifacts are retained outside the source checkout at /home/yifehuan/monofly/aiter_narrow_n_20261030/dispatch_smallm_generalization_20261102, including selected_rows.json and evidence/node264/final_validation/results.json.

Documentation

  • Docstrings updated
  • User guide updated
  • Performance guide updated
  • No documentation change is needed, with the reason stated below

The existing A4W4 tuner README documents backend selection, the production CSV and fallback contract.

Dependencies

  • No new third-party dependencies added
  • New dependencies are listed and justified below

FlyDSL remains optional for this dispatch route; its existing parser and launcher are imported only when it is available.

Breaking Changes

None to the public API or existing CK/ASM rows. New backend rows encode launch settings in kernelName and can retain a CK/ASM fallback in optional columns.

PR Self-Review

Reviewed revision

94b9757

Behavior and intent

Qualified exact-M CSV rows invoke existing B-preshuffled Triton/FlyDSL kernels with row-major packed A and shuffled per-1x32 scales, retaining CK/ASM fallbacks outside that call contract. The mixed-MXFP benchmark now recognizes those foreign names instead of handing them to CK. The default gfx950 op test includes all matching foreign CSV rows, and optional fallback logging distinguishes configured kernels from executed fallbacks. FlyDSL AOT now replays the A4W4 blockscale table through the same public GEMM entry, retaining main's replay architecture. No kernel implementation or public GEMM signature changes.

Validation and unverified scope

This revision rebases the two feature/review commits onto main e4973c4bed57a615068089fa02c88c64d644fd42. The FlyDSL AOT conflict was resolved by registering the A4W4 blockscale table with main's public-entry replay driver. The nine existing AOT tables retain all 24,378 replay jobs. All 21 installed FlyDSL rows reach a FlyDSL launcher in the new CPU dry-run test, and all 21 rows plus 21 smaller-M probes passed fresh AOT compilation followed by run-only --check. The six AOT replay tests, 50 real configuration/CSV checks (no skips), 36 CPU routing/logging/CLI checks (one inapplicable skip), Ruff, Black and git diff --check passed. The ROCm container had GPUs hidden; this is compilation/routing evidence. Rebased-head CI passed on 2026-11-04, including all eight MI35X Standard Tests shards, OPUS, Tuned Op Bench and Aiter Test Gate; all four required checks passed (30 successful checks, 27 scope skips).

The CSV, GEMM op test, mixed benchmark, tuner, CK codegen and tuner README are byte-identical to the verified pre-rebase head 1bc0f11; its cache/default/fallback and symmetric allocation review fixes are preserved. That pre-rebase head passed the 43 GPU tuned/baseline comparisons and four profiler/byte/graph cases, and its CI completed successfully on 2026-11-03. The performance qualification and 344 structured-input / 1,800-lookup checks remain the evidence from the implementation represented by 66c3cec; the 22 Triton names explicitly retain the measured .cg setting as _cmcg. The 2.92× claim is the recorded paired standalone measurement, not a CI performance claim. The rebased head passed the MI35X GPU CI above. Dedicated post-rebase GPU bit-exact/performance requalification, other GPU architectures, current ATOM nightly, full-model latency, an exhaustive Triton search and an independent paired large-N timing sweep remain unverified. Dedicated Triton workflow shards previously skipped by scope are not GPU validation evidence.

PR-specific question

Foreign kernel selection requires a gfx950/CU/M/N/K CSV match at exact M, B preshuffle, row-major A, contiguous byte operands and the default shuffled per-1x32 scale storage, with M>=32, N%16=0 and K%256=0. Triton rows require BF16; FlyDSL additionally validates its encoded dtype and tile/split constraints. Calls outside the stated shape, input-layout and output-dtype contract, or with bias, global scales or nontrivial alpha/beta, retain the recorded CK/ASM fallback. The CK generator excludes foreign names and still validates/registers genuine CK fallbacks. Logging is opt-in and cached by shape/dtype/kernel; the direct-kernel benchmark fails an unsupported foreign launch explicitly. These boundaries prevent unqualified launches and misleading backend timings.

Changed op tests

  • op_tests/test_gemm_a4w4.py compares the public tuned path and recorded CK/ASM baseline against its untimed FP32 reference. Both tuned and CK/ASM baseline candidates allocate an output inside each timed call. Its default gfx950 sweep now adds all 43 matching CSV-selected preshuffle shapes, while explicit -mnk/--csv inputs and gfx1250 table/off-grid behavior are preserved. The table labels the CSV configuration as configured kernel instead of implying profiler-confirmed execution.
  • op_tests/op_benchmarks/hip/bench_gemm_mixed_mxfp.py is an existing consumer of get_GEMM_config. It now routes Triton/FlyDSL names through the shared preshuffle adapter while retaining its fixed output buffer and direct CK/ASM timing. This fixes the foreign-name CK registry failure and reports the selected backend correctly; an unavailable/unsupported foreign candidate fails explicitly.
  • tests/test_flydsl_aot_replay.py checks all 21 production FlyDSL rows through the actual public-entry AOT replay with FakeTensors and verifies that each requests a FlyDSL kernel cache key. It catches incorrect table filtering or scale padding that would silently fall back.

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
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 gfx1201 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 7317 --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.

@aiter-bot

aiter-bot commented Nov 2, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

Revision 94b97579b949 · 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

Qualified exact-M CSV rows invoke existing B-preshuffled Triton/FlyDSL kernels with row-major packed A and shuffled per-1x32 scales, retaining CK/ASM fallbacks outside that call contract. The mixed-MXFP benchmark now recognizes those foreign names instead of handing them to CK. The default gfx950 op test includes all matching foreign CSV rows, and optional fallback logging distinguishes configured kernels from executed fallbacks. FlyDSL AOT now replays the A4W4 blockscale table through the same public GEMM entry, retaining main's replay architecture. No kernel implementation or public GEMM signature changes.

Validation and unverified scope

This revision rebases the two feature/review commits onto main `e4973c4bed57a615068089fa02c88c64d644fd42`. The FlyDSL AOT conflict was resolved by registering the A4W4 blockscale table with main's public-entry replay driver. The nine existing AOT tables retain all 24,378 replay jobs. All 21 installed FlyDSL rows reach a FlyDSL launcher in the new CPU dry-run test, and all 21 rows plus 21 smaller-M probes passed fresh AOT compilation followed by run-only `--check`. The six AOT replay tests, 50 real configuration/CSV checks (no skips), 36 CPU routing/logging/CLI checks (one inapplicable skip), Ruff, Black and `git diff --check` passed. The ROCm container had GPUs hidden; this is compilation/routing evidence. Rebased-head CI passed on 2026-11-04, including all eight MI35X Standard Tests shards, OPUS, Tuned Op Bench and Aiter Test Gate; all four required checks passed (30 successful checks, 27 scope skips).

The CSV, GEMM op test, mixed benchmark, tuner, CK codegen and tuner README are byte-identical to the verified pre-rebase head `1bc0f11`; its cache/default/fallback and symmetric allocation review fixes are preserved. That pre-rebase head passed the 43 GPU tuned/baseline comparisons and four profiler/byte/graph cases, and its CI completed successfully on 2026-11-03. The performance qualification and 344 structured-input / 1,800-lookup checks remain the evidence from the implementation represented by `66c3cec`; the 22 Triton names explicitly retain the measured `.cg` setting as `_cmcg`. The 2.92× claim is the recorded paired standalone measurement, not a CI performance claim. The rebased head passed the MI35X GPU CI above. Dedicated post-rebase GPU bit-exact/performance requalification, other GPU architectures, current ATOM nightly, full-model latency, an exhaustive Triton search and an independent paired large-N timing sweep remain unverified. Dedicated Triton workflow shards previously skipped by scope are not GPU validation evidence.

PR-specific question

Foreign kernel selection requires a gfx950/CU/M/N/K CSV match at exact M, B preshuffle, row-major A, contiguous byte operands and the default shuffled per-1x32 scale storage, with M>=32, N%16=0 and K%256=0. Triton rows require BF16; FlyDSL additionally validates its encoded dtype and tile/split constraints. Calls outside the stated shape, input-layout and output-dtype contract, or with bias, global scales or nontrivial alpha/beta, retain the recorded CK/ASM fallback. The CK generator excludes foreign names and still validates/registers genuine CK fallbacks. Logging is opt-in and cached by shape/dtype/kernel; the direct-kernel benchmark fails an unsupported foreign launch explicitly. These boundaries prevent unqualified launches and misleading backend timings.

Changed op tests

- `op_tests/test_gemm_a4w4.py` compares the public tuned path and recorded CK/ASM baseline against its untimed FP32 reference. Both tuned and CK/ASM baseline candidates allocate an output inside each timed call. Its default gfx950 sweep now adds all 43 matching CSV-selected preshuffle shapes, while explicit `-mnk`/`--csv` inputs and gfx1250 table/off-grid behavior are preserved. The table labels the CSV configuration as `configured kernel` instead of implying profiler-confirmed execution.
- `op_tests/op_benchmarks/hip/bench_gemm_mixed_mxfp.py` is an existing consumer of `get_GEMM_config`. It now routes Triton/FlyDSL names through the shared preshuffle adapter while retaining its fixed output buffer and direct CK/ASM timing. This fixes the foreign-name CK registry failure and reports the selected backend correctly; an unavailable/unsupported foreign candidate fails explicitly.
- `tests/test_flydsl_aot_replay.py` checks all 21 production FlyDSL rows through the actual public-entry AOT replay with FakeTensors and verifies that each requests a FlyDSL kernel cache key. It catches incorrect table filtering or scale padding that would silently fall back.

PR state

  • PASS — pull request is marked ready for review

Copilot findings

  • PASS — no active Copilot finding lacks a substantive author reply
  • ADVISORY — Copilot did not review the current head SHA

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
  • PASS — Aiter Test Gate: passed

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

@yifehuan
yifehuan force-pushed the yifehuan/dispatch_smallm branch 2 times, most recently from 89b5388 to 66c3cec Compare November 2, 2026 11:13
@yifehuan yifehuan changed the title [GEMM][gfx950] Enable Triton and FlyDSL tuning in the A4W4 CSV [GEMM][gfx950] Tune narrow-N MXFP4 with CSV-selected preshuffle kernels Nov 2, 2026
@yifehuan
yifehuan marked this pull request as ready for review November 2, 2026 11:38
@yifehuan
yifehuan requested a review from a team November 2, 2026 11:38
@github-actions github-actions Bot changed the title [GEMM][gfx950] Tune narrow-N MXFP4 with CSV-selected preshuffle kernels [CK] [FlyDSL] [GEMM][gfx950] Tune narrow-N MXFP4 with CSV-selected preshuffle kernels Nov 2, 2026
@yzhou103

yzhou103 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

@zoe-cop review这个pr

Comment thread aiter/ops/gemm_op_a4w4.py Resolved
Comment thread aiter/ops/gemm_op_a4w4.py Resolved
@yifehuan
yifehuan force-pushed the yifehuan/dispatch_smallm branch from 66c3cec to 1ca08bb Compare November 2, 2026 15:00
@github-actions github-actions Bot changed the title [CK] [FlyDSL] [GEMM][gfx950] Tune narrow-N MXFP4 with CSV-selected preshuffle kernels [HIP] [CK] [FlyDSL] [GEMM][gfx950] Tune narrow-N MXFP4 with CSV-selected preshuffle kernels Nov 2, 2026
@github-actions github-actions Bot added the HIP label Nov 2, 2026
@yifehuan

yifehuan commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the two inline findings in 1ca08bb and fixed the default CI shape coverage in the existing op test.

On gfx950, the unchanged CI invocation python op_tests/test_gemm_a4w4.py now includes all 43 foreign CSV keys among 110 default shapes. Explicit -mnk/--csv overrides and the existing gfx1250 shape path are preserved. The actual default-selection probe and all 43 tuned/baseline GPU op-test comparisons passed locally.

Repository skill checks completed: 21 derived review rules, all seven review gates, and independent refutation with no unresolved finding. A temporary merge with current main 3febddf also passed 49 configuration/CSV tests, the 43-row GPU comparisons, and four profiler/byte/output-buffer/graph benchmark cases. These are local MI355X results; no complete native-validator or CI GPU pass is inferred from them.

The 2.916–2.922× figure remains the recorded paired standalone cold-GEMM measurement represented by 66c3cec, using two fresh passes and ten before/candidate/after samples per mode. Kernel implementations and CSV rows are unchanged. It is not a CI latency claim; skipped Triton shards do not establish kernel execution. CI is rerunning at the revised head, so further CI coverage/performance claims await its actual op-test jobs.

@yzhou103

yzhou103 commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@valar-cop review

@valar-cop valar-cop left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

a few small things..

ci green.

Comment thread op_tests/test_gemm_a4w4.py Resolved
Comment thread aiter/ops/gemm_op_a4w4.py Resolved
Comment thread aiter/ops/gemm_op_a4w4.py Resolved
zufayu
zufayu previously approved these changes Nov 4, 2026
@yifehuan
yifehuan merged commit aaa0597 into main Nov 4, 2026
@yifehuan
yifehuan deleted the yifehuan/dispatch_smallm branch November 4, 2026 06:48
shantipriya-amd pushed a commit to shantipriya-amd/aiter that referenced this pull request Nov 18, 2026
…ted preshuffle kernels (ROCm#7317)

* feat(gemm): tune narrow-N MXFP4 with CSV-selected preshuffle backends

* fix(gemm): address preshuffle tuning review feedback
chaojhou pushed a commit to AMD-AGI/Hyperloom that referenced this pull request Nov 27, 2026
…th, and report why the torch probe failed (#2912)

## Problem

The aiter prewarm on an image with torch `2.11.0+rocm10.0.0` (Python 3.12, gfx950) failed its build preflight with:

```
preflight_toolchain: host torch is not a ROCm build (torch=)
```

An empty `torch=` means `probe_torch_abi` got nothing usable: it parsed the probe's entire stdout as a single JSON document and discarded stderr, so a failing `import torch` and a stray stdout line both produced this message, and the message could not tell them apart.

## Root cause (confirmed)

The isolated build child runs with `PATH`, `HOME`, `TMPDIR` and `LC_ALL` only. In that image `torch/cuda/__init__.py` imports `amdsmi`, which loads `libamd_smi.so` from a ROCm SDK directory that only the image's `LD_LIBRARY_PATH` names (`.../site-packages/_rocm_sdk_devel/lib`). Without it `import torch` fails, the probe exits non-zero, and the preflight reported an empty torch version.

Measured inside the image, with the image's interpreter, as uid 65534:

- A: environment `PATH`/`HOME`/`TMPDIR`/`LC_ALL` only (the build child's): `import torch` fails in `amdsmi` with `KeyError: 'libamd_smi.so'` / `cannot open shared object file`.
- B: the same plus the image's `LD_LIBRARY_PATH`: `import torch` succeeds (`2.11.0+rocm10.0.0`, hip `7.15.26333`).

The compile step's environment is built the same way and would have failed the same import.

## Change

- The build child's environment carries the service's `LD_LIBRARY_PATH` where it is set, from the isolation's own pass list `CHILD_PASSED_ENV_NAMES = ("LD_LIBRARY_PATH",)` (in `measure/runner/native/recipes.py`, because `isolated.py` imports that module), not the local runner template's `IMAGE_ENV_NAMES`; nothing else of this process (no credentials, proxies, `LD_PRELOAD`, `PYTHONPATH` or key paths). Under bubblewrap its absolute directories are bound read-only.
- A native recipe's compile environment uses the same list.
- `docs/reference/environment-variables.md` and the module docstring of `isolated.py` name the library search path the child is given.
- Diagnostics: the probe prints its facts on one line prefixed with `HYPERLOOM_TORCH_ABI=`; only that line is parsed, other stdout is ignored.
- torch counts as a ROCm build only when `torch.version.hip` is set.
- A failed probe (non-zero exit, no facts, timeout, interpreter that cannot start) returns an `error` with the return code and the tail of stderr, and none of the facts it may have printed; the targeted-build preflight puts it in its failure summary, so a failure names its cause.

## Tests

- The child's environment holds the image's `LD_LIBRARY_PATH` and no other variable of this process; under bubblewrap its directory is bound read-only; the existing "only its own environment" test runs with `LD_LIBRARY_PATH` unset.
- A stub `torch` that imports only when a library directory is on `LD_LIBRARY_PATH`: the real probe fails naming `libamd_smi.so` in the old reduced environment and passes in the child's.
- A recipe's compile environment carries `LD_LIBRARY_PATH` only where it is set.
- The child is never given `LD_PRELOAD` (nor a credential, proxy or `PYTHONPATH`), and the pass list is exactly `LD_LIBRARY_PATH`.
- Probe parsing: fake outputs modelled on torch 2.11.0+rocm10.0.0 with stray stdout lines, a `+rocm` version without `hip` (not ROCm), a CUDA torch, an unmarked JSON line (a failure), a probe that printed facts and then exited non-zero (facts not read), a failing import with a long stderr, timeout and missing interpreter, plus a real run against a stub `torch` that prints on import.

`measure/runner/native/tests` (except two bubblewrap timeout tests that also fail on the base commit on the local host, which cannot start bubblewrap) and the touched `orchestrator/enablement/runtime` tests pass.


## Follow-up: a4w4 coverage check vs aiter's narrow-N overlay

With the torch probe fixed, the prewarm built `module_gemm_a4w4_blockscale` on the same image and then refused it:

```
PrewarmError: the built modules lack kernels of gfx950/256 rows of narrow_n_a4w4_blockscale_tuned_gemm.csv
```

and the serving preflight moved the module aside for the same reason.

Cause: aiter (ROCm/aiter#7317) added `configs/model_configs/narrow_n_a4w4_blockscale_tuned_gemm.csv`, which is merged into the default `AITER_CONFIG_GEMM_A4W4` table. Its 43 gfx950/256 rows select `triton_preshuffle_*` and `flydsl_mxpsh_*` kernels, with no `libtype` column, and some name a `fallbackKernelName`. aiter's CK codegen (`get_tune_dict` in `csrc/ck_gemm_a4w4_blockscale/gen_instances.py`) drops rows whose kernel starts with `_ZN`, `triton_` or `flydsl_`, and builds each CK `fallbackKernelName` instead. `csv_jit_kernel_rows` dropped only `_ZN` rows, so it asked the CK module for the Triton/FlyDSL kernel names, which no module holds.

Change: `csv_jit_kernel_rows` skips libtype-less rows with the same prefixes (`FOREIGN_KERNEL_PREFIXES`) and, for such a row, requires its CK `fallbackKernelName` (not `_ZN`/Triton/FlyDSL, not empty or `0`), keyed apart from the CK rows' dispatch entries as aiter's separate fallback registry is. This fixes both the prewarm's check and the serving preflight's.

Tests: rows copied from the real narrow-N CSV (header and rows as in aiter): the rows give only their CK fallbacks for gfx950/256 and nothing for another CU count; a module with those fallbacks covers the table and one without them does not; a fallback of `0` is not required; a CK row and a fallback of the same shape are both required (neither replaces the other); the prewarm installs an a4w4 module built from an image with the narrow-N overlay when it holds the CK fallback, and refuses it naming the overlay when it does not (this case fails before the change).


## Real-image evidence

Same image (gfx950, CU 256) and the same recipe both times; the recipe sets no `AITER_CONFIG_*`.

- Run 1 at `fd9b690207` (probe fixed): the build child imported torch and built `module_gemm_a4w4_blockscale`, then the coverage check refused it against the narrow-N overlay (above), and the serving preflight moved the image's own module aside. That was the second cause.
- Run 2 at `12fea4eaf3` (coverage check fixed): no prewarm was needed. The image's `module_gemm_a4w4_blockscale` passes the corrected check and is no longer moved aside; nothing was moved, nothing was built before the test, and nothing was built at the first prefill.

In run 2 the runner logged nothing about the preflight: `_build_image_own_once` only logged when the preflight moved modules aside, so a preflight that found the image's modules covering its tables (`skip`) and one that could not run (`noop`, e.g. no card target or no aiter JIT directory) both left no trace.

## Log what the preflight decided

`_build_image_own_once` now logs one INFO line per test with the preflight's summary for `skip` and `noop` (e.g. `aiter serving preflight before the test: the serving .so covers the CSVs this boot loads for gfx950; nothing moved`, or `...: nothing checked: <reason>`); a preflight that moves modules aside stays a WARNING. Test: one line per decision, at INFO for skip and noop and WARNING for invalidate.



## Review decisions (round 2)

- The isolation keeps its own pass list (`CHILD_PASSED_ENV_NAMES`, only `LD_LIBRARY_PATH`) for both the child and the compile; it no longer shares the local runner template's `IMAGE_ENV_NAMES`.
- The `+rocmN` version-label rule is dropped: ROCm is decided by `torch.version.hip` only.
- The three behaviours (library search path + probe diagnostics, a4w4 coverage, the preflight log line) stay in this one PR.

Trims: the unmarked-JSON branch of `_abi_line`, the `env` parameter of `probe_torch_abi` and the `environ` parameter of `_child_environment` are removed; their tests now set `os.environ` (monkeypatch) or wrap the probe's `run`.
Fyzyukk added a commit to Fyzyukk/aiter that referenced this pull request Nov 27, 2026
…line test

The previous commit removed _a4w4_fallback_config / _log_a4w4_fallback, the
triton_/flydsl_ padded-M fallback and the test's baseline candidate. Those are
upstream code from ROCm#7317 (the narrow-N CSV still carries the fallback columns),
not part of the OPUS change, so they are back exactly as on upstream/main.
OPUS rows have no fallback columns and still fall through to the default ASM path.

a4w4_blockscale_tuned_gemm.csv: two ASM rows (2048x16384x4096 and
32768x16384x53248) are back to upstream's rows; the diff against upstream is
now the 549 OPUS rows only.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants