[2/5] autotune: two-track config + first real adopter (rmsnorm) (#770)#785
Open
jhinpan wants to merge 4 commits into
Open
[2/5] autotune: two-track config + first real adopter (rmsnorm) (#770)#785jhinpan wants to merge 4 commits into
jhinpan wants to merge 4 commits into
Conversation
Contributor
There was a problem hiding this comment.
Pull request overview
This PR extends FlyDSL’s autotuning system to support a two-track “default heuristic vs forced search” flow and introduces a first real adopter (RMSNorm) that exercises builder-mode autotuning (rebuilding modules per structural config).
Changes:
- Add builder-mode support to
Autotuner(build_fn-based rebuild + in-process build cache) and introduce a heuristicdefault=path that skips search unlessFLYDSL_AUTOTUNE=1. - Extend autotune machinery with stride normalization + extra cache-key axes, and add unit tests covering builder/default behavior.
- Add RMSNorm autotune integration (
rmsnorm_config.py+rmsnorm_autotune.py) and a GPU integration test.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
python/flydsl/autotune.py |
Adds builder-mode execution, two-track default/forced-search behavior, and additional cache key axes; updates benchmark/run path accordingly. |
kernels/rmsnorm_kernel.py |
Adds a build-time BLOCK_THREADS knob and applies known_block_size when needed. |
kernels/rmsnorm_config.py |
Introduces heuristic default + exhaustive config generation for RMSNorm tuning. |
kernels/rmsnorm_autotune.py |
Provides the tuned RMSNorm front-end using builder-mode autotuning. |
tests/unit/test_autotune.py |
Adds GPU-free unit tests for builder mode, default skip/force behavior, kwarg filtering, and env gating. |
tests/kernels/test_rmsnorm_autotune.py |
Adds an end-to-end GPU test validating default correctness, forced search, persistence, and cache reuse. |
Comments suppressed due to low confidence (1)
python/flydsl/autotune.py:250
- In builder mode (fn=None), the disk-cache filename falls back to "unknown.json", so different tuners in the same cache dir can clobber each other’s tuned results. Consider deriving the cache filename from
fnwhen present, otherwise frombuild_fn(and include the module name) so each tuner has an isolated cache file.
# Disk cache
fn_name = getattr(fn, "__name__", None) or getattr(fn, "func", None)
if fn_name is not None and not isinstance(fn_name, str):
fn_name = getattr(fn_name, "__name__", "unknown")
fn_name = fn_name or "unknown"
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comment on lines
+279
to
+288
| # Dtypes + normalized strides of tensor args for type/layout specialization | ||
| dtype_parts = [] | ||
| stride_parts = [] | ||
| for name, val in sig_args.items(): | ||
| if hasattr(val, "dtype"): | ||
| dtype_parts.append(f"{name}:{val.dtype}") | ||
| if hasattr(val, "shape") and hasattr(val, "stride"): | ||
| stride_parts.append(f"{name}:{_normalize_strides(val)}") | ||
| key_vals.append(tuple(dtype_parts)) | ||
| key_vals.append(tuple(stride_parts)) |
Comment on lines
372
to
376
| def kernel_call(): | ||
| if config.pre_hook: | ||
| config.pre_hook(merged_kwargs) | ||
| self._restore_tensors(snapshot) | ||
| self._reset_tensors(args, merged_kwargs) |
Comment on lines
360
to
+367
| compiler_opts = config.compiler_opts() | ||
| fn = self._resolve_fn(config, key, args, kwargs) | ||
| merged_kwargs = dict(self._filter_call_kwargs(fn, kwargs)) | ||
| # In builder mode the config's structural kwargs (e.g. BLOCK_THREADS) | ||
| # are consumed by build_fn, not passed to the launch call. | ||
| if self.build_fn is None: | ||
| merged_kwargs.update(config.all_kwargs()) | ||
|
|
Comment on lines
+426
to
+431
| """Run a single (already-chosen) config: resolve fn, apply kwargs+hints.""" | ||
| fn = self._resolve_fn(config, key, args, kwargs) | ||
| merged = dict(self._filter_call_kwargs(fn, kwargs)) | ||
| if self.build_fn is None: | ||
| merged.update(config.all_kwargs()) | ||
| return self._run_with_hints(fn, config.compiler_opts(), args, merged) |
FlyDSL's autotuner exists but nothing uses it, and two gaps block real
adoption. This is the first of a series making it a correct, adopted path.
Cache key (_make_key) previously specialized on shape/dtype only. A config
tuned under one compiler build, GPU arch, or memory layout would be silently
reused under another. Fold in the axes Triton/quack rely on:
- normalized stride pattern ({0,1,other}: broadcast vs contiguous vs strided)
- device arch (get_rocm_arch)
- toolchain fingerprint (reuses jit_function._flydsl_key)
- cache-invalidating env vars (reuses _cache_invalidating_env_values)
The dtype/stride axes are sorted by arg name so a call is keyed identically
regardless of kwarg order (no duplicate tuning / cache files).
restore_value (new) is the correctness soul of autotune: benchmarking runs
the same kernel dozens of times, so an in-place / accumulating kernel (e.g.
fused-add rmsnorm) corrupts its own inputs and picks a config on garbage.
Snapshot the named tensors once and restore before every rep.
reset_to_zero is now also re-applied on the real (non-benchmark) call — both
the post-tune run and cache hits — via a shared _run_config, so an
accumulate-into-zero kernel returns the single-clean-run result instead of
carrying benchmark-rep state. (Was applied only inside the bench loop.)
Also defer the CompilationContext import so the autotuner core stays
importable and unit-testable without the compiled flydsl._mlir bindings.
Adds tests/unit/test_autotune.py: 19 GPU-free tests covering Config
serialization, every cache-key axis (incl. env-fingerprint change and
kwarg-order insensitivity), restore_value/reset_to_zero semantics (incl. the
final-run and cache-hit reset), pruning, and disk-cache round-trip.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
eb94a0a to
0aa86e0
Compare
e96dad5 to
db07800
Compare
Comment-only cleanup of the PR1 additions: keep the one key fact per helper, drop the Triton/quack background, redundant restatements, and by-example prose. No logic change; 19 unit tests still pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
db07800 to
95ea147
Compare
Second in the series. Gives the autotuner an "avoid-search" path and puts it to work on a real kernel, so it stops being dead code. Builder mode. Every current FlyDSL kernel bakes its structural knobs at module-build time rather than exposing them as jit Constexpr params. The existing @autotune, which injects config kwargs into one jit call, can't tune those. Add builder mode: build_fn(config, *args) -> launch_callable rebuilds the module per config. autotune_builder(): one-call adoption. Instead of a hand-rolled wrapper per kernel, a kernel opts in with just its kernel-specific pieces: rmsnorm_autotuned = autotune_builder( name="rmsnorm", build=build_rmsnorm_module, specialize=lambda inp, g, out, m, dtype_str="bf16", **kw: { "N": inp.shape[-1], "dtype_str": dtype_str}, configs=get_all_configs, default=get_default, structural=("BLOCK_THREADS",)) The helper owns cache naming, callable config generation, the structural-vs- compiler knob split, build caching, and launch-kwarg filtering. rmsnorm's adopter dropped from ~79 lines of boilerplate to a single declaration. Correctness (surfaced by two independent fresh reviews): - Build cache keys only on the STRUCTURAL knobs + spec, not repr(config), so configs differing only in a compiler hint (waves_per_eu) reuse one built module. Verified on MI350X: a 12-config sweep now builds 4 modules, not 12. - A build-only scalar (dtype_str) passed positionally is rejected with a clear error instead of silently binding to the wrong launch slot (e.g. stream). - autotune_builder requires a non-empty name (empty/None would fall back to unknown.json and defeat the per-kernel cache identity). - Build-only scalars enter the cache key via the specialize() axes. - Compiler hints (waves_per_eu / maxnreg) are folded into the JitFunction's compile_hints (restored after) so each distinct hint compiles a distinct binary instead of reusing a cached one. - FLYDSL_AUTOTUNE=1 bypasses cache + default to force a fresh search. - Disk cache is re-loaded when FLYDSL_AUTOTUNE_CACHE_DIR changes (a module- level tuner isn't pinned to the import-time dir for loads or saves). - Config.pre_hook is documented as non-persistable (not serialized). Two-track config == Triton @Heuristics + @autotune: default= gives zero-search normal runs; FLYDSL_AUTOTUNE=1 forces the sweep. First adopter rmsnorm: build_rmsnorm_module gains a BLOCK_THREADS build knob (+known_block_size when >256; default arg keeps the old signature). config space in rmsnorm_config.py; small-N (imported SMALL_N_THRESHOLD) emits a single config since that kernel ignores BLOCK_THREADS. VEC_WIDTH stays pinned (128b copy). Verified on MI350X (gfx950), M=4096 N=8192 bf16: default and forced-search match the torch reference (max err 1.5e-2); sweep picks BLOCK_THREADS 256-512 and a subsequent normal call reuses the cache (zero benchmark invocations asserted). Tests: GPU-free unit tests for builder mode + autotune_builder (rebuild/cache, build-cache-ignores-hints, default skip/force, scalar-in-key, name required, positional-scalar rejected) = 31; tests/kernels/test_rmsnorm_autotune.py (l2_device) covers default, forced-search, and no-re-tune cache reuse. ruff + black clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
95ea147 to
1bc2ee7
Compare
zhiding512
reviewed
Jul 4, 2026
| # span both the <=256 (no known_block_size) and >256 (needs known_block_size) | ||
| # regimes so the tuner can trade occupancy against per-thread work. | ||
| _BLOCK_THREADS_CHOICES = (128, 256, 512, 1024) | ||
| _WAVES_PER_EU_CHOICES = (0, 1, 2) # 0 == leave to the compiler |
Collaborator
There was a problem hiding this comment.
waves_per_eu does any effect in FLYDSL?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Second in the #770 series: give the autotuner an avoid-search path and put it to work on a real kernel, so it stops being dead code.
Builder mode
Every current FlyDSL kernel bakes its structural knobs at module-build time — they size shared storage, the vectorized tile stride, and the launch block, and
known_block_sizeis fixed at@kerneldecoration — rather than exposing them as jitConstexprparams. The existing@autotune, which injects config kwargs into a single jit call, can't tune those.So this adds builder mode:
build_fn(config, *args, **kwargs) -> launch_callablerebuilds the module per config; built modules are cached per(key, config). Structural config kwargs route tobuild_fn(not the launch call); build-only kwargs likedtype_strare filtered out of the launch call by signature.Two-track config
== Triton
@heuristics+@autotune, quackget_default+ exhaustive. Newdefault=heuristic on@autotune: normal runs take the analytic default and skip the search entirely (zero-search); setFLYDSL_AUTOTUNE=1to force the full sweep. Autotuners without a default always search.First adopter: rmsnorm
build_rmsnorm_modulegains aBLOCK_THREADSbuild knob (addsknown_block_sizewhen >256); the default arg keeps the old signature working, so the existing rmsnorm test path is unchanged.kernels/rmsnorm_config.py—get_default(analyticBLOCK_THREADS) +get_all_configs(BLOCK_THREADS×waves_per_eu, fast-path only).VEC_WIDTHis intentionally not tuned (pinned to128/elem_bitsby the 128-bit buffer copy).kernels/rmsnorm_autotune.py—rmsnorm_autotuned, the tuned front end.Verification (MI350X / gfx950, M=4096 N=8192 bf16)
Default and forced-search runs both match the torch reference (max err 1.5e-2). The 12-config sweep runs cleanly and picks
BLOCK_THREADS256–512; the result is cached (second call doesn't re-tune):Tests
tests/unit/test_autotune.py.tests/kernels/test_rmsnorm_autotune.py(l2_device): default run, forced-search + tuned-config persisted, cache reuse.ruff + black clean.
Refs #770.
🤖 Generated with Claude Code