Skip to content

Add autotuning: ct.autotune and ct.@tuned - #389

Draft
maleadt wants to merge 8 commits into
mainfrom
tb/autotune
Draft

maleadt wants to merge 8 commits into
mainfrom
tb/autotune

Conversation

@maleadt

@maleadt maleadt commented Dec 2, 2026

Copy link
Copy Markdown
Member

Tile sizes and compiler hints decide how fast a cuTile kernel runs, and the right values differ per architecture and element type. Today they are found by hand: #370, #372 and #374 each improved the examples by 1.2–2.2× that way, and the performance chapter says "cuTile.jl has no autotuner". On an RTX 5080, 81 configurations of the matmul example at 4096³ range from 1.7 to 56 TFLOPS.

This adds a search and a way to deploy its result.

# explore: time a launch over a space of configurations
result = ct.autotune((tm=(128, 64, 256), tn=(128, 64, 256), occupancy=(2, 1, 4))) do (; tm, tn, occupancy)
    @cuda backend=cuTile blocks=cld(M, tm) * cld(N, tn) occupancy=occupancy matmul_kernel(
        A, B, C, ct.Constant(tm), ct.Constant(tn), ct.Constant(32))
end

# deploy: launch with the stored configuration, or the first one of the space
function matmul!(C, A, B; search::Bool=false)
    ct.@tuned(search=search, tm=(128, 64, 256), tn=(128, 64, 256), hints=((;), (occupancy=1,))) do (; tm, tn, hints)
        @cuda backend=cuTile blocks=cld(M, tm) * cld(N, tn) hints... matmul_kernel(
            A, B, C, ct.Constant(tm), ct.Constant(tn), ct.Constant(32))
    end
end

A configuration is a NamedTuple and the closure decides what its fields mean, so one mechanism covers ct.Constant arguments, hints, grids that depend on them, and launches of several kernels.

  • ct.autotune compiles all candidates concurrently without launching them, then times the ones that compiled in turns, dropping slow ones early. Among configurations within 2% of the fastest it picks the earliest, so results are stable when the default is listed first. The 81-configuration matmul search takes 14 s to compile cold (4–6 s with CUBINs in the disk cache) and about 4 s to time.
  • ct.@tuned never searches unless search=true, following cuDNN.jl's autotune keyword; there is no cuTile-wide switch, a library exposes the keyword as it sees fit. A found configuration is saved as a small TOML file in the scratch space of the calling package (hence a macro), and shipped=dir reads records committed to a repository.
  • Records are found by content: a hash of what the first configuration's launch compiles to (Tile IR without debug information, plus the optimization level), the space, an optional key and the compute capability. There is nothing to version: a record stops matching when the kernel, the element type or the array layout changes. key is for what the code doesn't show, mainly problem size.
  • In steady state @tuned adds 0.05–0.1 µs to a 5.4 µs launch and allocates nothing.

The examples launch through @tuned with their hand-picked values first, and ship records for sm_120 in examples/tuning. Untuned they perform as before; with the records, layer norm's forward pass is 11% faster and the matmuls 2–3%, the rest keep their defaults. Given 128×128 tiles first, FMHA finds 64×64 on sm_120 in about a second (0.42 → 0.18 ms).

Known limitations:

  • Kernels shorter than the launch overhead (a few µs) can't be ranked by wall-clock timing; the search then returns roughly the first configuration. Timing with events would fix that.
  • Within a session, the choice is remembered per closure type, so run-time values passed as ct.Constant have to be repeated in key to get their own record.
  • Shipped records stop matching after a code-generation change to their kernels, with only a @debug message.

Draft because it requires CUDA.jl 6.6 for splatting keyword arguments into @cuda (JuliaGPU/CUDA.jl#3661); CI can't resolve that until it is released. Tested locally against that branch on an RTX 5080: the full suite on Julia 1.13 and the tuning tests on 1.11.

Supersedes #247; closes #40.

Tile sizes and compiler hints decide a kernel's performance, and the
best values differ per architecture and element type; until now they
were found with a hand-written loop over `@cuda` launches. Add
`ct.autotune(f, space)`, which calls `f(config)` for every NamedTuple
configuration of a search space and returns a `TuningResult` with the
chosen configuration and the timings of all of them.

The candidates are first compiled concurrently, by calling `f` with
launches turned into dry runs that compile and load their kernel but
return before running it. A dry run keeps candidates from writing the
same outputs at the same time. Compiling goes through the normal
caches, so a later launch of the winner with the same arguments needs
no compilation. The flag is a ScopedValue read on every launch, which
costs about 2 ns: launching a cached vector add took 5.5-5.8 us both
with and without it.

The surviving candidates are then timed in turns, dropping those far
behind the best, and the earliest configuration within 2% of the
fastest wins, so that noise does not decide between near-ties and the
first configuration acts as the default.
The chapter said that cuTile.jl has no autotuner and showed a
hand-written loop over tile sizes. Show `ct.autotune` on the matmul
example instead, with its output, and explain how the search treats
near-ties, failing configurations and kernels that update their
inputs, and that it cannot tell apart kernels much shorter than the
launch overhead.
Tuning records are to be found by what a call site launches rather than by
a name the user picks, so that a record stops applying when the kernel
changes. Give every compiled kernel a digest of its code: the hash of its
Tile IR bytecode, emitted a second time without debug information, and its
optimization level. Debug information holds absolute source paths and line
numbers, which would make the digest differ between installations and
after edits elsewhere in the file. The digest is kept with the CUBIN on
`TileCompilerResults`, so that kernels in package images carry it too.

A launch reports its kernel to the vector in a new scoped value,
`launch_observer`, before a dry run returns, so that `tuned` can see the
kernels of a call without running them, including kernels compiled ahead
with `launch=false`. `kernel_digest(kernel)` looks the digest up from the
compilation results; a digest field on `TileKernel` made every launch
allocate 48 bytes more.
`ct.autotune` finds the best configuration of a launch but leaves it to the
caller to use it. Add a call site that does: `ct.@tuned(space...) do cfg
... end` launches the configuration a tuning record names, or the first
one, which is the hand-picked default, when there is none. With
`search=true`, a call without a record searches the space with `autotune`,
saves the winner and launches it; other tasks reaching the same site wait
for that search.

Records are found by content: a dry run of the first configuration
collects the digests of the kernels it launches, which together with the
space, an optional `key` and the compute capability name the record. A
record therefore stops applying when the code of that launch changes,
including through its argument types or their layout, with nothing for
the user to declare. The choice is remembered for the session per closure
type, key, space, device and record locations, so that the steady-state
call adds a lock-free lookup and no allocation to the launch. Any method
definition makes a site look again, and so does, for a site that fell
back to its first configuration, any record saved since.

Each record is a TOML file, written through a temporary file and renamed,
named after the key and the device so that GPUs of the same compute
capability keep their own and a record from the same GPU is preferred.
`@tuned` keeps them in a Scratch.jl space of the package containing the
call (`ct.tuning_store(MyLib)`), so they go away with the package; `ct.tuned`
takes the store explicitly, `shipped=dir` adds read-only records a package
commits to its repository, and `ct.clear_tuning!` forgets them. A store
that cannot be written keeps its records in memory for the session.
Explain how a launch site uses `ct.@tuned`: the first configuration as
the default, the `search` keyword and how a library can expose it, which
record applies to a launch and what `key` is for, what the launch
function may do and how to protect kernels that update their inputs,
and where records are kept and how a package ships them.
The matmul, batched matmul, fused GEMM, FMHA, MoE and layer-norm examples
hand-picked their tile sizes and hints for an RTX 5080. They now launch
through `ct.@tuned`, with those values as the first configuration, so
that without a tuning record they behave as before, and a modest space
around them: tile sizes of 64 to 256, and the occupancy hint, or for MoE
also `num_worker_warps`. Hints are passed to `@cuda` as a splatted
`NamedTuple`, where an empty one keeps the kernel's `@compiler_options`.
Each `run` forwards `search`, which `benchmarks.jl --search` sets.

The GEMM examples gain a function that launches with explicit tile
sizes, which their tests use to keep covering other sizes. The tuned
calls key on the problem size and on the values they pass as constants
that can differ between calls, since a choice is remembered per call
site for the session; FMHA keys on the exact KV length, which decides
whether a candidate's tiles divide it. MoE tunes its two matmuls but not
`tile_m`, which shapes the routing data, and layer norm leaves its final
reduction alone, as a 10 µs kernel is too short to time reliably.
Tuned on an RTX 5080 with `tileiras` 13.5 at the benchmark sizes, and
passed to the examples' tuned launches as `shipped`, so that they use
them without searching. Against the hand-picked defaults, which stay in
effect elsewhere, the records make the layer-norm forward pass about 11%
faster (occupancy 2) and the matmul and batched matmul about 2-3%
faster. The MoE records pick narrower tiles for both matmuls without
changing the end-to-end time measurably; FMHA, fused GEMM and the
layer-norm backward pass keep their defaults.

Document how the examples use their records and how to tune them where
none applies.
The examples and the performance chapter pass compiler hints to `@cuda`
by splatting a configuration's `NamedTuple`, which `@cuda` accepts from
CUDA.jl 6.6 (JuliaGPU/CUDA.jl#3661). Raise the compat bounds of CUDACore
for the package, and of CUDA for the examples and the tests, which run
the examples.

This branch has not been deployed

No deployments
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.

Autotuning kernel launch parameters

1 participant