Offline GEMM Tuning for AI Inference: A Practical Guide

    GEMM dominates the compute time of large language model inference, and a small kernel-level win can translate into a meaningful end-to-end gain. This guide explains why the same matrix shape maps to very different kernels depending on tiling, memory layout, thread configuration, and instruction scheduling, and why no single kernel is optimal for every shape. It contrasts offline tuning with online tuning, then walks through a six-stage batch workflow — shape extraction, normalization and deduplication, budget-bounded candidate search, validation and database generation, framework integration, and end-to-end verification — with sample Python and YAML configurations. It closes with seven common pitfalls (insufficient shape coverage, the wide decode M range, picking only the top-1 kernel, forgetting backward-pass GEMMs, mixing precisions, grouped GEMMs in MoE models, and noisy measurements) and a three-level framework for evaluating operator-level, model-level, and business-level gains.

    1. Problem Definition: Why GEMM Is Worth Tuning

    General Matrix-Matrix Multiplication (GEMM) is the most compute-intensive primitive in modern AI workloads. Training relies on it for both forward and backward passes, while inference leans on it for linear layers, attention projections, and expert networks. In large language model (LLM) inference, GEMM typically accounts for the majority of compute time, so even a modest kernel-level improvement is easily amplified into a visible end-to-end gain.

    Throughout this guide, “tuning” means finding the best-performing implementation for a specific production scenario — given its matrix shapes, data types, and hardware architecture — measured against throughput, latency, and goodput (effective throughput under a latency constraint).

    A frequently overlooked fact is that modern compute libraries do not ship a single matmul implementation. The same (M, N, K) shape can map to several different algorithms and kernels on a given device, and these can differ substantially in:

    • Tiling and tile sizes: how much data each thread block processes, and how well that data is reused across cache levels;
    • Memory layout: combinations of row-major, column-major, and transpose flags affect access continuity and coalescing efficiency;
    • Thread configuration: the number of thread blocks, warps, and threads determines the ratio of compute units to memory-access units;
    • Instruction and pipeline strategy: which compute instructions are chosen, multi-stage buffering and prefetch policies, and whether split-K is used to increase parallelism.

    Each design involves trade-offs. Some configurations achieve high arithmetic intensity but demand aggressive data reuse; others tolerate lower occupancy while hiding memory latency more effectively. The practical consequence is that no single kernel is optimal for all shapes — the winner flips with matrix shape, data type, and hardware architecture. That variability is precisely where tuning pays off.

    2. Offline vs. Online Tuning: Two Technical Routes

    In practice, GEMM tuning follows one of two routes:

    • Offline tuning: benchmark every operator that can appear in the target workload before deployment, pick the best implementation, and freeze the result;
    • Online tuning: measure candidates and select an implementation dynamically at runtime, based on the actual input characteristics.

    Online tuning requires no upfront preparation and adapts more gracefully to shapes that change at runtime. Its cost is a measurement penalty the first time a new shape appears, plus possible performance jitter during operation. Offline tuning has three clear advantages:

    1. A higher performance ceiling: the tuning process is not constrained by real-time requirements, so it can exhaust or broadly search a much larger candidate space and is more likely to find configurations close to the hardware peak;
    2. Zero runtime tuning overhead: production requests simply look up precomputed results, with no measurement logic inserted into the serving path;
    3. Stable and predictable performance: results are deterministic in a fixed environment and consistent across runs, which simplifies capacity planning and performance regression tracking.
    Dimension Offline tuning Online tuning
    Timing Before deployment, one-off During service operation
    Search space Can be large, close to exhaustive Constrained by real-time requirements; usually smaller or heuristic-driven
    Runtime overhead One table lookup Measurement required on first encounter of a new shape
    Determinism Strong, reproducible Weaker; affected by concurrency and runtime state
    Maintenance cost Retuning needed after hardware, driver, or library upgrades Self-adaptive; lower maintenance cost
    Applicable workloads Performance-sensitive production loads with relatively stable, predictable shapes Exploratory loads with highly dynamic shapes that cannot be enumerated in advance

    The two routes are not mutually exclusive. Mature systems often adopt an “offline-first, online-as-fallback” strategy: offline results serve the vast majority of requests with a deterministic, high-performance implementation, while uncovered shapes are handed to the runtime mechanism.

    Because offline tuning is already widespread in performance-sensitive settings, most mainstream GPU vendors’ general-purpose matmul libraries support offline pre-tuning and ship benchmarking command-line tools so developers can measure candidate implementations for a single operator. Many deep learning frameworks expose this capability transparently through a Tunable Operator mechanism: users enable a flag, and the framework looks up the appropriate implementation automatically at runtime, without needing to know which kernel is invoked. Several open-source inference and operator libraries provide similar auto-parameter-selection modules, further lowering the barrier to entry.

    3. From a Single Operator to the Whole Model: Why Scripting Matters

    Benchmarking one GEMM with a command-line tool is straightforward. A real model is a different story. Consider an LLM inference service:

    • The model contains many linear layers that are structurally similar but differ in size (attention projections, feed-forward networks, embedding projections, and so on);
    • The M dimension differs dramatically between the prefill and decode phases: in prefill it scales with the input sequence length, while in decode it is roughly equal to the number of concurrent requests. Different batching strategies shift the actual shapes further;
    • Quantized models may involve several different data type combinations;
    • Expert layers in Mixture-of-Experts (MoE) models often require grouped matmul.

    Hand-testing dozens, hundreds, or even more distinct GEMM shapes is hardly practical. If tuning can automate operator extraction, per-operator search, result collation, and configuration generation, most of the model’s GEMMs can be optimized at a very low incremental time cost. This is exactly the value of model-level offline tuning tooling.

    4. The End-to-End Workflow of Batch Offline Tuning

    A complete batch offline tuning pipeline breaks down into six stages: shape extraction → normalization and deduplication → candidate search → validation and database generation → framework integration → end-to-end validation. The last three can be grouped together as “model-level integration,” while the first four form the core.

    1. ┌──────────────────────────────────────────────────────────────────────────┐
    2. │ ① Shape extraction ② Normalize & ③ Candidate search ④ Validate & │
    3. │ (capture every op dedupe (parallel bench, store results) │
    4. │ on representative (key on m/n/k, bounded by budget) (correctness │
    5. │ inputs) dtype, layout) checks, DB) │
    6. └─────────────────────────────┬─────────────────────────────┬────────────────┘
    7. │ │
    8. ▼ ▼
    9. ⑤ Framework integration ⑥ End-to-end validation
    10. (load at startup, (regression against an
    11. look up at runtime) untuned baseline)

    4.1 Shape Extraction

    The goal is to enumerate every GEMM shape the model will actually use, with as few runs as possible. Two common approaches:

    • Operator-level tracing: enable the framework’s operator-level logging, run a handful of inference or training steps, and reconstruct all matmul calls from the logs;
    • Module-level interception: register hooks on key modules such as linear and attention layers, and record input, weight, and output shapes for each invocation.

    To ensure representativeness, the input samples should cover typical production traffic: different batch sizes and sequence lengths, both prefill and decode phases, and different precision and quantization modes. Too few samples will miss shapes and leave untuned “holes” in production; too many will inflate downstream tuning time.

    4.2 Normalization and Deduplication

    Raw logs contain many operators with identical shapes, or shapes differing only slightly. Normalization must come before deduplication. At minimum, include these dimensions:

    • Compute dimensions: the sizes of M, N, and K;
    • Data layout: row/column major order of each operand, and whether it is transposed;
    • Data type: input type and compute precision, such as BF16, FP16, or FP8;
    • Epilogue operations: whether a bias, fused activation, or scaling (for example quantization scaling) is applied;
    • Hardware information: GPU model and architecture identifier.

    Together these form the unique key for a tuning result. Hardware information is mandatory because the optimal implementation for one shape can differ entirely across GPU models.

    1. # Illustrative code: collection and normalization (pseudocode; hook mechanics vary by framework)
    2. from dataclasses import dataclass, asdict
    3. @dataclass(frozen=True)
    4. class GemmSpec:
    5. m: int
    6. n: int
    7. k: int
    8. dtype: str # input data type, e.g. "bf16"
    9. trans_a: bool # whether A is transposed
    10. trans_b: bool # whether B is transposed
    11. epilogue: str # epilogue type, e.g. "none" / "bias" / "bias_relu"
    12. arch: str # GPU architecture identifier
    13. def normalize(m, n, k, dtype, layout_a, layout_b, has_bias, activation, arch):
    14. """Normalize a single operator call into a deduplicable canonical description"""
    15. return GemmSpec(
    16. m=int(m), n=int(n), k=int(k),
    17. dtype=dtype,
    18. trans_a=(layout_a == "col"),
    19. trans_b=(layout_b == "col"),
    20. epilogue="bias_relu" if (has_bias and activation == "relu")
    21. else "bias" if has_bias else "none",
    22. arch=arch,
    23. )
    24. specs = set()
    25. for args in representative_workloads: # representative input set
    26. outputs = model.forward(args)
    27. loss = criterion(outputs, args.labels)
    28. loss.backward() # also covers GEMMs in the backward pass
    29. specs |= collected_gemm_specs # populated by hooks
    30. specs = sorted(specs, key=lambda s: (s.arch, s.dtype, s.m, s.n, s.k))
    31. print(f"Collected {len(specs)} deduplicated GEMM descriptions")
    32. for i, spec in enumerate(specs):
    33. print(i, asdict(spec))

    4.3 Searching Candidates Under a Budget

    For each normalized GEMM description, the tuning tool iterates over the library’s candidate implementations, measures execution time, and ranks them. The cost of a full search is roughly “number of operators × candidates per operator × time per measurement,” so two controls are typically introduced:

    • Time budget: cap the search duration per operator, then stop and return the best result found so far. A common pattern is to offer presets ranging from “fast” to “exhaustive” to match different tuning cycles;
    • Parallel execution: tuning is naturally parallel. On a multi-GPU host, distribute the operator list across devices and run them in independent worker processes, compressing total time to a fraction of the single-GPU serial run.
    1. # Illustrative code: running tuning tasks in parallel across processes (pseudocode)
    2. from concurrent.futures import ProcessPoolExecutor
    3. def tune_one(worker):
    4. results = {}
    5. for spec in worker.specs: # each worker is bound to one GPU
    6. try:
    7. best = library.search(
    8. spec.m, spec.n, spec.k,
    9. dtype=spec.dtype,
    10. trans_a=spec.trans_a, trans_b=spec.trans_b,
    11. epilogue=spec.epilogue,
    12. arch=spec.arch,
    13. time_budget_s=worker.budget, # per-operator time budget
    14. keep_top=worker.top_k, # number of top candidates to keep
    15. )
    16. results[spec_key(spec)] = best
    17. except Exception as exc: # one failure does not abort the run
    18. results[spec_key(spec)] = {"status": "failed", "error": str(exc)}
    19. return results
    20. workers = assign_specs_to_workers(specs, num_gpus=8)
    21. with ProcessPoolExecutor(max_workers=len(workers)) as pool:
    22. raw_results = {k: v for part in pool.map(tune_one, workers) for k, v in part.items()}
    23. failed = [k for k, v in raw_results.items() if v.get("status") == "failed"]
    24. print(f"Succeeded {len(raw_results) - len(failed)}, failed {len(failed)}")

    4.4 Validation and Model-Level Integration

    Once candidates have been found, three finishing steps remain:

    1. Generate the tuning database: organize the best implementation and its identifier (algorithm ID, kernel name, and so on) into a structured file keyed by “hardware + shape + data type + layout”;
    2. Integrate with the framework: enable tunable operators in the inference framework and point them at the tuning database. The framework loads it at startup, then looks up and selects the matching implementation by operator description at runtime;
    3. End-to-end validation: compare against the untuned baseline on time-to-first-token, throughput, and memory footprint, and verify output accuracy.

    For easier version management and canary rollout, keep the tuning database under configuration management and follow these conventions:

    • Hardware binding: the database is tied to a specific GPU model/architecture, driver, and compute library version, and must be regenerated after any change;
    • Fallback by default: operators that miss the database automatically fall back to the library’s default heuristic, preserving correctness;
    • Traceability: record metadata such as tuning time, input samples, and search budget to make issues reproducible and regression analysis possible.
    1. # Illustrative config: model-level offline GEMM tuning job
    2. target:
    3. model: llm_inference # model/service to tune
    4. arch: mi300x # target GPU architecture
    5. workloads: # representative inputs: cover both prefill and decode
    6. - name: prefill_bs8_len2048
    7. type: prefill
    8. batch_size: 8
    9. seq_len: 2048
    10. dtype: bf16
    11. - name: decode_bs32_len1
    12. type: decode
    13. batch_size: 32
    14. seq_len: 1
    15. dtype: bf16
    16. search:
    17. preset: balanced # fast / balanced / exhaustive
    18. time_budget_s: 5 # max search time per operator
    19. keep_top: 5 # candidates retained per shape
    20. execution:
    21. gpus: [0, 1, 2, 3, 4, 5, 6, 7]
    22. timeout_s: 600 # timeout for a single tuning task
    23. output:
    24. tune_db: ./tune_db/mi300x_llm_inference.db
    25. report: ./reports/mi300x_llm_inference.md

    5. Engineering Practices and Common Pitfalls

    1. Insufficient shape coverage. The effectiveness of offline tuning depends directly on covering the operators that actually appear in production. Changes to batching and scheduling policy, dynamic sequence lengths, or new model structures can all introduce shapes that were never tuned. Re-collect the operator inventory periodically, take the difference against the existing tuning database, and tune only the new shapes incrementally.

    2. Coverage of the large-M range. In the decode phase, M is approximately the number of concurrent requests and can span a wide range. Searching every M individually makes tuning cost grow linearly with the number of distinct values. In practice, tune only a handful of representative values and let the framework fall back to the default implementation for the rest. Whether adding more values is worthwhile can be decided by measuring the performance loss.

    3. Taking only the top-1 result can be fragile. The fastest implementation is not necessarily the most robust: if its lead over the runner-up falls within measurement noise, the advantage may not reproduce under real traffic, and top-ranked configurations may also consume more resources. In engineering terms, you can:

    • keep several top candidates and validate them further in a benchmark environment;
    • extend measurement duration and increase repetition counts to reduce noise.

    The right trade-off depends on the business requirements for latency and resources.

    4. Forgetting the backward pass. Training workloads include a large number of gradient matmuls in addition to the forward pass, and their transposed forms and dimension orders often differ from the forward ones. Collecting operators only along the inference path leaves that portion of the benefit on the table.

    5. Mixing precisions. FP16 and BF16 have different dynamic ranges, low-precision types such as FP8 are sensitive to scaling strategy, and mixed-precision training produces multiple types simultaneously. Tune each type independently under its own key, then compare output numerics afterwards to confirm that no unacceptable accuracy loss has been introduced.

    6. Special operators such as grouped matmul. Expert layers in MoE models typically use grouped matmul, where the effective row count per group varies with routing decisions, and the optimal configuration is highly sensitive to group size. Tune these operators separately according to their call parameters, and test them with samples drawn from the real routing distribution whenever possible.

    7. The measurement itself is subject to interference. Avoid sharing a GPU with other high-load tasks during tuning. Frequency fluctuations and temperature changes also introduce noise; when necessary, lock the GPU clock in the tuning environment and compare before-and-after results under identical conditions.

    6. Evaluating Tuning Results

    After tuning, assess the gains at three levels:

    • Operator level: relative speedup per shape, and the achieved fraction of peak compute (actual TFLOPS versus the hardware peak);
    • Model level: end-to-end latency, throughput, and memory footprint;
    • Business level: goodput under the latency constraint, and performance variance during long-running stability tests.

    Also record tuning time, database size, and operator coverage as input for future maintenance. Once the tuning flow is scripted, it can be folded into CI: automatically retune when the compute library or driver version changes, and diff the old and new results to catch performance regressions.

    7. Conclusion

    The essence of offline GEMM tuning is trading a one-off search cost before deployment for long-term, stable performance gains in production. For AI inference workloads where GEMM dominates compute time and shapes are relatively stable, the method often delivers a sizable end-to-end improvement for a very small engineering investment.

    From benchmarking a single operator to one-click batch tuning across an entire model, the core idea stays the same: extract the real operators accurately, search thoroughly within a budget, and integrate into production in a conservative way. With this methodology, developers can extract the full capability of their hardware at low cost, whether deploying on a self-managed GPU cluster or in the cloud.