Skip to content

[FlyDSL] [CI] [Build] Add an on-disk AOT cache for the FlyDSL GEMM launchers - #8287

Closed
coderfeli wants to merge 7 commits into
mainfrom
felix/flydsl-aot-cache
Closed

coderfeli wants to merge 7 commits into
mainfrom
felix/flydsl-aot-cache

Conversation

@coderfeli

@coderfeli coderfeli commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This PR adds an on-disk AOT cache for the FlyDSL GEMM launchers (aiter/ops/flydsl/aot_cache.py).

  • Miss: the kernel is compiled with flyc.compile(..., compile_only=True) and exported with export_to_c.
  • Hit: it is loaded with flyc.load_module, so a cold process skips MLIR tracing and the LLVM compile.

Converted launchers:

  • preshuffle GEMM (gfx942/gfx950)
  • a8w8 blockscale
  • mxfp8 8-wave
  • mxscale preshuffle (GEMM, fused GEMM, split-K reduce)
  • batched mxfp8 GEMM (gfx950)

Motivation

Today every new process traces and compiles each FlyDSL GEMM on its first call, which takes about 80–330 ms per kernel. With many tuned shapes this dominates warm-up. The dry_run prebuild replay (python -m aiter.aot.flydsl.gemm) also has to keep working, and must not under-build.

Changes

  • aiter/ops/flydsl/aot_cache.py (new): FlyDSLAotCache.launch(key, make_exe, *args).
    • Invalidation: each entry records the Python sources its trace touched (<digest>-<srchash>.o/.json). The fingerprint directory covers the FlyDSL/HIP/Python versions, the code-affecting environment and the arch. Editing one kernel file invalidates only the entries that depend on it.
    • Concurrency: builds take a per-digest fcntl.flock. An entry is published atomically, .json first and then .o. Concurrent processes and parallel replays never compile or export the same entry twice.
    • Modes: AITER_FLYDSL_AOT_CACHE=0|1|verify (default 1) and AITER_FLYDSL_AOT_CACHE_DIR.
    • Prebuild: under COMPILE_ONLY the cache exports the entry and also runs FlyDSL's compile-only launch. The replay's kernel identification and M-bisection hook that launch. The launch is skipped when the export has just traced the kernel.
    • Keys: in-memory keys include the device; the on-disk digest uses only the device type.
  • Launchers: preshuffle, blockscale, mxfp8 8-wave, mxscale preshuffle and batched mxfp8 now go through the cache. tensor_shim gains current_raw_stream / current_stream_arg.
  • docs/flydsl_aot_cache.md: design, invalidation, prebuild interplay and limits.
    • Known limit, pre-existing on main: ops routed through torch.ops.aiter_routed run their fake under the dry run, so they are not prebuilt. That fix is left to a separate PR.
  • op_tests/test_flydsl_aot_cache.py: an end-to-end JIT vs AOT check.

Performance (if applicable)

Hardware Workload/configuration Before After Change
MI308X (gfx942) preshuffle GEMM, first call in a cold process (8 shapes, fp8/int8) 174–464 ms (JIT) 3.3–26 ms (AOT hit) ~10–80x faster first call
MI308X (gfx942) preshuffle GEMM, steady-state kernel time 4.1–11.3 us 4.5–11.4 us within noise
MI308X (gfx942) preshuffle GEMM wrapper host time (m=1, 2000 calls) 37.7 us 36.4 us -3%

Testing

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

Documentation

  • Docstrings updated
  • User guide updated (docs/flydsl_aot_cache.md)
  • Performance guide updated
  • No documentation change is needed, with the reason stated below

Dependencies

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

FlyDSL APIs used, classified by FlyDSL's docs/api_stability.md:

  • Stable: flyc.compile(compile_only=True), CompiledFunction.export_to_c, flyc.load_module, flyc.JitArgumentRegistry, flydsl.compiler.protocol.cache_signature and flydsl.runtime.device.get_rocm_arch.
  • Not stable (internal):
    • flydsl.compiler.jit_argument.PointerJitArg, constructed directly to make a null-pointer placeholder for the compile-only export.
    • flydsl.utils.env (env.compile.compile_only), to detect COMPILE_ONLY.
    • The _is_stream_param marker on fx.Stream, to recognize stream arguments and build a null-stream placeholder.
    • The fingerprint also hashes the installed FlyDSL package's sources and native libraries, so a FlyDSL change invalidates entries rather than reusing them.

A FlyDSL release that moves or renames one of the internal symbols breaks this module at import or at the first launch, so the pin bump must re-run op_tests/test_flydsl_aot_cache.py.

  • flyc.load_module landed in FlyDSL CI: Move Triton tests from TW cluster to internal cluster #1451 and was first released in 0.5.1.dev1058. This PR bumps the FlyDSL pin from 0.5.0 to 0.5.1.dev1058 in requirements.txt, pyproject.toml, setup.py and .github/requirements/triton-test.txt.
  • With an older FlyDSL the cache is inert: every key falls back to the existing JIT path.
  • 0.5.1.dev1058 rejects an rmem tensor written inside a traced if ('ub.poison' op register operand/result remain after rmem SSA promotion, a regression from FlyDSL Fix gemm tuner error mi350 #1313). radix_topk_one_block.py now computes those values in the branches and writes the rmem tensors once outside them. The selection is unchanged. Verified with 0.5.0 and dev1058: test_topk_per_row, test_topk_per_row_stable, test_qsa (110 passed), and direct strided/ragged decode calls.

Breaking Changes

None.

  • The cache is on by default and writes under the aiter cache directory. Set AITER_FLYDSL_AOT_CACHE=0 to get the previous pure-JIT behavior.
  • Kernel binaries are unchanged, except the topk one-block kernel, whose source changed to work around the dev1058 regression above.

PR Self-Review

Reviewed revision

0897ec1

Behavior and intent

The first call of a converted FlyDSL GEMM now loads a cached object instead of tracing and compiling. Kernel code, launch arguments and binaries are unchanged. Prebuild keeps working and builds the same kernels as before.

Validation and unverified scope

  • FlyDSL used: 0.5.0.dev1039, with flyc.load_module. op_tests/test_flydsl_aot_cache.py was re-run on MI308X with the pinned 0.5.1.dev1058 wheel: all four modes pass, including the path assertions.
  • Runtime, MI308X (gfx942):
    • Command: python3 op_tests/test_flydsl_aot_cache.py.
    • Coverage: 4 shapes × {fp8, int8}, in 4 cold subprocesses for jit, aot miss, aot hit and aot verify.
    • Result: all outputs are bitwise equal to JIT.
  • Multi-GPU and CUDA graphs:
    • One entry launched on all 8 GPUs in one process gives identical results. load_module creates a HIP context only on the current device.
    • 4 concurrent cold processes sharing one cache build the entry once.
    • CUDA graph capture and replay match eager, including when the first call (and so the load) happens inside the capture, and on a second GPU.
  • Prebuild, gfx950 compile-only:
    • Command: GPU_ARCHS=gfx950 python -m aiter.aot.flydsl.gemm --csv a8w8_mxfp8_bpreshuffle_tuned_gemm.csv.
    • Result: 20 ok, 0 failed.
    • With the a4w4 blockscale CSV (3 rows) as well, AITER_FLYDSL_AOT_CACHE=0 and two runs of =1 give the same 62 gpu.binary blobs (from the FlyDSL cache .pkl files).
    • These are also identical to main built with the previous FlyDSL.
    • The second =1 run rebuilds nothing.
  • Prebuild robustness:
    • Two concurrent replays sharing one cache: no duplicate LLVM compile or export.
    • Re-running a replay rebuilds nothing.
    • Touching one kernel file rebuilds only the entries that depend on it.
  • Unverified:
    • Mode 0 (pure JIT) still launches only on the first GPU a process compiled for. This is a FlyDSL JIT limitation that exists on main too (docs §7, issue 4); the AOT path is not affected.
    • Runtime on gfx950 hardware. The gfx950 binaries are only proven identical to main; they were not executed.
    • gfx1250 mxfp8 is not converted and still goes through JIT.
    • Garbage collection of stale variants and .lock files is not implemented.
    • flock assumes a local filesystem for the cache directory.

PR-specific question

  • Compiled-handle cache keys: in-memory handles are keyed by constexprs, the dtypes that change the launcher signature, and the device. All tensors are passed as flat pointers (ptr_arg), so rank and stride do not change the ABI. The on-disk digest normalizes the device to its type, so one entry serves every GPU of the same arch.

Changed op tests

  • op_tests/test_flydsl_aot_cache.py (new):
    • Runs the preshuffle GEMM in fresh subprocesses in all four cache modes and asserts bitwise equality with JIT.
    • It also asserts the path each mode took, so it cannot pass on a silent JIT fallback:
      • mode 0 runs the JIT and writes nothing;
      • a miss exports one .o/.json pair per entry, with no fallback;
      • a hit neither traces, builds nor rewrites the cache;
      • verify neither builds nor falls back.
    • It is the only test that covers cross-process cache hit, miss and verify; the existing op tests run in one process and never load from disk.
    • It skips outside gfx942/gfx950, and with a FlyDSL that has no flyc.load_module (before 0.5.1.dev1058), where every mode would run the JIT.
    • Checked that the assertions fire: forcing every mode to the JIT, or running the hit on an empty cache, fails the test.

🤖 Generated with Claude Code

@coderfeli
coderfeli requested a review from a team November 19, 2026 08:40
@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 8287 --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.

@github-actions github-actions Bot changed the title [FlyDSL] Add an on-disk AOT cache for the FlyDSL GEMM launchers [FlyDSL] [JIT] Add an on-disk AOT cache for the FlyDSL GEMM launchers Nov 19, 2026
Add aiter/ops/flydsl/aot_cache.py. On a miss, each kernel is compiled
with flyc.compile(..., compile_only=True) and exported with
export_to_c. On a hit, it is loaded with flyc.load_module, so a cold
process skips MLIR tracing and the LLVM compile.

- Each entry records the Python sources its trace touched. The digest
  also covers the toolchain, the code-affecting environment and the
  arch. Editing one kernel therefore invalidates only the entries that
  depend on it.
- Concurrent builders are serialized with a per-digest flock, and an
  entry is published atomically (.json, then .o).
- AITER_FLYDSL_AOT_CACHE=0/1/verify selects the mode; verify recompiles
  and checks the result against the cache.
- Under the dry_run replay (aiter.aot.flydsl.gemm), prebuild still runs
  FlyDSL's compile-only launch, which the replay's kernel identification
  and M-bisection rely on. The fresh-export case is skipped to avoid a
  second trace.
- Convert the preshuffle (gfx942/gfx950), blockscale, mxfp8 8-wave,
  mxscale preshuffle and batched mxfp8 GEMM launchers. Handle keys
  include the device.
- Replay batches are now sized so that every worker is occupied.
- Ops routed through torch.ops.aiter_routed now run their Python body
  under dry_run instead of the fake, so they reach FlyDSL and prebuild.
- Add op_tests/test_flydsl_aot_cache.py and docs/flydsl_aot_cache.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderfeli
coderfeli force-pushed the felix/flydsl-aot-cache branch from bc14778 to 9a77b8c Compare November 19, 2026 09:11
coderfeli and others added 3 commits November 19, 2026 11:03
The test only compared outputs across modes, so it passed when every mode
ran the JIT: with a FlyDSL that has no flyc.load_module, or when the cache
fell back after a failed export or load.

- Each child reports the entries it holds, how many are JIT fallbacks, how
  many it exported and how many times it traced.
- A miss must export one .o/.json pair per entry, with no fallback.
- A hit must neither trace, build nor rewrite the cache; verify must not
  build or fall back.
- Skip when flyc.load_module is missing instead of passing on the JIT.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The doc said the cache used only public FlyDSL API; it also constructs
PointerJitArg, reads flydsl.utils.env and checks fx.Stream._is_stream_param.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
0.5.1.dev1058 is the first FlyDSL release with flyc.load_module (FlyDSL
#1451), so the AOT cache now loads exported objects instead of falling
back to the JIT. op_tests/test_flydsl_aot_cache.py passes on MI308X
(gfx942) with it, asserting the path of every mode.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot changed the title [FlyDSL] [JIT] Add an on-disk AOT cache for the FlyDSL GEMM launchers [FlyDSL] [CI] [JIT] Add an on-disk AOT cache for the FlyDSL GEMM launchers Nov 19, 2026
coderfeli and others added 2 commits November 19, 2026 14:18
# Conflicts:
#	aiter/ops/flydsl/batched_gemm_a8w8_gfx950.py
@github-actions github-actions Bot changed the title [FlyDSL] [CI] [JIT] Add an on-disk AOT cache for the FlyDSL GEMM launchers [FlyDSL] [CI] [Build] Add an on-disk AOT cache for the FlyDSL GEMM launchers Nov 19, 2026
@github-actions github-actions Bot removed the JIT label Nov 19, 2026
@aiter-bot

aiter-bot commented Nov 19, 2026 •

Copy link
Copy Markdown

NOT READY FOR HUMAN REVIEW

PR Self-Review

Revision 0897ec125559 · 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

The first call of a converted FlyDSL GEMM now loads a cached object instead of tracing and compiling. Kernel code, launch arguments and binaries are unchanged. Prebuild keeps working and builds the same kernels as before.

Validation and unverified scope

- **FlyDSL used:** 0.5.0.dev1039, with `flyc.load_module`. `op_tests/test_flydsl_aot_cache.py` was re-run on MI308X with the pinned 0.5.1.dev1058 wheel: all four modes pass, including the path assertions.
- **Runtime, MI308X (gfx942):**
  - Command: `python3 op_tests/test_flydsl_aot_cache.py`.
  - Coverage: 4 shapes × {fp8, int8}, in 4 cold subprocesses for jit, aot miss, aot hit and aot verify.
  - Result: all outputs are bitwise equal to JIT.
- **Multi-GPU and CUDA graphs:**
  - One entry launched on all 8 GPUs in one process gives identical results. `load_module` creates a HIP context only on the current device.
  - 4 concurrent cold processes sharing one cache build the entry once.
  - CUDA graph capture and replay match eager, including when the first call (and so the load) happens inside the capture, and on a second GPU.
- **Prebuild, gfx950 compile-only:**
  - Command: `GPU_ARCHS=gfx950 python -m aiter.aot.flydsl.gemm --csv a8w8_mxfp8_bpreshuffle_tuned_gemm.csv`.
  - Result: 20 ok, 0 failed.
  - With the a4w4 blockscale CSV (3 rows) as well, `AITER_FLYDSL_AOT_CACHE=0` and two runs of `=1` give the same 62 `gpu.binary` blobs (from the FlyDSL cache `.pkl` files).
  - These are also identical to `main` built with the previous FlyDSL.
  - The second `=1` run rebuilds nothing.
- **Prebuild robustness:**
  - Two concurrent replays sharing one cache: no duplicate LLVM compile or export.
  - Re-running a replay rebuilds nothing.
  - Touching one kernel file rebuilds only the entries that depend on it.
- **Unverified:**
  - Mode `0` (pure JIT) still launches only on the first GPU a process compiled for. This is a FlyDSL JIT limitation that exists on `main` too (docs §7, issue 4); the AOT path is not affected.
  - Runtime on gfx950 hardware. The gfx950 binaries are only proven identical to `main`; they were not executed.
  - gfx1250 mxfp8 is not converted and still goes through JIT.
  - Garbage collection of stale variants and `.lock` files is not implemented.
  - `flock` assumes a local filesystem for the cache directory.

PR-specific question

- **Compiled-handle cache keys:** in-memory handles are keyed by constexprs, the dtypes that change the launcher signature, and the device. All tensors are passed as flat pointers (`ptr_arg`), so rank and stride do not change the ABI. The on-disk digest normalizes the device to its type, so one entry serves every GPU of the same arch.

Changed op tests

- `op_tests/test_flydsl_aot_cache.py` (new):
  - Runs the preshuffle GEMM in fresh subprocesses in all four cache modes and asserts bitwise equality with JIT.
  - It also asserts the path each mode took, so it cannot pass on a silent JIT fallback:
    - mode `0` runs the JIT and writes nothing;
    - a miss exports one `.o`/`.json` pair per entry, with no fallback;
    - a hit neither traces, builds nor rewrites the cache;
    - verify neither builds nor falls back.
  - It is the only test that covers cross-process cache hit, miss and verify; the existing op tests run in one process and never load from disk.
  - It skips outside gfx942/gfx950, and with a FlyDSL that has no `flyc.load_module` (before 0.5.1.dev1058), where every mode would run the JIT.
  - Checked that the assertions fire: forcing every mode to the JIT, or running the hit on an empty cache, fails the test.

🤖 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 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
  • 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.

FlyDSL 0.5.1.dev1058 fails to compile this kernel with "'ub.poison' op
register operand/result remain after rmem SSA promotion". Since FlyDSL
#1313 removed fly-rewrite-func-signature, an rmem tensor written inside a
traced `if` is yielded out of scf.if as a memref, and rmem SSA promotion
can no longer resolve its stores.

Compute the per-element class, the index/value fragments and the bitonic
local index as SSA values in the branches and write the rmem tensors once
outside them. Behaviour is unchanged; verified with FlyDSL 0.5.0 and
dev1058 (test_topk_per_row, test_topk_per_row_stable, test_qsa, and
strided/ragged decode calls).

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

@zhiding512 zhiding512 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.

Thanks for the thorough write-up. The export_to_c + flyc.load_module design, the per-digest flock and the publish order (.json, then .o) look right to me, and the FlyDSL internals used here check out against both 0.5.0 and 0.5.1.dev1058 (PointerJitArg argument order, cache_signature, _is_stream_param, env.compile.compile_only).

gfx950 runtime (listed as unverified in the self-review): validated on MI355X with this branch and FlyDSL 0.5.1.dev1058. op_tests/test_flydsl_aot_cache.py passes there. A cross-process check with the same structure (jit / miss / hit / verify, one fresh process each) over nine tuned gfx950 kernels covering all six caches also passed: bitwise-identical outputs in all four modes, zero error against an fp32 reference, no unwritten output elements, 10 exports on the miss, no build or cache rewrite on hit and verify, and no JIT fallback. The first call on a hit took 3–19 ms, against 200–3250 ms through the JIT (8-wave: 283 ms, see the last minor item).

Requesting changes because, with the cache on by default, there are two ways it can silently load a stale kernel (inline on _sources_current and _build). Also inline: a conflict with torch.profiler in _record_sources, the export skipping tensor_shim's failed-compile cleanup, a new arch probe, and an unchecked checkAllclose in the test.

CI / process

  • The MI35X failures on da88a53 look like the FlyDSL bump breaking radix_topk_one_block. 0897ec1 looks right to me: the first, third and fourth hunks move the rmem stores out of the branches without changing values, and in scatter_step classify_prefix now also runs on invalid lanes, which is safe because all three callers load keys through safe indices. Triton MI35X is green on it.
  • The standard shards on 0897ec1 stopped in the wheel-cache restore steps before any test ran (a runner problem, not this PR), so they need a re-run. Merge main first: this run predates #8352, which removes the "Focused regression tests" step that also fails on main, so shard 0 would fail again without it.
  • Since the bump alone breaks unrelated kernels, consider landing "pin bump + topk fix" as its own PR first, with ci:atom_full as the CI guide asks for FlyDSL upgrades. That would also make this PR's CI attributable.
  • CI ran on MI35X only. Please add ci:mi300x, since gfx942 is the arch the self-review validated.

Minor (no need to reply to each)

  • The docstring and §4.1 say key may hold lists and dicts, but self._mem.get(key) (L395) raises unhashable type for them, outside the fallback. Either drop them from the docs or normalize the in-memory key too.
  • compile_bmm_a8w8_mxfp8_gfx950 (batched_gemm_a8w8_gfx950.py L364) launches with CPU placeholders, so its key holds device('cpu') (L337) and the disk digest gets ("device", "cpu") (aot_cache.py L264). A runtime process ("cuda") never looks that up. The device only matters to the in-memory JIT handles, so consider leaving it out of the disk digest.
  • Load-failure path (L465–471): under the lock, re-run _find and retry the load before unlinking. Otherwise ranks that hit a transient load error rebuild the entry one after another.
  • _is_tracked(f) (L234) gets the raw co_filename but compares it with resolved roots, so on a symlinked install the aiter/aot and aot_cache.py exclusions don't apply (over-invalidation only).
  • docs §5.1 (L309): the key snippet lacks XQ.device. The FlyDSL versions given for load_module (0.5.0.dev1039 vs "first released in 0.5.1.dev1058") disagree.
  • Follow-up, not for this PR: on a hit, the 8-wave first call is ~283 ms. About 215 ms of that is _validate() calling flydsl.runtime.device.get_rocm_arch(), which spawns rocm_agent_enumerator once per process. get_gfx_runtime() would bring it in line with the other kernels.



def _sources_current(sources: dict) -> bool:
return all(_file_digest(p) == d for p, d in sources.items())

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.

Stale hit across checkouts. The sidecar records absolute paths, and a lookup hashes the files at those paths, i.e. those of the checkout that built the entry, not the files this process imported. Neither fingerprint() nor _disk_key() includes the aiter root, so two worktrees, clones or containers that share the default ~/.aiter/flydsl_aot (same FlyDSL, torch and arch) resolve to the same entry. B then loads A's kernel for as long as A's files are unchanged.

Repro with this file verbatim and _export / _load_module stubbed to write and read the kernel's version string: two stub aiter roots A and B, B's kernel edited, one shared cache dir:

{"checkout": "A", "source_in_this_process": "A: original kernel", "kernel_that_ran": "A: original kernel", "builds": 1}
{"checkout": "B", "source_in_this_process": "B: edited kernel",   "kernel_that_ran": "A: original kernel", "builds": 0}

The sidecar B accepted lists .../A/aiter/ops/flydsl/kernel.py.

One worktree per branch is the common kernel-development setup. This also defeats shipping prebuilt .o files (§7), because the build host's paths don't exist on the target, so those entries never hit. Suggest recording files under the package relative to _tracked_root() and resolving them against the current process's root in _find, keeping absolute paths only for files outside the package.

tmp_obj = _export(exe, args, tmp, sym)
# Hashed now, not from the per-process cache: the build read the
# files as they are on disk at this point.
_file_digest.cache_clear()

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.

An edit during a run publishes the old kernel under the new hashes. The trace runs the modules this process imported earlier, but these hashes are taken from the files on disk after cache_clear(). Suppose a tracked file changes while the process runs: an editor save, or a git checkout / rebase during a long benchmark, a server, or a multi-minute AOT replay. The entry then claims to match the new sources while holding the old code, and every later process hits it.

Same stub setup with one checkout. The first process edits kernel.py on disk after importing it, then launches:

{"source_in_this_process": "C: original kernel",      "kernel_that_ran": "C: original kernel", "builds": 1}
{"source_in_this_process": "C: edited after import", "kernel_that_ran": "C: original kernel", "builds": 0}

Suggest: when any recorded source's st_mtime is later than this process's start (e.g. psutil.Process().create_time()), use the build in-process but don't publish it, and keep the per-process digest instead of clearing it. The comment at L500–501 describes the opposite of what happens for modules that were already imported.

try:
yield
finally:
sys.setprofile(old)

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.

Breaks C-level profilers. If the active profiler was installed with PyEval_SetProfile, as torch.profiler.profile(with_stack=True) does, sys.getprofile() returns its context object. sys.setprofile(old) then installs that non-callable object as a Python profile function: the next call raises TypeError: 'TraceContext' object is not callable, and CPython uninstalls the profiler. Checked with torch 2.10 (CPU activity only, same save/restore code):

sys.getprofile() under torch.profiler(with_stack=True): TraceContext
build raised TypeError: 'TraceContext' object is not callable
python stack tracer still installed: False

_kernel swallows the TypeError, so while profiling, every cold miss silently takes the JIT path and the rest of the trace loses its Python stacks. Suggest skipping recording when sys.getprofile() is not None (build and use the entry in-process, don't publish), or recording through sys.monitoring with a tool id of its own on 3.12+.

def _export(exe, args, out_dir: Path, sym: str) -> Path:
"""Compile ``exe`` for ``args`` without launching and export ``<sym>.o``."""
placeholders = [_placeholder(v) for v in args]
cf = flyc.compile(exe, *placeholders, compile_only=True)

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.

This calls flyc.compile directly, without the failed-compile cleanup that tensor_shim._compile_and_run does ("flyc.compile leaks ir.Context on failure"). Whenever an ir.Context is current, JitFunction._compile_or_execute inlines the call (return self.func(*args, **kwargs)). So if a failed export leaks a context, the _JitKernel fallback that _kernel runs right after takes that inline path instead of compiling. aiter/ops/flydsl/AGENTS.md also asks to reuse tensor_shim's cleanup rather than add a second copy. Suggest factoring the context pop out of _compile_and_run and using it here and in _verify.

from flydsl.runtime.device import get_rocm_arch

return get_rocm_arch()
props = torch.cuda.get_device_properties(torch.cuda.current_device())

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.

This adds a new local arch probe (gcnArchName). .github/instructions/aiter-ops-flydsl.instructions.md asks for the shared chip_info helpers instead. Keep the FLYDSL_GPU_ARCH override, but otherwise use get_gfx_runtime(): it returns the live GPU at runtime and the replay arch under AITER_AOT_REPLAY=1 (the dry run also patches _detect_native), so the dry run and the runtime would still compute the same fingerprint.

torch.cuda.synchronize()
first_ms = (time.perf_counter() - t0) * 1e3
_, us = run_perftest(run_flydsl, x, w_shuffled, xs, ws, out, tm, tn, tk, sk)
err = checkAllclose(

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.

checkAllclose returns the mismatch ratio and never raises, and err is only reported, so the test passes if JIT and AOT are equally wrong. The FlyDSL review rules flag an unchecked checkAllclose. Please assert it per mode (e.g. assert err == 0), as the bitwise check does.

Coverage: this is the only cross-process hit/miss/verify test, and it drives only the preshuffle GEMM. The five gfx950 caches go through the raw-pointer (ptr_arg) ABI of export_to_c / load_module, which nothing here exercises. A check with the same structure over nine tuned gfx950 kernels passed on MI355X: mxpsh sk1, sk2 and fused sk4; mxfp8 8-wave; bmm B=1 sk4 and B=8; blockscale ps0 bf16/fp16 and ps1 bf16 with ragged N=2112. Adding cases like these, gated on gfx950, would keep that path covered.

@coderfeli coderfeli closed this Nov 21, 2026
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.

4 participants