Skip to content

[2/5] autotune: two-track config + first real adopter (rmsnorm) (#770)#785

Open
jhinpan wants to merge 4 commits into
ROCm:mainfrom
jhinpan:feat/autotune-rmsnorm-adopt
Open

[2/5] autotune: two-track config + first real adopter (rmsnorm) (#770)#785
jhinpan wants to merge 4 commits into
ROCm:mainfrom
jhinpan:feat/autotune-rmsnorm-adopt

Conversation

@jhinpan

@jhinpan jhinpan commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

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.

Stacked on #783 (1/5). Targets main (cross-fork PRs can't base on a fork branch), so it currently shows PR1's commit too — review only eb94a0ac, or merge #783 first and this will shrink to its own diff.

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_size is fixed at @kernel decoration — rather than exposing them as jit Constexpr params. 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_callable rebuilds the module per config; built modules are cached per (key, config). Structural config kwargs route to build_fn (not the launch call); build-only kwargs like dtype_str are filtered out of the launch call by signature.

Two-track config

== Triton @heuristics + @autotune, quack get_default + exhaustive. New default= heuristic on @autotune: normal runs take the analytic default and skip the search entirely (zero-search); set FLYDSL_AUTOTUNE=1 to force the full sweep. Autotuners without a default always search.

First adopter: rmsnorm

  • build_rmsnorm_module gains a BLOCK_THREADS build knob (adds known_block_size when >256); the default arg keeps the old signature working, so the existing rmsnorm test path is unchanged.
  • kernels/rmsnorm_config.pyget_default (analytic BLOCK_THREADS) + get_all_configs (BLOCK_THREADS × waves_per_eu, fast-path only). VEC_WIDTH is intentionally not tuned (pinned to 128/elem_bits by the 128-bit buffer copy).
  • kernels/rmsnorm_autotune.pyrmsnorm_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_THREADS 256–512; the result is cached (second call doesn't re-tune):

[autotune] tuning 12 configs...
  [4/12] Config(BLOCK_THREADS=256) -> 0.081 ms
  [7/12] Config(BLOCK_THREADS=512) -> 0.081 ms
  ...
[autotune] best: Config(BLOCK_THREADS=256) (0.081 ms)

Tests

  • +6 GPU-free unit tests (builder rebuild/cache, default skip/force, kwarg filtering, env gate) → 22 total in 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

Copilot AI review requested due to automatic review settings July 1, 2026 07:05

Copilot AI 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.

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 heuristic default= path that skips search unless FLYDSL_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 fn when present, otherwise from build_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 thread python/flydsl/autotune.py Outdated
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 thread python/flydsl/autotune.py
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 thread python/flydsl/autotune.py
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 thread python/flydsl/autotune.py Outdated
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>
@jhinpan jhinpan force-pushed the feat/autotune-rmsnorm-adopt branch 5 times, most recently from e96dad5 to db07800 Compare July 2, 2026 06:54
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>
@jhinpan jhinpan force-pushed the feat/autotune-rmsnorm-adopt branch from db07800 to 95ea147 Compare July 2, 2026 07:08
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>
@jhinpan jhinpan force-pushed the feat/autotune-rmsnorm-adopt branch from 95ea147 to 1bc2ee7 Compare July 2, 2026 19:15
Comment thread kernels/rmsnorm_config.py
# 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

@zhiding512 zhiding512 Jul 4, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

waves_per_eu does any effect in FLYDSL?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants