Skip to content

hk.tune: a GEMM schedule search

Stability: experimental. These names may change in any release (stability).

hk.tune: search a GEMM shape's schedule space within a GPU-time budget, and keep a winner only when the measurement says it is one.

python -m hk.tune 2048x16384x4096                  # one shape (M x N x K)
python -m hk.tune 1x4608x9216 512x7168x8192 --budget 90
python -m hk.tune --model Qwen/Qwen2.5-32B --tp 2 --m 1,16,512,2048
python -m hk.tune --list                           # this machine's records

From Python:

import hk.tune
res = hk.tune.tune(2048, 16384, 4096, budget=60)
print(res.summary())           # champion, verdict, gain and band, GPU-s
res.accepted                   # what hk.ops.matmul now runs for this shape

How a shape is tuned (hk.tune.search): the shipped route's candidates and the generated space's best by an analytic model (hk.tune.cost) are compiled on the CPU in parallel, checked against fp32, then timed in rungs of successive halving and improved by local search, all interleaved in one process; the champion is then measured against the current route (and the baselines) in sets of rounds on fresh activations and accepted only past a margin drawn from the measured spread, confirmed on fresh sets (hk.tune.stats). A tie keeps the route.

What it writes (hk.tune.records): a win goes into this machine's records, $HK_TUNE_DIR/routes_gemm_<arch>.json, which hk.ops.matmul and hk.templates.gemm read in front of the shipped routes for that shape's M bucket. Nothing shipped changes. HK_AUTOTUNE=0 ignores the records.

The space is hk's own GEMMs' knobs (hk.tune.space): on gfx950 the pingpong GEMM, the four-warp block GEMM and the decode GEMV; on gfx1100 the WMMA GEMM and the decode GEMV.

The guide is docs/tune.md; the benchmark that judges it is bench/tune.

hk.tune.tune

hk.tune.tune(m: int, n: int, k: int, *, budget: float = 60.0, save: bool = True, baselines: Optional[Dict[str, Callable]] = None, workers: int = 32, log: Optional[Callable[[str], None]] = <built-in function print>, arch: Optional[str] = None, compiler=None, profile: bool = False, **search)

Tune one M x N x K bf16 GEMM (C = A @ B.T, B as (N, K)) on the current GPU; returns a Result (hk.tune.search). A win is written to this machine's records unless save=False. baselines ({name: fn(a, b, out)}) are timed in the decision's sets; default F.linear.

profile=True then runs hk.profile on what hk.ops.matmul now launches for the shape against hipBLASLt (F.linear) -- 30-70 s -- and keeps its verdict (res.profile): why the result is as fast as it is, and what the kernel would have to change to be faster.

hk.tune.tune_shapes

hk.tune.tune_shapes(shapes: Sequence[Tuple[int, int, int]], **kw) -> List

tune() each shape in turn, one compiler for all of them (kernels shared between shapes compile once).

hk.tune.model_shapes

hk.tune.model_shapes(model: str, tp: int = 1, ms: Sequence[int] = (1, 16, 128, 512, 2048, 8192), layers: str = '') -> List[Tuple[int, int, int]]

(M, N, K) of a model's linear layers (qkv, o, gate_up, down; and the LM head where asked) at tensor-parallel size tp, at each M of ms.

hk.tune.parse_shape

hk.tune.parse_shape(s: str) -> Tuple[int, int, int]

"MxNxK" -> (M, N, K).

hk.tune.torch_baselines

hk.tune.torch_baselines(names: Iterable[str] = ('torch',)) -> Dict[str, Callable]

Baselines to time beside the decision, by name: "torch" is F.linear (hipBLASLt on ROCm); the tuning benchmark's others (tunableop, aiter, aiter_triton, flydsl, hipkittens, triton -- bench/tune/baselines.py) when this runs from a checkout that has them. An unavailable one is skipped with a message.

hk.tune.explain

hk.tune.explain(m: int, n: int, k: int, *, vs: str = 'torch.nn.functional:linear') -> dict

hk.profile (docs/profile.md) on hk.ops.matmul at M x N x K -- the kernel this machine's records give the shape -- against vs: {"line": the verdict, "bound", "losses", "compare": the interleaved comparison's line}; {"error": ...} if the profiler cannot run here.

hk.tune.search

The search: from the current route, over the schedule space, to a winner that the acceptance rule believes -- or to "the route stands".

hk.tune.search.Search

class hk.tune.search.Search(space, *, budget: float = 60.0, min_gain: float = 0.01, k_noise: float = 2.0, pool_per_kind: int = 16, explore: int = 6, max_seeds: Optional[int] = None, rung_rounds: Sequence[int] = (3, 6, 10), local_moves: int = 12, local_iters: int = 6, restarts: int = 2, playoff: int = 5, decide_sets: int = 3, decide_rounds: int = 7, confirm_sets: int = 2, log: Optional[Callable[[str], None]] = None)

One shape's search; see the module docstring.

hk.tune.search.Result

class hk.tune.search.Result(m: int, n: int, k: int, arch: str, route: Candidate, champion: Optional[Candidate] = None, decision: Optional[stats.Decision] = None, route_ms: Optional[float] = None, ms: Optional[float] = None, baselines: Dict[str, Dict[str, Any]] = <factory>, counts: Dict[str, int] = <factory>, gpu_seconds: float = 0.0, wall_seconds: float = 0.0, compile_seconds: float = 0.0, load_seconds: float = 0.0, phases: Dict[str, float] = <factory>, profile: Dict[str, Any] = <factory>, log: List[str] = <factory>, timed: Dict[str, Optional[float]] = <factory>, refused: Dict[str, str] = <factory>, record: str = '') -> None

What one tuning run found and what it cost.

hk.tune.stats

What a timing means: the statistics and the acceptance rule of hk.tune.

hk.tune.stats.decide

hk.tune.stats.decide(route_sets: Sequence[Sequence[float]], cand_sets: Sequence[Sequence[float]], *, min_gain: float = 0.01, k_noise: float = 2.0, floor: Optional[float] = None) -> Decision

Whether the candidate beats the route, from S sets of rounds timed interleaved (route_sets[s] and cand_sets[s] in the same rounds).

hk.tune.stats.confirm

hk.tune.stats.confirm(first: Decision, again: Decision) -> Decision

A win only if the decision and its confirmation both say so; the numbers are pooled over both.

hk.tune.stats.Decision

class hk.tune.stats.Decision(verdict: str, gain: float, sigma: float, bar: float, band: List[float] = <factory>, ratios: List[float] = <factory>, sets: int = 0) -> None

A candidate against the route it would replace, over sets.

hk.tune.stats.halve

hk.tune.stats.halve(scores: Dict[Hashable, Sequence[float]], keep: int, protect: Iterable[Hashable] = (), floor: Optional[float] = None) -> List[Hashable]

Successive halving's cut: the keep fastest by median, plus every protected arm (the route), in rank order. An arm within its own noise of the last kept one is kept too: a cut is not a decision, and cutting a near-tie by one noisy median throws away the arm the next rung would have told apart.

hk.tune.stats.summary

hk.tune.stats.summary(times: Sequence[float], floor: Optional[float] = None)

(median ms, spread, rounds kept) of one arm's rounds; median None if no round counts.

hk.tune.records

The records hk.tune writes, and the lookup hk.ops.matmul and hk.templates.gemm make in front of their own routes.

hk.tune.records.user_route

hk.tune.records.user_route(arch: str, m: int, n: int, k: int) -> Optional[Tuple[str, Any]]

(name, schedule record) of this machine's tuned candidate for the shape, or None: no record for (N, K) in M's bucket, or HK_AUTOTUNE=0. The record is hk.schedules' (Schedule.to_record()); whether it takes the shape is the caller's check (hk.ops.gemm_cdna.user_route, hk.ops.gemm.user_route).

hk.tune.records.save

hk.tune.records.save(arch: str, m: int, n: int, k: int, name: str, spec, point: Dict[str, Any]) -> Path

Write one tuned shape: its candidate, its route and its measurement. Atomic; replaces an earlier route for the same (N, K) and M bucket.

hk.tune.records.load

hk.tune.records.load(arch: str) -> dict

This machine's records for arch (an empty table if none). Read once per process, again after a tuner in this process wrote (hk.autotune's generation counter) or after forget(): the lookup is on the launch path of every hk.ops.matmul, which has no syscall to spare -- a record written by another process is seen by the next process, as the schedule records are (hk.autotune.load_records).

hk.tune.records.path

hk.tune.records.path(arch: str) -> Path

This machine's record file for arch: $HK_TUNE_DIR/routes_gemm_.json.

hk.tune.records.bucket

hk.tune.records.bucket(m: int) -> int

M rounded up to a power of two: the Ms one record answers.

hk.tune.space

The schedule space hk.tune searches, behind a small provider interface, over hk.schedules (K1: one Schedule type per GEMM kernel family).

hk.tune.space.provider

hk.tune.space.provider(arch: str) -> ScheduleSpace

The space provider for an arch.

hk.tune.space.ScheduleSpace

class hk.tune.space.ScheduleSpace(arch: str)

hk's GEMMs on one arch, as hk.schedules spells them.

hk.tune.space.Candidate

class hk.tune.space.Candidate(kind: str, items: Tuple[Tuple[str, Any], ...], name: str = '', obj: Any = None) -> None

One point: a kernel family and its record (the knobs off the family's defaults); obj is the hk.schedules object, name the shipped candidate's name when it is one.

hk.tune.cost

An analytic estimate of a GEMM candidate's time: the order the search compiles and times candidates in, never a decision.

hk.tune.cost.estimate

hk.tune.cost.estimate(kind: str, s: Dict[str, Any], m: int, n: int, k: int, arch: str) -> float

Seconds, roughly, for candidate (kind, full schedule) at M x N x K.

hk.tune.measure

Timing GEMM candidates on the GPU, the way the project times them.

hk.tune.measure.GemmBench

class hk.tune.measure.GemmBench(m: int, n: int, k: int, arch: str, *, seed: int = 0, rotate_bytes: Optional[int] = None, device=None)

One M x N x K problem on the current GPU.

hk.tune.measure.Compiler

class hk.tune.measure.Compiler(workers: int = 32)

Builds candidates' kernels on the CPU, workers hipcc processes at a time, while the GPU times something else.

Tracing stays on the calling thread (hk's IR builder is a module-global stack, hk.runtime.warm); submit traces and emits C++ at once and hands hipcc to a thread pool; result waits for one candidate's builds.