advanced27 min studyLesson 529 in Engineering

Autotuning pays for every candidate

Search legal schedules with measured costs while accounting for compilation expense, noise, and workload overfit.

On this page

What you’ll understand

  • Define a legal schedule search space before timing candidates.
  • Calculate tuning break-even under explicit per-call savings.
  • Separate learned or heuristic cost estimates from held-out measured performance.

Tile sizes, layouts, vector widths, pipeline stages, and launch shapes can create a large schedule space. Autotuning explores that space using measurements or a cost model, but its candidates must first preserve the same computation and fit the target. Tuning consumes compile time and execution resources, and a winner on one shape or quiet device can lose on the production workload. Optimize useful end-to-end work, including the cost of finding and deploying the schedule.

Legality and resource filters come first

Define configurable choices and reject combinations that violate dependency, memory, alignment, target, or numeric contracts. A schedule that silently enables broader fast-math permissions is not directly comparable with a strict reference unless the product explicitly accepts that changed contract. Check output correctness and memory safety before recording performance as a useful candidate. Compilation success alone does not show that tail handling, aliasing, or synchronization is correct on all valid inputs.

The Cartesian product of choices can grow quickly, but not every combination is independent or supported. A vector width may constrain tile shape, a pipeline depth may exceed shared-memory capacity, and a layout may preclude a library path. Prune with justified constraints rather than using the cost model to explain away illegal results. Preserve the exact target, compiler revision, flags, and generated configuration so the winner can be reproduced rather than remembered as one unexplained benchmark number.

Nraw=∏jnj,Slegal⊆SrawN_{\rm raw}=\prod_j n_j,\qquad\mathcal S_{\rm legal}\subseteq\mathcal S_{\rm raw}
nj counts choices for tuning dimension j. The product counts raw combinations before dependent constraints and legality filters. It is a search-size bound, not the number of correct or compilable implementations.↔ Scroll wide equations horizontally.

The cost model is a fallible ranking tool

A heuristic or learned model can rank candidates cheaply using features such as operation shape, resource use, and target properties. Its prediction is not a legality proof or a throughput guarantee. Training on one device, compiler, or workload distribution can make rankings poor after a target change. Keep held-out shapes and realistic contention conditions, and compare prediction errors with actual useful latency. A model can still help if it reliably places good candidates near the top, even without exact time predictions.

Measurements themselves are noisy. Warmup, compilation, cache state, synchronization, clocks, thermal behavior, and competing jobs can change results. Time the relevant completion boundary and repeat candidates under a consistent policy. The minimum of many noisy measurements is biased toward lucky outcomes; retest finalists independently. Include setup and conversion costs when production pays them. A kernel-only winner that requires an expensive per-call layout conversion may lose in the complete graph.

Nbreak=⌈Ttunetbaseline−tselected⌉(tselected<tbaseline)N_{\rm break}=\left\lceil\frac{T_{\rm tune}}{t_{\rm baseline}-t_{\rm selected}}\right\rceil\quad(t_{\rm selected}<t_{\rm baseline})
T_tune and per-call times use seconds, producing a count of invocations needed to amortize tuning under fixed savings. It excludes deployment, cache invalidation, and workload changes unless included in the measured costs.↔ Scroll wide equations horizontally.

Treat the tuning result as a versioned artifact

Key cached tuning results by the properties that affect validity and performance, including shapes, dtype, relevant layout, target, compiler revision, and numeric mode. A result for one alignment or dynamic range may not transfer to another. Bound tuning at startup or provide a safe baseline so a cold service does not stall on a large search. Revalidate after backend upgrades and preserve correctness checks for the selected configuration, particularly when previously pruned or unsupported schedules become available.

The optimization lab provides only a contrasting smooth problem. Reset and set both step size η=0.5 and initial position x₀=2, predict that the first gradient-descent update on f(x)=x²/2 gives x=1, then inspect as the iteration advances with Play or Step. It has no schedules, compiler, resource constraints, or measured kernels. Real tuning spaces are discrete and can be irregular, so this toy's convergence does not justify assuming a smooth convex landscape or following its updates as a compiler search algorithm.

When does tuning repay 9.6 seconds?

A legal search has 48 measured candidates. Each costs 0.12 seconds to compile and 0.08 seconds to validate and benchmark. The selected correct schedule reduces steady per-call latency from 2.0 ms to 1.6 ms. Assume stable savings and no other costs.

  1. Each candidate costs 0.20 seconds, so total tuning cost is 48×0.20=9.6 seconds. Invalid candidates excluded before measurement would change this budget.

  2. The saving is 0.4 ms per invocation, or 0.0004 seconds. Break-even is 9.6/0.0004=24,000 invocations under the fixed-workload model.

  3. At fewer calls, the selected kernel may be faster while the complete tuning-and-execution workflow is slower. Retest the winner on held-out realistic workloads and include any per-call conversion cost before claiming the saving persists.

The result

Autotuning has a lifecycle cost. A faster kernel is valuable only when its verified savings justify the search and remain relevant to deployment.

Explore the model

Interactive lab

Interactive lab · optimization

A smooth toy is not a schedule search space

Reset, set η=0.5, x₀=2;predict first update x=1 for f(x)=x²/2, then inspect the iteration with Play or Step. This exact quadratic model has no compilation, discrete schedules, resource filters, or benchmark noise.

A smooth toy is not a schedule search spaceGradient descent on f(x) = x²/2: xₙ = (1 − η)ⁿx₀. Playback advances two discrete iterations per second. Values outside |x| ≤ 4 are explicitly reported. Current readings: Position x0: 2; Objective x²/2: 2; Iteration behavior: Stable step. All parameters are adjustable with the labeled controls below.−4−202402.174.356.528.7Parameter xf(x) = x²/2n = 0
ObjectiveDiscrete iterate
Position x0
2
Objective x²/2
2
Iteration behavior
Stable step
n = 0 · t = 0 s

Gradient descent on f(x) = x²/2: xₙ = (1 − η)ⁿx₀. Playback advances two discrete iterations per second. Values outside |x| ≤ 4 are explicitly reported. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forA tuning cost model ranks legal candidates; it does not make the real space smooth or guarantee convergence to a production winner.

Check your understanding

A candidate benchmarks fastest but changes strict reduction order without permitted floating-point flags. How should it be treated?

Try it yourself

A search spends six seconds and selects a valid schedule saving 0.2 ms per call, including all per-call conversions. Compute break-even invocation count and explain one reason production might still fail to realize that saving.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Convert the latency difference to seconds before dividing.

Compare with the solution

Break-even is 6/0.0002=30,000 calls. Different shapes, target revision, contention, thermal state, cache behavior, or changing layout mix can reduce or reverse the saving. The result needs versioned configuration and representative validation rather than an assumption that the original quiet benchmark remains accurate indefinitely.

Take it with you

  • Search only schedules valid under the required numeric and resource contracts.
  • Cost models and noisy benchmarks need held-out measured verification.
  • Amortize tuning and preserve the selected schedule's versioned deployment assumptions.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.