Repository navigation
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
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]>
bc14778 to
9a77b8c
Compare
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]>
… the AOT cache Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # aiter/ops/flydsl/batched_gemm_a8w8_gfx950.py
NOT READY FOR HUMAN REVIEWPR Self-ReviewRevision Author self-review accepted. Readiness report: Author answers
Show the author's self-review answersBehavior and intentValidation and unverified scopePR-specific questionChanged op testsPR state
Copilot findings
Code and op-test hygiene
Required CI
Shadow mode reports what would block but keeps the status successful. Set |
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
left a comment
There was a problem hiding this comment.
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 inscatter_stepclassify_prefixnow 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_fullas 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
keymay hold lists and dicts, butself._mem.get(key)(L395) raisesunhashable typefor 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 holdsdevice('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
_findand 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 rawco_filenamebut compares it with resolved roots, so on a symlinked install theaiter/aotandaot_cache.pyexclusions don't apply (over-invalidation only).- docs §5.1 (L309): the key snippet lacks
XQ.device. The FlyDSL versions given forload_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()callingflydsl.runtime.device.get_rocm_arch(), which spawnsrocm_agent_enumeratoronce 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()) |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
Summary
This PR adds an on-disk AOT cache for the FlyDSL GEMM launchers (
aiter/ops/flydsl/aot_cache.py).flyc.compile(..., compile_only=True)and exported withexport_to_c.flyc.load_module, so a cold process skips MLIR tracing and the LLVM compile.Converted launchers:
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).<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.fcntl.flock. An entry is published atomically,.jsonfirst and then.o. Concurrent processes and parallel replays never compile or export the same entry twice.AITER_FLYDSL_AOT_CACHE=0|1|verify(default1) andAITER_FLYDSL_AOT_CACHE_DIR.tensor_shimgainscurrent_raw_stream/current_stream_arg.docs/flydsl_aot_cache.md: design, invalidation, prebuild interplay and limits.torch.ops.aiter_routedrun 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)
Testing
Documentation
docs/flydsl_aot_cache.md)Dependencies
FlyDSL APIs used, classified by FlyDSL's
docs/api_stability.md:flyc.compile(compile_only=True),CompiledFunction.export_to_c,flyc.load_module,flyc.JitArgumentRegistry,flydsl.compiler.protocol.cache_signatureandflydsl.runtime.device.get_rocm_arch.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._is_stream_parammarker onfx.Stream, to recognize stream arguments and build a null-stream placeholder.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_modulelanded 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 inrequirements.txt,pyproject.toml,setup.pyand.github/requirements/triton-test.txt.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.pynow 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.
AITER_FLYDSL_AOT_CACHE=0to get the previous pure-JIT behavior.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
flyc.load_module.op_tests/test_flydsl_aot_cache.pywas re-run on MI308X with the pinned 0.5.1.dev1058 wheel: all four modes pass, including the path assertions.python3 op_tests/test_flydsl_aot_cache.py.load_modulecreates a HIP context only on the current device.GPU_ARCHS=gfx950 python -m aiter.aot.flydsl.gemm --csv a8w8_mxfp8_bpreshuffle_tuned_gemm.csv.AITER_FLYDSL_AOT_CACHE=0and two runs of=1give the same 62gpu.binaryblobs (from the FlyDSL cache.pklfiles).mainbuilt with the previous FlyDSL.=1run rebuilds nothing.0(pure JIT) still launches only on the first GPU a process compiled for. This is a FlyDSL JIT limitation that exists onmaintoo (docs §7, issue 4); the AOT path is not affected.main; they were not executed..lockfiles is not implemented.flockassumes a local filesystem for the cache directory.PR-specific question
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):0runs the JIT and writes nothing;.o/.jsonpair per entry, with no fallback;flyc.load_module(before 0.5.1.dev1058), where every mode would run the JIT.🤖 Generated with Claude Code