|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | +# Copyright (C) 2024-2026, Advanced Micro Devices, Inc. All rights reserved. |
| 5 | + |
| 6 | +"""AOT pre-compilation for the FlyDSL decode Top-K-per-row kernel. |
| 7 | +
|
| 8 | +The launcher is JIT-specialized on two axes, both baked into the kernel: batch size |
| 9 | +(via short_max) and context length (via blocks_per_row, derived from the |
| 10 | +logits width). Both are bucketed to powers of two in the runtime config, so the |
| 11 | +distinct-kernel count collapses to ~36 per arch across the whole (num_rows, context) |
| 12 | +range. This module enumerates those and compiles them into the FlyDSL cache so a |
| 13 | +serving worker never pays the first-call JIT compile at runtime for these shapes. |
| 14 | +
|
| 15 | +Usage: |
| 16 | + # Compile all distinct Top-K kernels from the default CSV |
| 17 | + python -m aiter.aot.flydsl.topk |
| 18 | +
|
| 19 | + # Custom CSV file(s) |
| 20 | + python -m aiter.aot.flydsl.topk --csv /path/to/config.csv |
| 21 | +
|
| 22 | +Environment variables: |
| 23 | + FLYDSL_RUNTIME_CACHE_DIR Cache directory (default: ~/.flydsl/cache). |
| 24 | + ARCH / GPU_ARCHS Target GPU architecture(s) (e.g. gfx942, gfx950). |
| 25 | +""" |
| 26 | + |
| 27 | +from __future__ import annotations |
| 28 | + |
| 29 | +import argparse |
| 30 | +import csv |
| 31 | +import os |
| 32 | +import sys |
| 33 | +import time |
| 34 | +from typing import Any |
| 35 | + |
| 36 | +import flydsl.expr as fx |
| 37 | + |
| 38 | +from aiter.aot.flydsl.common import ( |
| 39 | + collect_aot_jobs, |
| 40 | + compile_only_env, |
| 41 | + cu_num_to_arch, |
| 42 | + override_env, |
| 43 | +) |
| 44 | + |
| 45 | +_CONFIG_DIR = os.path.join( |
| 46 | + os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), |
| 47 | + "configs", |
| 48 | +) |
| 49 | +DEFAULT_CSVS = [os.path.join(_CONFIG_DIR, "topk_decode_aot.csv")] |
| 50 | +TOPK_AOT_ARCH_DEFAULT = "gfx942" |
| 51 | + |
| 52 | + |
| 53 | +def parse_csv(csv_path: str) -> list[dict[str, Any]]: |
| 54 | + """One job per *distinct* compiled Top-K kernel for each CSV row. |
| 55 | +
|
| 56 | + Each row is (k, max_model_len, max_num_seqs, cu_num). The kernel is specialized |
| 57 | + on two drift axes: num_rows (via short_max + caps) and blocks_per_row (via the |
| 58 | + context length). We sweep both -- num_rows 1..max_num_seqs and every distinct |
| 59 | + blocks_per_row 2..min(32, ceil(max_model_len/items_per_block)) -- and dedupe by |
| 60 | + the runtime _kernel_config (evaluated for the row's target arch), so exactly |
| 61 | + one job per distinct compiled kernel is emitted. A representative context length |
| 62 | + per blocks_per_row suffices because the kernel is context-length-agnostic within |
| 63 | + a blocks_per_row (contexts sharing a bpr reuse one kernel).""" |
| 64 | + from aiter.ops.flydsl.topk_per_row_decode import ( |
| 65 | + _TIERED_BLOCK_THREADS, |
| 66 | + _TIERED_LOAD_VEC, |
| 67 | + _kernel_config, |
| 68 | + ) |
| 69 | + |
| 70 | + items_per_block = _TIERED_LOAD_VEC * _TIERED_BLOCK_THREADS |
| 71 | + |
| 72 | + jobs: list[dict[str, Any]] = [] |
| 73 | + seen: set = set() |
| 74 | + with open(csv_path, newline="") as f: |
| 75 | + for row in csv.DictReader(f): |
| 76 | + k = int(row["k"]) |
| 77 | + mml = int(row["max_model_len"]) |
| 78 | + max_seqs = int(row.get("max_num_seqs") or 128) |
| 79 | + cu = int(row.get("cu_num") or 0) |
| 80 | + arch = cu_num_to_arch(cu, default=TOPK_AOT_ARCH_DEFAULT) |
| 81 | + # blocks_per_row = min(32, max(2, ceil(L / items_per_block))); sweep every |
| 82 | + # distinct value up to the row's max context via a representative L. |
| 83 | + max_bpr = min(32, max(2, -(-mml // items_per_block))) |
| 84 | + # Derive configs for the target arch so the dedup + the compile below |
| 85 | + # agree, and match a runtime on that arch. |
| 86 | + with override_env("FLYDSL_GPU_ARCH", arch): |
| 87 | + for bpr in range(2, max_bpr + 1): |
| 88 | + rep_l = min(bpr * items_per_block, mml) |
| 89 | + for num_rows in range(1, max_seqs + 1): |
| 90 | + cfg = _kernel_config(num_rows, rep_l) |
| 91 | + ident = (k, arch, tuple(sorted(cfg.items()))) |
| 92 | + if ident in seen: |
| 93 | + continue |
| 94 | + seen.add(ident) |
| 95 | + jobs.append( |
| 96 | + { |
| 97 | + "kernel_name": ( |
| 98 | + f"topk_per_row_decode_k{k}_nr{num_rows}" |
| 99 | + f"_bpr{cfg['blocks_per_row']}_{arch}" |
| 100 | + ), |
| 101 | + "k": k, |
| 102 | + "num_rows": num_rows, |
| 103 | + "max_model_len": rep_l, |
| 104 | + "cu_num": cu, |
| 105 | + } |
| 106 | + ) |
| 107 | + return jobs |
| 108 | + |
| 109 | + |
| 110 | +def compile_one_config( |
| 111 | + kernel_name: str, |
| 112 | + k: int, |
| 113 | + num_rows: int, |
| 114 | + max_model_len: int, |
| 115 | + cu_num: int = 0, |
| 116 | + **kwargs, |
| 117 | +) -> dict: |
| 118 | + """Compile one Top-K kernel configuration into the FlyDSL cache.""" |
| 119 | + del kwargs |
| 120 | + |
| 121 | + import torch |
| 122 | + from torch._subclasses.fake_tensor import FakeTensorMode |
| 123 | + |
| 124 | + from aiter.ops.flydsl.topk_per_row_decode import ( |
| 125 | + _build_launcher, |
| 126 | + _required_seq_rows, |
| 127 | + ) |
| 128 | + |
| 129 | + aot_arch = cu_num_to_arch(cu_num, default=TOPK_AOT_ARCH_DEFAULT) |
| 130 | + result = { |
| 131 | + "kernel_name": kernel_name, |
| 132 | + "shape": kernel_name, |
| 133 | + "compile_time": None, |
| 134 | + "compile_arch": aot_arch, |
| 135 | + } |
| 136 | + |
| 137 | + t0 = time.time() |
| 138 | + try: |
| 139 | + with ( |
| 140 | + override_env("ARCH", aot_arch), |
| 141 | + override_env("FLYDSL_GPU_ARCH", aot_arch), |
| 142 | + FakeTensorMode(), |
| 143 | + ): |
| 144 | + launcher, ws_slots, _ = _build_launcher(k, num_rows, max_model_len) |
| 145 | + |
| 146 | + dev = torch.device("cpu") |
| 147 | + next_n = 1 |
| 148 | + logits = torch.empty( |
| 149 | + (num_rows, max_model_len), dtype=torch.float32, device=dev |
| 150 | + ) |
| 151 | + seq = torch.empty( |
| 152 | + (max(_required_seq_rows(next_n, num_rows), 1),), |
| 153 | + dtype=torch.int32, |
| 154 | + device=dev, |
| 155 | + ) |
| 156 | + idx = torch.empty((num_rows, k), dtype=torch.int32, device=dev) |
| 157 | + ws = torch.empty((max(ws_slots, 1),), dtype=torch.int32, device=dev) |
| 158 | + stream = fx.Stream(0) |
| 159 | + |
| 160 | + # Call the launcher directly (like the GEMM/MoE AOT), NOT via |
| 161 | + # _run_compiled/flyc.compile. Under COMPILE_ONLY the JitFunction.__call__ |
| 162 | + # writes the disk cache under the runtime cache key and returns before |
| 163 | + # engine init / launch; flyc.compile instead builds a runnable |
| 164 | + # CompiledFunction, which loads the code object even under COMPILE_ONLY -- |
| 165 | + # loading a cross-arch object faults the GPU. Same cache key either way. |
| 166 | + # Fake tensors give create_buffer_resource its descriptors; COMPILE_ONLY |
| 167 | + # skips the launch, so no tensor data is read. |
| 168 | + with compile_only_env(): |
| 169 | + launcher( |
| 170 | + logits, |
| 171 | + next_n, |
| 172 | + seq, |
| 173 | + idx, |
| 174 | + ws, |
| 175 | + num_rows, |
| 176 | + int(logits.stride(0)), |
| 177 | + int(logits.stride(1)), |
| 178 | + stream, |
| 179 | + ) |
| 180 | + |
| 181 | + elapsed = time.time() - t0 |
| 182 | + result["compile_time"] = elapsed |
| 183 | + print(f" [OK] compile {elapsed:6.1f}s {kernel_name} arch={aot_arch}") |
| 184 | + except Exception as e: |
| 185 | + print(f" [FAIL] compile {kernel_name} arch={aot_arch}: {e}") |
| 186 | + |
| 187 | + return result |
| 188 | + |
| 189 | + |
| 190 | +def main() -> None: |
| 191 | + ap = argparse.ArgumentParser( |
| 192 | + description="AOT pre-compile FlyDSL decode Top-K kernels from a config CSV", |
| 193 | + formatter_class=argparse.RawTextHelpFormatter, |
| 194 | + ) |
| 195 | + ap.add_argument("--csv", type=str, nargs="+", default=DEFAULT_CSVS) |
| 196 | + args = ap.parse_args() |
| 197 | + |
| 198 | + csv_paths = [os.path.abspath(p) for p in args.csv] |
| 199 | + for p in csv_paths: |
| 200 | + if not os.path.isfile(p): |
| 201 | + print(f"Error: CSV not found: {p}") |
| 202 | + sys.exit(1) |
| 203 | + |
| 204 | + cache_dir = os.path.expanduser( |
| 205 | + os.environ.get("FLYDSL_RUNTIME_CACHE_DIR", "~/.flydsl/cache") |
| 206 | + ) |
| 207 | + arch = os.environ.get("ARCH") or os.environ.get("GPU_ARCHS") or "(from cu_num)" |
| 208 | + jobs = collect_aot_jobs(csv_paths, parse_csv) |
| 209 | + |
| 210 | + print("=" * 72) |
| 211 | + print("FlyDSL Top-K AOT Pre-compilation") |
| 212 | + print("=" * 72) |
| 213 | + for csv_path in csv_paths: |
| 214 | + print(f" CSV: {csv_path}") |
| 215 | + print(f" Total jobs: {len(jobs)}") |
| 216 | + print(f" Cache dir: {cache_dir}") |
| 217 | + print(f" Target arch: {arch}") |
| 218 | + print("=" * 72) |
| 219 | + |
| 220 | + total_t0 = time.time() |
| 221 | + results = [] |
| 222 | + for i, job in enumerate(jobs, 1): |
| 223 | + print(f"\n[{i}/{len(jobs)}] ", end="") |
| 224 | + results.append(compile_one_config(**job)) |
| 225 | + |
| 226 | + ok = sum(1 for r in results if r["compile_time"] is not None) |
| 227 | + fail = sum(1 for r in results if r["compile_time"] is None) |
| 228 | + |
| 229 | + print("\n" + "=" * 72) |
| 230 | + print(f" Total time: {time.time() - total_t0:.1f}s") |
| 231 | + print(f" Compiled: {ok} ok, {fail} failed") |
| 232 | + print(f" Cache dir: {cache_dir}") |
| 233 | + print() |
| 234 | + if fail > 0: |
| 235 | + print("Some compilations failed. Check output above for details.") |
| 236 | + sys.exit(1) |
| 237 | + print("All compilations succeeded. Cache is ready.") |
| 238 | + sys.exit(0) |
| 239 | + |
| 240 | + |
| 241 | +if __name__ == "__main__": |
| 242 | + main() |
0 commit comments