add add-flashinfer-solution skill for e2e Solution authoring workflow

#7
skills/add-flashinfer-solution/SKILL.md ADDED
@@ -0,0 +1,821 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: add-flashinfer-solution
3
+ description: End-to-end workflow for adding a new Solution to the flashinfer-trace dataset, running its benchmark with flashinfer-bench, and visualizing traces in the web UI / public leaderboard. Use when implementing a new attention / GEMM / MoE / RMSNorm / sampling kernel as a Solution against an existing Definition, integrating a third-party kernel library (Flash Attention, FLA, SGLang, TRT-LLM, vLLM, cuDNN, etc.), or onboarding new contributors to the benchmark workflow.
4
+ ---
5
+
6
+ # Add a New Solution → Run Benchmark → Visualize Traces
7
+
8
+ End-to-end guide. Read sections in order on first use; jump to specific sections via the index after that.
9
+
10
+ ## Index
11
+
12
+ 1. [When to use this skill](#1-when-to-use-this-skill)
13
+ 2. [Background: flashinfer-bench vs flashinfer-trace](#2-background-flashinfer-bench-vs-flashinfer-trace)
14
+ 3. [Prerequisites](#3-prerequisites)
15
+ 4. [Workflow overview (7 steps)](#4-workflow-overview)
16
+ 5. [Step 1 — Pick a Definition + audit existing solutions](#step-1--pick-a-definition--audit-existing-solutions)
17
+ 6. [Step 2 — Pull workload LFS data](#step-2--pull-workload-lfs-data)
18
+ 7. [Step 3 — Write the wrapper (`main.py`)](#step-3--write-the-wrapper-mainpy)
19
+ 8. [Step 4 — Write the Solution JSON](#step-4--write-the-solution-json)
20
+ 9. [Step 5 — Run benchmark with `flashinfer-bench run`](#step-5--run-benchmark-with-flashinfer-bench-run)
21
+ 10. [Step 6 — Inspect generated traces](#step-6--inspect-generated-traces)
22
+ 11. [Step 7 — Visualize](#step-7--visualize)
23
+ 12. [Common gotchas](#common-gotchas)
24
+ 13. [Reference & templates](#reference--templates)
25
+
26
+ ---
27
+
28
+ ## 1. When to use this skill
29
+
30
+ Trigger this skill when:
31
+ - You are implementing a **new kernel** as a Solution for an existing Definition in `flashinfer-trace`
32
+ - You are wrapping a **third-party library** (Flash Attention, Flash Linear Attention, SGLang vendored kernel, TRT-LLM, vLLM, cuDNN, xFormers, …) so it can run inside `flashinfer-bench`
33
+ - You need to **run the benchmark** and produce traces (latency / speedup / correctness) for a Solution
34
+ - You want to **visualize results** in the local Next.js web UI or upload to https://bench.flashinfer.ai
35
+
36
+ Do NOT use this skill for:
37
+ - Adding a new Definition (use the official `extract-kernel-definitions` skill)
38
+ - Collecting Workload tensor data from a SGLang inference run (use `collect-workloads`)
39
+ - Onboarding a brand-new model (use `onboard-model`)
40
+
41
+ ## 2. Background: flashinfer-bench vs flashinfer-trace
42
+
43
+ Two repos, two roles:
44
+
45
+ | Repo | Role | Contains |
46
+ |---|---|---|
47
+ | **flashinfer-bench** (https://github.com/flashinfer-ai/flashinfer-bench) | benchmark **codebase / framework** | Python package `flashinfer_bench/` + CLI (`flashinfer-bench run`, `flashinfer-bench report …`) + Next.js web UI under `web/` |
48
+ | **flashinfer-trace** (https://huggingface.co/datasets/flashinfer-ai/flashinfer-trace) | benchmark **dataset** | `definitions/`, `solutions/`, `workloads/`, `blob/workloads/` (LFS), `traces/` |
49
+
50
+ Data model:
51
+
52
+ ```
53
+ Definition ──── what kernel + parameter space (axes, inputs, outputs, reference impl)
54
+ Workload ──── concrete tensor inputs for one Definition instance (UUID-keyed)
55
+ Solution ──── one implementation of a Definition (Python / Triton / CUDA / …)
56
+ Trace ──── result of running a Solution on a Workload (latency, speedup, status)
57
+ ```
58
+
59
+ Adding a new Solution = create the JSON + `main.py` under `solutions/<author>/<op_type>/<def_name>/`, then run `flashinfer-bench run` to evaluate it against existing Workloads, which writes Traces under `traces/<author>/<op_type>/<def_name>.jsonl`.
60
+
61
+ ## 3. Prerequisites
62
+
63
+ ### 3.1 Hardware
64
+ - Linux x86_64 + NVIDIA GPU (H100 PCIe / SXM, B200, L40, A100 ... see Definition `target_hardware` to check compatibility)
65
+
66
+ ### 3.2 Disk space
67
+ - **Important**: home quota is typically tight (~5 GB). Place all heavy dirs on a scratch path:
68
+ ```
69
+ HOME (small):
70
+ /home/<user>/kernel_arena/
71
+ flashinfer-bench → symlink → SCRATCH
72
+ flashinfer-trace → symlink → SCRATCH
73
+ scripts/ → symlink → SCRATCH
74
+ results/ → symlink → SCRATCH
75
+
76
+ SCRATCH (~700 GB):
77
+ /home/scratch.<user>/kernel_arena/
78
+ flashinfer-bench/ # Codebase clone
79
+ flashinfer-trace/ # Dataset clone (LFS data lives here)
80
+ scripts/ # Your wrapper scripts, run scripts
81
+ results/ # Run logs
82
+ ```
83
+ - LFS data per Workload: ~500 KB–2 MB; pulling 50–100 Workloads is typically <100 MB
84
+
85
+ ### 3.3 Environment — recommended: pre-built `.sqsh` image
86
+
87
+ If your team has a pre-built `flashinfer-bench-runner.sqsh` on shared
88
+ scratch (see Section 3.5 for how to build one), use it directly. Zero pip
89
+ install per invocation, ~5 min saved per `crun` job. This is the
90
+ recommended path for collaborators consuming the image.
91
+
92
+ ```bash
93
+ crun -q 'gpu.chip=gh100 and cpu.arch=x86_64' --gpus=1 -C \
94
+ -img /home/scratch.<team-shared>/containers/flashinfer-bench-runner.sqsh \
95
+ -r /tmp <your_script>.sh
96
+ ```
97
+
98
+ FYI: /home/scratch.yuny_wwfo/containers/flashinfer-bench-runner.sqsh is the one I built
99
+
100
+ Inside `<your_script>.sh`, **no pip install needed** — everything is baked
101
+ in. Jump straight to the dataset:
102
+
103
+ ```bash
104
+ cd /home/scratch.<your-user>/kernel_arena/flashinfer-trace
105
+ flashinfer-bench run --local . --definitions <def> --solutions <sol> ...
106
+ ```
107
+
108
+ ### 3.4 Environment — fallback: `crun -img nvcr.io/...` + per-run pip install
109
+
110
+ If a pre-built `.sqsh` is not available (first contributor on a new
111
+ cluster; one-off Solution authoring; you can't or don't want to build an
112
+ image), the fallback is the path used to verify the three reference
113
+ Solutions before the sqsh existed. Zero NGC API key setup, zero docker
114
+ daemon, zero custom image — `crun` pulls the NGC base on the compute node
115
+ (which has cluster-configured NGC credentials), and the user script
116
+ installs pip dependencies into `/tmp/pip-pkgs` inside that container.
117
+
118
+ Per-run cost: ~5 min pip install at start of every `crun` invocation. The
119
+ torch 2.5 → 2.12 upgrade triggered by `fla-core` is the dominant time.
120
+
121
+ ```bash
122
+ crun -q 'gpu.chip=gh100 and cpu.arch=x86_64' --gpus=1 -C \
123
+ -img nvcr.io/nvidia/pytorch:24.10-py3 \
124
+ -r /tmp <your_script>.sh
125
+ ```
126
+
127
+ Inside `<your_script>.sh`:
128
+
129
+ ```bash
130
+ PIP_TARGET=/tmp/pip-pkgs
131
+ mkdir -p "$PIP_TARGET"
132
+ export PYTHONPATH="$PIP_TARGET:$PYTHONPATH"
133
+ export PATH="$PIP_TARGET/bin:$PATH"
134
+
135
+ # Match the stack used to verify the three reference Solutions:
136
+ # `flashinfer-python==0.6.9` is pinned for CuTe DSL ABI; everything else
137
+ # lets pip pick the latest compatible (which is what the reference Solutions
138
+ # were verified against — flashinfer-bench 0.1.2, fla-core 0.5.0,
139
+ # nvidia-cutlass-dsl 4.5.0, cuda-python 13.2.0, torch upgraded to 2.12).
140
+ pip install --target "$PIP_TARGET" --no-cache-dir \
141
+ flashinfer-python==0.6.9 \
142
+ flashinfer-bench \
143
+ flash-linear-attention \
144
+ "nvidia-cutlass-dsl[cu13]" \
145
+ cuda-python \
146
+ safetensors huggingface-hub
147
+ ```
148
+
149
+ **Why `flashinfer-python` is pinned but the rest are not**: the CuTe DSL
150
+ GDN kernel inside `flashinfer-python==0.6.9` has tight ABI coupling with
151
+ the cutlass-dsl + cuda-python versions; pinning the latest of those + a
152
+ known-good `flashinfer-python` is what the three reference Solutions were
153
+ verified with. Other packages float to latest deliberately so the script
154
+ keeps working as PyPI publishes minor revisions.
155
+
156
+ For wrappers that need additional libraries:
157
+ - **FA3**: add a source-build step (`cd /tmp && git clone https://github.com/Dao-AILab/flash-attention.git && cd flash-attention/hopper && python setup.py install`); ~15-25 min one-time compile
158
+ - **SGLang vendored kernel**: vendor the kernel file into your Solution's `sources/` — no pip install required
159
+
160
+ ### 3.5 Building a `.sqsh` image (one-time, ~30 min)
161
+
162
+ The pre-built `.sqsh` is created once on a GPU compute node (frontend
163
+ cannot run `enroot start` because of VS Code SSH session cgroup namespace
164
+ constraints) and dropped at a shared scratch path for the team to consume.
165
+
166
+ **Prerequisites**:
167
+ - NGC API key in `~/.config/enroot/.credentials` (one-time):
168
+ ```bash
169
+ mkdir -p ~/.config/enroot && chmod 700 ~/.config/enroot
170
+ cat > ~/.config/enroot/.credentials <<EOF
171
+ machine nvcr.io login \$oauthtoken password <YOUR_NGC_API_KEY>
172
+ machine authn.nvidia.com login \$oauthtoken password <YOUR_NGC_API_KEY>
173
+ EOF
174
+ chmod 600 ~/.config/enroot/.credentials
175
+ ```
176
+ Generate the key at https://ngc.nvidia.com → Account → API Keys.
177
+
178
+ - Scratch path with ~50 GB free (NGC base sqsh 18 GB + final sqsh 22 GB +
179
+ enroot cache 10 GB).
180
+
181
+ **Build script** (drop at `/home/scratch.<user>/.fbench-build/build_on_gpu.sh`):
182
+
183
+ ```bash
184
+ #!/bin/bash
185
+ set -e
186
+ export ENROOT_CACHE_PATH=/home/scratch.<user>/.enroot-cache
187
+ export ENROOT_DATA_PATH=/home/scratch.<user>/.enroot-data
188
+ mkdir -p $ENROOT_CACHE_PATH $ENROOT_DATA_PATH \
189
+ /home/scratch.<user>/containers
190
+ cd /home/scratch.<user>/containers
191
+
192
+ echo "=== HOST: $(hostname) @ $(date) ==="
193
+
194
+ # Step 1: pull NGC base → sqsh (~10 min, first time only; subsequent builds reuse)
195
+ BASE_SQSH=$(ls *pytorch+24.10-py3*.sqsh 2>/dev/null | head -1)
196
+ if [ -z "$BASE_SQSH" ]; then
197
+ enroot import 'docker://nvcr.io#nvidia/pytorch:24.10-py3'
198
+ BASE_SQSH=$(ls *pytorch+24.10-py3*.sqsh | head -1)
199
+ fi
200
+ echo "Base: $BASE_SQSH"
201
+
202
+ # Step 2: create instance + install pip layer
203
+ enroot remove -f fbench-build 2>/dev/null || true
204
+ enroot create --name fbench-build "$BASE_SQSH"
205
+
206
+ enroot start --rw --root fbench-build bash -c '
207
+ set -e
208
+ # The NGC base image ships a broken /root/.local/bin/pip whose shebang
209
+ # points to /bin/python3.11, which does not exist. Use `python -m pip`
210
+ # to invoke the container python directly.
211
+ rm -rf /root/.local
212
+ apt-get update && apt-get install -y --no-install-recommends git-lfs
213
+ python -m pip install --no-cache-dir \
214
+ flashinfer-python==0.6.9 \
215
+ flashinfer-bench \
216
+ flash-linear-attention \
217
+ "nvidia-cutlass-dsl[cu13]" \
218
+ cuda-python safetensors huggingface-hub
219
+ python -c "
220
+ import torch; print(\"torch:\", torch.__version__)
221
+ import flashinfer_bench; print(\"flashinfer-bench OK\")
222
+ import fla; print(\"fla OK\")
223
+ "
224
+ '
225
+
226
+ # Step 3: export final sqsh (~5 min mksquashfs compression)
227
+ rm -f flashinfer-bench-runner.sqsh
228
+ enroot export --output flashinfer-bench-runner.sqsh fbench-build
229
+ enroot remove -f fbench-build
230
+ chmod 644 flashinfer-bench-runner.sqsh
231
+ ls -lh flashinfer-bench-runner.sqsh
232
+ echo "=== DONE @ $(date) ==="
233
+ ```
234
+
235
+ **Submit on a GPU compute node** (not frontend — frontend's VS Code SSH
236
+ cgroup namespace breaks `enroot start`):
237
+
238
+ ```bash
239
+ srun -p 'a100-80gb-pcie@cr+mp/h12sswnt/1gpu-16cpu-128gb' \
240
+ --gres=gpu:1 -t 0:45:00 \
241
+ bash /home/scratch.<user>/.fbench-build/build_on_gpu.sh
242
+ ```
243
+
244
+ A100 1-GPU partition is fine — the build doesn't use the GPU, it just
245
+ needs a host shell outside the front-end VS Code session cgroup.
246
+
247
+ Total wall time: ~25-30 min on first build, ~20 min on rebuilds (Step 1
248
+ base sqsh cached).
249
+
250
+ After the run, the final `flashinfer-bench-runner.sqsh` (~22 GB) is at
251
+ `/home/scratch.<user>/containers/flashinfer-bench-runner.sqsh`. Move it to
252
+ team-shared scratch and tell collaborators to use it via Section 3.3.
253
+
254
+ ### 3.6 Clone the dataset
255
+ ```bash
256
+ cd /home/scratch.<user>/kernel_arena
257
+ git clone https://huggingface.co/datasets/flashinfer-ai/flashinfer-trace
258
+ cd flashinfer-trace
259
+ git-lfs install --local
260
+ # Don't pull all LFS yet — pull only the Workloads you need (Step 2)
261
+ ```
262
+
263
+ ### 3.7 (Optional) Clone the framework codebase for the local web UI
264
+ ```bash
265
+ git clone https://github.com/flashinfer-ai/flashinfer-bench.git
266
+ ```
267
+
268
+ ## 4. Workflow overview
269
+
270
+ ```
271
+ Step 1 ── Pick a Definition + audit existing solutions
272
+ Step 2 ── Pull workload LFS data (just for that Definition)
273
+ Step 3 ── Write wrapper (main.py)
274
+ Step 4 ── Write Solution JSON
275
+ Step 5 ── Run benchmark with `flashinfer-bench run`
276
+ Step 6 ── Inspect generated traces
277
+ Step 7 ── Visualize (web UI / public site)
278
+ ```
279
+
280
+ Estimated time for an experienced contributor:
281
+ - First time end-to-end: **half a day to a full day** (env setup dominates)
282
+ - Subsequent solutions on same env: **1–2 hours per Solution**
283
+
284
+ ---
285
+
286
+ ## Step 1 — Pick a Definition + audit existing solutions
287
+
288
+ ### 1.1 Find candidate Definition
289
+
290
+ Browse `flashinfer-trace/definitions/<op_type>/` and pick a JSON file. The filename matches the Definition `name`.
291
+
292
+ ```bash
293
+ ls /home/scratch.<user>/kernel_arena/flashinfer-trace/definitions/
294
+ # dsa_paged gdn gemm gqa_paged gqa_ragged mamba_ssu
295
+ # mla_paged mla_ragged moe rmsnorm rope sampling
296
+ ls /home/scratch.<user>/kernel_arena/flashinfer-trace/definitions/gqa_paged/
297
+ # gqa_paged_decode_h32_kv8_d128_ps1.json
298
+ # gqa_paged_decode_h32_kv8_d128_ps64.json
299
+ # ...
300
+ ```
301
+
302
+ ### 1.2 Read the Definition JSON
303
+
304
+ Field semantics → see [`reference/definition_schema.md`](reference/definition_schema.md). Key fields to confirm before writing the wrapper:
305
+
306
+ | Field | What to confirm |
307
+ |---|---|
308
+ | `axes` | Which dims are `const` (compile-time) vs `var` (runtime). Wrapper signature must accept all `var` axes |
309
+ | `inputs` | Tensor names + dtypes + shapes. Wrapper signature must match exactly |
310
+ | `outputs` | Whether output is allocated by wrapper (return) or pre-allocated (`destination_passing_style: true`) |
311
+ | `tags` | `fi_api:` tells you which FlashInfer API the Definition was modeled after — your Solution may want to follow the same contract |
312
+ | `reference.code` | The PyTorch reference implementation. Read it to understand semantics (sm_scale, masking, LSE base, etc.) |
313
+
314
+ ### 1.3 Audit existing solutions for that Definition
315
+
316
+ ```bash
317
+ DEF=mla_paged_decode_h16_ckv512_kpe64_ps1
318
+ OP=mla_paged
319
+ TRACE=/home/scratch.<user>/kernel_arena/flashinfer-trace
320
+ for author in baseline claude-opus-4-1-20250805 gemini-2.5-pro gpt-5-2025-08-07 gpt-o3; do
321
+ p="$TRACE/solutions/$author/$OP/$DEF"
322
+ if [ -d "$p" ]; then
323
+ echo "$author:"
324
+ ls "$p"
325
+ fi
326
+ done
327
+ ```
328
+
329
+ Why: read existing Solutions' `main.py` to understand:
330
+ - How they map `axes` / `inputs` to function arguments
331
+ - How they handle paged KV layout (flat indices vs 2D page table)
332
+ - How they convert LSE base, sm_scale, dtype
333
+ - Whether they pre-allocate output (`destination_passing_style`)
334
+
335
+ The `baseline/` solution (FlashInfer wrapper) is the ground-truth reference — match its function signature.
336
+
337
+ ---
338
+
339
+ ## Step 2 — Pull workload LFS data
340
+
341
+ Workload tensors live in `blob/workloads/<op_type>/<def_name>/<def_name>_<uuid>.safetensors`, stored as Git-LFS. Pull selectively to save disk:
342
+
343
+ ### 2.1 Pull all workloads for one Definition
344
+ ```bash
345
+ cd /home/scratch.<user>/kernel_arena/flashinfer-trace
346
+ DEF=mla_paged_decode_h16_ckv512_kpe64_ps1
347
+ OP=mla_paged
348
+ git-lfs pull --include="blob/workloads/$OP/$DEF/*"
349
+ ```
350
+
351
+ ### 2.2 Pull only N workloads (for quick iteration on a tight quota)
352
+
353
+ Each Workload UUID is one entry in `workloads/<op>/<def>.jsonl`. Use head to take the first N:
354
+
355
+ ```bash
356
+ WL_FILE=workloads/$OP/$DEF.jsonl
357
+ UUIDS=$(head -5 "$WL_FILE" | python3 -c "import json,sys; [print(json.loads(l)['uuid']) for l in sys.stdin]")
358
+ INCLUDES=""
359
+ for u in $UUIDS; do
360
+ INCLUDES="${INCLUDES}${INCLUDES:+,}blob/workloads/$OP/$DEF/${DEF}_${u}.safetensors"
361
+ done
362
+ git-lfs pull --include="$INCLUDES"
363
+ ```
364
+
365
+ ### 2.3 Temp-trim the workloads jsonl to N entries (so the runner only sees those N)
366
+ ```bash
367
+ WL_FILE=workloads/$OP/$DEF.jsonl
368
+ cp "$WL_FILE" "$WL_FILE.bak"
369
+ head -5 "$WL_FILE.bak" > "$WL_FILE"
370
+ # After your run, restore:
371
+ # mv "$WL_FILE.bak" "$WL_FILE"
372
+ ```
373
+
374
+ Tip: a `bash trap` cleanup line is the safest way to ensure the original jsonl is restored even on script failure.
375
+
376
+ ### 2.4 Verify workloads exist
377
+ ```bash
378
+ find blob/workloads/$OP/$DEF -name "*.safetensors" -size +1k | head -5
379
+ ```
380
+
381
+ ---
382
+
383
+ ## Step 3 — Write the wrapper (`main.py`)
384
+
385
+ The wrapper is a single Python file at:
386
+ ```
387
+ solutions/<author>/<op_type>/<def_name>/main.py
388
+ ```
389
+
390
+ ### 3.1 Wrapper signature contract
391
+
392
+ Function signature must match the Definition's `inputs` exactly:
393
+ - Each `inputs[].name` becomes a positional or keyword argument
394
+ - Each `axes[].name` (the `var` ones) is also passed
395
+ - Tensor dtypes / shapes match `inputs[].dtype` / `inputs[].shape`
396
+
397
+ Default entry point is `main.py::run`. Function returns the output tensor(s) in the order declared by `outputs[]`.
398
+
399
+ If `spec.destination_passing_style: true`, output tensors are pre-allocated and passed in — modify them in place, then return None or a status flag.
400
+
401
+ ### 3.2 Three wrapper patterns (templates)
402
+
403
+ Pick the template closest to your situation:
404
+
405
+ | Pattern | When to use | Template |
406
+ |---|---|---|
407
+ | **Dense baseline** | Wrapping a generic dense impl (PyTorch SDPA / cuDNN frontend) for reference | [`templates/dense_baseline_main.py`](templates/dense_baseline_main.py) |
408
+ | **External Python lib** | Wrapping a pip-installable third-party lib (`fla-core`, `flash-attn`, `xformers`, `triton.ops` …) | [`templates/linear_attention_main.py`](templates/linear_attention_main.py) |
409
+ | **Vendored kernel** | Bringing in a Triton / CUDA kernel file from another project (SGLang / vLLM / private) without depending on the upstream package | [`templates/vendored_kernel_main.py`](templates/vendored_kernel_main.py) |
410
+
411
+ ### 3.3 Writing checklist
412
+
413
+ - [ ] Function signature matches Definition `inputs` + `var` axes
414
+ - [ ] Output shape / dtype matches Definition `outputs`
415
+ - [ ] LSE (if produced) uses **base-2** convention (FlashInfer convention; convert from natural-log via `* (1.0 / math.log(2.0))`)
416
+ - [ ] `sm_scale` is taken from the input parameter, NOT recomputed as `1/sqrt(d)`
417
+ - [ ] Paged KV cache is read using the supplied `kv_indices` / `kv_indptr` flat layout (not assumed dense)
418
+ - [ ] GQA: kv heads broadcasted to query heads if the underlying lib expects MHA (`repeat_interleave(H_q // H_kv, dim=-2)`)
419
+ - [ ] Persistent state (e.g. recurrent kernels) returns the new state in the order Definition declares
420
+ - [ ] No global state mutation across batches (avoid using cached buffers keyed only on shape — also key on device + dtype)
421
+
422
+ See [`reference/wrapper_gotchas.md`](reference/wrapper_gotchas.md) for a full list of common pitfalls.
423
+
424
+ ---
425
+
426
+ ## Step 4 — Write the Solution JSON
427
+
428
+ Create `solutions/<author>/<op_type>/<def_name>/<solution_name>.json`:
429
+
430
+ ```json
431
+ {
432
+ "name": "my_solution_v1",
433
+ "definition": "mla_paged_decode_h16_ckv512_kpe64_ps1",
434
+ "author": "<your-author-tag>",
435
+ "spec": {
436
+ "language": "python",
437
+ "target_hardware": ["NVIDIA H100", "NVIDIA B200"],
438
+ "entry_point": "main.py::run",
439
+ "dependencies": [],
440
+ "destination_passing_style": false
441
+ },
442
+ "sources": [
443
+ {"path": "main.py", "content": "<full content of main.py>"}
444
+ ]
445
+ }
446
+ ```
447
+
448
+ ### 4.1 Field semantics
449
+
450
+ Full schema → [`reference/solution_schema.md`](reference/solution_schema.md). Quick reference:
451
+
452
+ | Field | Notes |
453
+ |---|---|
454
+ | `name` | Solution identifier. Convention: `<lib_or_method>_<op_type>_<variant_or_hash>`, e.g. `fa3_gqa_paged_decode_v1`, `sglang_mla_decode_v1` |
455
+ | `definition` | MUST exactly match the Definition `name` |
456
+ | `author` | Subdir name under `solutions/`. Pick a stable identifier for your team / lab (e.g. `acme-research`) |
457
+ | `spec.language` | `python` (most common) / `triton` / `cuda` / `tilelang` / `tvm_ffi` |
458
+ | `spec.target_hardware` | List of strings; framework checks current GPU is in this list before running |
459
+ | `spec.entry_point` | `<file>::<function>`; default is `main.py::run` |
460
+ | `spec.dependencies` | pip-installable packages required at runtime (e.g. `["flash-attn>=3.0.0", "fla-core"]`); leave `[]` if everything is vendored |
461
+ | `spec.destination_passing_style` | `true` if outputs are pre-allocated and passed in; `false` (default) if the entry function returns the outputs |
462
+ | `sources` | List of `{path, content}` dicts; include `main.py` plus any vendored `.py` / `.cu` / `.triton` files |
463
+
464
+ ### 4.2 Multi-file Solution
465
+
466
+ For vendored kernels or multi-module wrappers, list every file in `sources`:
467
+
468
+ ```json
469
+ "sources": [
470
+ {"path": "main.py", "content": "..."},
471
+ {"path": "vendored_kernel.py", "content": "..."},
472
+ {"path": "kernel.cu", "content": "..."}
473
+ ]
474
+ ```
475
+
476
+ Files are extracted to a temp dir at run time; relative imports work as expected.
477
+
478
+ ### 4.3 Tooling
479
+
480
+ `flashinfer-bench solution build .` (in the solution dir) helps generate the JSON `sources` blob from on-disk files, but writing manually with `json.dumps` from a quick Python script also works.
481
+
482
+ ---
483
+
484
+ ## Step 5 — Run benchmark with `flashinfer-bench run`
485
+
486
+ ### 5.1 Bare `flashinfer-bench run` command (inside the container)
487
+
488
+ ```bash
489
+ cd /home/scratch.<user>/kernel_arena/flashinfer-trace
490
+
491
+ flashinfer-bench run \
492
+ --local . \
493
+ --definitions <def_name> \
494
+ --solutions <solution_name_1> [<solution_name_2> ...] \
495
+ --warmup-runs 5 \
496
+ --iterations 20 \
497
+ --num-trials 1 \
498
+ --timeout 600 \
499
+ --log-level INFO
500
+ ```
501
+
502
+ ### 5.1a Full `crun` invocation (computelab / SLURM cluster) — what to actually type
503
+
504
+ On computelab and similar clusters, wrap the command in a shell script and
505
+ launch via `crun`. The script reproduces the exact path used to verify the
506
+ three reference Solutions:
507
+
508
+ ```bash
509
+ #!/bin/bash
510
+ # my_run.sh
511
+ set -e
512
+ LOGFILE=/home/yuny/kernel_arena/results/my_run_$(date +%Y%m%d_%H%M%S).log
513
+ mkdir -p $(dirname $LOGFILE)
514
+ exec > >(tee -a "$LOGFILE") 2>&1
515
+
516
+ echo "=== HOST: $(hostname) TIME: $(date) ==="
517
+
518
+ # 1. Install dependency stack into ephemeral /tmp/pip-pkgs
519
+ PIP_TARGET=/tmp/pip-pkgs
520
+ mkdir -p $PIP_TARGET
521
+ pip install --target $PIP_TARGET --no-cache-dir \
522
+ flashinfer-python==0.6.9 \
523
+ flashinfer-bench \
524
+ flash-linear-attention \
525
+ "nvidia-cutlass-dsl[cu13]" \
526
+ cuda-python \
527
+ safetensors huggingface-hub 2>&1 | tail -3
528
+ export PYTHONPATH=$PIP_TARGET:$PYTHONPATH
529
+ export PATH=$PIP_TARGET/bin:$PATH
530
+
531
+ # 2. (Optional) Deploy your solution into the dataset before running
532
+ DATASET=/home/scratch.yuny_wwfo/kernel_arena/flashinfer-trace
533
+ DST=$DATASET/solutions/<your-author>/<op_type>/<def_name>
534
+ mkdir -p $DST
535
+ cp /home/yuny/kernel_arena/solutions/<your-solution>/*.json $DST/
536
+ cp /home/yuny/kernel_arena/solutions/<your-solution>/main.py $DST/
537
+
538
+ # 3. Run the benchmark
539
+ cd $DATASET
540
+ flashinfer-bench run \
541
+ --local . \
542
+ --definitions <def_name> \
543
+ --solutions <your-solution-name> \
544
+ --warmup-runs 5 \
545
+ --iterations 20 \
546
+ --num-trials 1 \
547
+ --timeout 600 \
548
+ --log-level INFO
549
+ ```
550
+
551
+ Then submit:
552
+
553
+ ```bash
554
+ crun -q 'gpu.chip=gh100 and cpu.arch=x86_64' --gpus=1 -C \
555
+ -img nvcr.io/nvidia/pytorch:24.10-py3 \
556
+ -r /tmp /home/yuny/kernel_arena/scripts/my_run.sh
557
+ ```
558
+
559
+ GPU chip query examples:
560
+ - `gpu.chip=gh100` → H100 (PCIe / SXM)
561
+ - `gpu.chip=gb200` → B200
562
+ - `gpu.chip=ga100` → A100
563
+
564
+ **With a pre-built `.sqsh`** (Section 3.3): replace the `-img` URL with the
565
+ sqsh path, and **drop the pip-install block from the script** — deps are
566
+ already baked in:
567
+
568
+ ```bash
569
+ crun -q 'gpu.chip=gh100 and cpu.arch=x86_64' --gpus=1 -C \
570
+ -img /home/scratch.<team-shared>/containers/flashinfer-bench-runner.sqsh \
571
+ -r /tmp /home/yuny/kernel_arena/scripts/my_run.sh
572
+ ```
573
+
574
+ ### 5.2 Key flags
575
+
576
+ | Flag | Meaning |
577
+ |---|---|
578
+ | `--local <path>` | Point to a local trace dataset clone (not HF) |
579
+ | `--definitions` | Whitelist Definitions to run (space-separated; can also pass `--definitions all`) |
580
+ | `--solutions` | Whitelist Solutions to run; `baseline` (FlashInfer wrapper) typically runs as the comparison reference automatically |
581
+ | `--warmup-runs` | Forward passes before timing (default 10) |
582
+ | `--iterations` | Forward passes for timing each trial |
583
+ | `--num-trials` | Repeat trials, take median (default 3) |
584
+ | `--timeout` | Per-(solution × workload) wall time, seconds |
585
+ | `--log-level` | `DEBUG` / `INFO` / `WARNING` / `ERROR` |
586
+ | `--no-save-results` | Don't write traces (only print summary). Omit to write traces |
587
+
588
+ ### 5.3 What happens
589
+
590
+ For each (Solution × Workload) pair the runner:
591
+ 1. Loads input tensors from the workload `safetensors`
592
+ 2. Builds a baseline output via Definition `reference.code` (PyTorch)
593
+ 3. Calls the Solution's `entry_point`
594
+ 4. Compares Solution output vs baseline (rtol=1e-2, atol=1e-2 by default → status PASSED / INCORRECT_NUMERICAL)
595
+ 5. Times `iterations` warmup + measured passes → reports latency, ref_latency, speedup
596
+
597
+ Result is a row in `traces/<author>/<op_type>/<def_name>.jsonl`.
598
+
599
+ ### 5.4 Status enum
600
+
601
+ | Status | Meaning |
602
+ |---|---|
603
+ | `PASSED` | Output within tolerance, latency measured |
604
+ | `INCORRECT_NUMERICAL` | rtol / atol exceeded |
605
+ | `RUNTIME_ERROR` | Exception during execution (true exception is hidden by worker isolation — see Common gotchas) |
606
+ | `TIMEOUT` | Exceeded `--timeout` |
607
+ | `SETUP_FAILED` | Failed to set up baseline / solution before measurement |
608
+
609
+ ---
610
+
611
+ ## Step 6 — Inspect generated traces
612
+
613
+ After `flashinfer-bench run`, check:
614
+
615
+ ```bash
616
+ TRACE=/home/scratch.<user>/kernel_arena/flashinfer-trace
617
+ find $TRACE/traces -name "*.jsonl" -newer $TRACE/run.log 2>/dev/null
618
+ # Or just list everything:
619
+ find $TRACE/traces -name "*<def_name>*.jsonl" -size +100c
620
+ ```
621
+
622
+ ### 6.1 Per-trace inspection
623
+ ```bash
624
+ head -1 $TRACE/traces/<author>/<op>/<def>.jsonl | python3 -m json.tool | head -40
625
+ ```
626
+
627
+ Key fields per trace row:
628
+ - `definition`, `solution`, `workload.uuid`
629
+ - `evaluation.status` (PASSED / RUNTIME_ERROR / …)
630
+ - `evaluation.environment.hardware` (e.g. `NVIDIA H100 PCIe`)
631
+ - `evaluation.performance.speedup_factor`, `latency_ms`, `reference_latency_ms`
632
+ - `evaluation.correctness.max_absolute_error`, `max_relative_error`
633
+
634
+ ### 6.2 Quick stats from CLI
635
+ ```bash
636
+ flashinfer-bench report best --local . 2>&1 | head -40
637
+ flashinfer-bench report summary --local . 2>&1 | head -40
638
+ ```
639
+
640
+ > Note: The `flashinfer-bench report visualize` CLI subcommand has a known issue in the current 0.6.x release where it treats Pydantic objects as dicts (`.get(...)`) and raises AttributeError. Use `report best` / `report summary` for CLI-level inspection, and the web UI (Step 7) for full visualization.
641
+
642
+ ---
643
+
644
+ ## Step 7 — Visualize
645
+
646
+ Two paths:
647
+
648
+ ### 7.1 Public site (read-only, official traces only)
649
+
650
+ https://bench.flashinfer.ai
651
+
652
+ This site is the production build of `flashinfer-bench/web/`. It shows the official `baseline` + `claude-…` / `gemini-…` / `gpt-…` author traces but NOT your local traces. It also has a `/viewer` page that accepts a single trace JSON as paste-in for inspection.
653
+
654
+ ### 7.2 Local web UI (sees your traces)
655
+
656
+ The local Next.js dev server reads traces from the local `flashinfer-trace` clone:
657
+
658
+ ```bash
659
+ # Install pnpm (if not already; standalone binary is the simplest path)
660
+ curl -fsSL -o ~/bin/pnpm \
661
+ https://github.com/pnpm/pnpm/releases/download/v9.15.0/pnpm-linuxstatic-x64
662
+ chmod +x ~/bin/pnpm
663
+ export PATH=~/bin:$PATH
664
+
665
+ # Configure pnpm to store packages on scratch (avoids home-quota issues)
666
+ mkdir -p /home/scratch.<user>/.pnpm-store
667
+ pnpm config set store-dir /home/scratch.<user>/.pnpm-store
668
+
669
+ # Install web app dependencies
670
+ cd /home/scratch.<user>/kernel_arena/flashinfer-bench/web
671
+ pnpm install # ~2-3 minutes; produces ~1.9 GB node_modules
672
+
673
+ # Point the data loader at your local dataset
674
+ export FIB_DATASET_PATH=/home/scratch.<user>/kernel_arena/flashinfer-trace
675
+ # Belt-and-suspenders: the data loader also looks at three fallback paths;
676
+ # the surest cover is to symlink one of the fallback locations:
677
+ ln -sfn $FIB_DATASET_PATH /tmp/flashinfer-trace
678
+ ln -sfn $FIB_DATASET_PATH /home/scratch.<user>/kernel_arena/flashinfer-bench/flashinfer_trace
679
+
680
+ # Start the dev server (apps/web only; skip apps/docs to save resources)
681
+ cd apps/web
682
+ nohup pnpm dev > /tmp/dev.log 2>&1 &
683
+
684
+ # Wait until ready (typically 60–90 s on a frontend-only machine)
685
+ until grep -q "Ready in" /tmp/dev.log; do sleep 2; done
686
+ echo "Open http://localhost:3000"
687
+ ```
688
+
689
+ Notes on the web UI:
690
+ - Default port 3000 (web app), 3030 (docs)
691
+ - VS Code Remote-SSH auto-forwards port 3000 to local; otherwise set up an SSH tunnel
692
+ - **First page-load is slow** in dev mode — Next.js compiles each route on demand; `/` typically takes 200–400 s the first time, then is cached. Subsequent loads are seconds
693
+ - For a faster experience: `pnpm build && pnpm start` produces a production bundle (~10 min build, then sub-second navigation forever)
694
+
695
+ ### 7.3 Pages worth opening
696
+
697
+ | Path | Contents |
698
+ |---|---|
699
+ | `http://localhost:3000` | Leaderboard / kernel list / model list (homepage) |
700
+ | `http://localhost:3000/kernels/<def_name>` | Per-Definition page: Solutions table, fast_p curve over workloads, top-5 by speedup |
701
+ | `http://localhost:3000/models/<model_id>` | Per-model coverage page (which Definitions belong to this model, status) |
702
+ | `http://localhost:3000/viewer` | Paste a single Trace JSON to inspect raw structure |
703
+
704
+ ### 7.4 Sharing traces with collaborators
705
+
706
+ Traces are jsonl files in `traces/<author>/<op_type>/<def_name>.jsonl`. To share:
707
+ - Copy the jsonl directly (one file per (author, op_type, def))
708
+ - Open the public Viewer (https://bench.flashinfer.ai/viewer) and paste a single line of jsonl as a Trace JSON
709
+ - Or commit + push to a branch of `flashinfer-trace` and open a PR (then the public site updates after merge)
710
+
711
+ ---
712
+
713
+ ## Common gotchas
714
+
715
+ Curated from real run failures. Full list with diagnostics → [`reference/wrapper_gotchas.md`](reference/wrapper_gotchas.md).
716
+
717
+ ### Numerical / contract mismatches
718
+
719
+ | Symptom | Likely cause | Fix |
720
+ |---|---|---|
721
+ | `INCORRECT_NUMERICAL` with `max_rel_error` ~ 1e0 | LSE base mismatch (natural log vs base-2) | Multiply natural-log LSE by `1 / math.log(2)` |
722
+ | `INCORRECT_NUMERICAL`, max_abs_error proportional to `1 / sqrt(d)` | sm_scale dropped, lib defaulted to `1 / sqrt(d)` instead of the supplied value | Pass `scale=sm_scale` (or `softmax_scale=`) explicitly |
723
+ | `INCORRECT_NUMERICAL` only on long-KV workloads | GQA expansion (`repeat_interleave`) mis-axis | Expand `H_kv → H_q` along the *head* axis only |
724
+ | Output values look like garbage | `transpose_state_layout=True` not set on FLA / k-first vs k-last layout | Match the Definition's KV layout flag |
725
+ | MLA wrapper passes correctness but speedup is < 1× | Kernel is fall-back path (e.g. FA3 ps=1 hits cp.async slow path) | Try ps=64 variant or different backend |
726
+
727
+ ### Runtime / framework
728
+
729
+ | Symptom | Likely cause | Fix |
730
+ |---|---|---|
731
+ | `RUNTIME_ERROR` with no traceback shown | Worker subprocess swallowed the exception | Reproduce by `import` + calling the function directly outside `flashinfer-bench run` (skip the runner) |
732
+ | First Solution fails 3 times → all subsequent runs `SKIPPED` | `flashinfer-bench` skips Solutions with 3 consecutive failures | Fix the underlying issue or rerun targeting a different Solution; see PersistentRunner state caveats below |
733
+ | Second `flashinfer-bench run` re-uses stale baseline | PersistentRunner caches reference output keyed on (definition, workload); kill the persistent worker between runs | Pass `--runner=isolated` or restart the bench session |
734
+ | `ImportError` for vendored module despite being in `sources` | Path issue: framework extracts sources to a temp dir but `sys.path` excludes that dir | At top of `main.py`, do `sys.path.insert(0, os.path.dirname(__file__))` before importing vendored modules |
735
+
736
+ ### Environment / disk
737
+
738
+ | Symptom | Likely cause | Fix |
739
+ |---|---|---|
740
+ | `git-lfs pull` fails or outputs only pointers | git-lfs not installed locally | `git-lfs install --local`, then re-pull |
741
+ | Disk-full mid-run | Home quota too small | Move repo + scripts + results to scratch (Section 3.3) |
742
+ | `ImportError: flashinfer_bench has no attribute apply` | Old pip cache with stale flashinfer-bench | `pip install --target /tmp/pip-pkgs --no-cache-dir flashinfer-bench` |
743
+
744
+ ### Hardware-specific
745
+
746
+ | Symptom | Likely cause | Fix |
747
+ |---|---|---|
748
+ | `flashinfer.gdn` raises `'NoneType' object is not callable` (`run_pretranspose_decode is None`) on NGC PyTorch 24.10 | FlashInfer 0.6.x GDN uses CuTe DSL whose ABI doesn't match torch 2.11 in NGC 24.10 | Use FLA wrapper (Linear-Attention pattern) as the Solution; file an upstream issue if needed |
749
+ | FA3 wheel won't import (`undefined symbol`) | C++11 ABI mismatch between prebuilt wheel and PyTorch in container | Source-build FA3: `git clone Dao-AILab/flash-attention && cd hopper && python setup.py install` |
750
+ | Solution fails on B200 but works on H100 | `target_hardware` includes only H100 / wrapper hard-codes SM90 | Add `"NVIDIA B200"` to `spec.target_hardware`; verify cubin / kernel template covers SM100 |
751
+
752
+ ---
753
+
754
+ ## Reference & templates
755
+
756
+ ### Reference docs (deep dives)
757
+
758
+ - [`reference/definition_schema.md`](reference/definition_schema.md) — full Definition JSON schema with field semantics
759
+ - [`reference/solution_schema.md`](reference/solution_schema.md) — full Solution JSON schema
760
+ - [`reference/wrapper_gotchas.md`](reference/wrapper_gotchas.md) — extended troubleshooting list
761
+ - [`reference/visualization.md`](reference/visualization.md) — full web-UI / viewer setup notes including production build path
762
+
763
+ ### Wrapper templates (copy-paste starting points)
764
+
765
+ - [`templates/dense_baseline_main.py`](templates/dense_baseline_main.py) — PyTorch SDPA-style dense baseline (paged GQA decode example)
766
+ - [`templates/dense_baseline_solution.json`](templates/dense_baseline_solution.json) — matching Solution JSON
767
+ - [`templates/linear_attention_main.py`](templates/linear_attention_main.py) — third-party Python lib wrapper (FLA-style; recurrent state, gated delta rule)
768
+ - [`templates/linear_attention_solution.json`](templates/linear_attention_solution.json) — matching Solution JSON
769
+ - [`templates/vendored_kernel_main.py`](templates/vendored_kernel_main.py) — vendored Triton kernel (SGLang-style; MLA decode with split-K + LSE reduction)
770
+ - [`templates/vendored_kernel_solution.json`](templates/vendored_kernel_solution.json) — matching Solution JSON
771
+
772
+ Each template is heavily commented; the comments mark the lines you typically need to change for a new Definition.
773
+
774
+ ---
775
+
776
+ ## Quick reference: end-to-end run script
777
+
778
+ A complete script for running a single (Definition, Solution) pair from scratch:
779
+
780
+ ```bash
781
+ #!/bin/bash
782
+ set -e
783
+ USER_NAME=$(whoami)
784
+ SCRATCH=/home/scratch.${USER_NAME}_*
785
+ TRACE_ROOT=$SCRATCH/kernel_arena/flashinfer-trace
786
+ DEF=mla_paged_decode_h16_ckv512_kpe64_ps1 # ← Edit
787
+ OP=mla_paged # ← Edit
788
+ SOL=my_solution_v1 # ← Edit
789
+ AUTHOR=acme-research # ← Edit
790
+
791
+ export PIP_TARGET=/tmp/pip-pkgs
792
+ mkdir -p "$PIP_TARGET"
793
+ export PYTHONPATH="$PIP_TARGET:$PYTHONPATH"
794
+ export PATH="$PIP_TARGET/bin:$PATH"
795
+ pip install --target "$PIP_TARGET" --no-cache-dir flashinfer-bench 2>&1 | tail -2
796
+
797
+ cd "$TRACE_ROOT"
798
+ git-lfs install --local
799
+ git-lfs pull --include="blob/workloads/$OP/$DEF/*"
800
+
801
+ # (Solution files at solutions/$AUTHOR/$OP/$DEF/ are assumed already created)
802
+
803
+ flashinfer-bench run \
804
+ --local . \
805
+ --definitions "$DEF" \
806
+ --solutions "$SOL" \
807
+ --warmup-runs 5 \
808
+ --iterations 20 \
809
+ --num-trials 1 \
810
+ --timeout 600 \
811
+ --log-level INFO
812
+
813
+ # Inspect
814
+ find traces -name "*${DEF}*.jsonl" -size +100c | xargs wc -l
815
+ ```
816
+
817
+ Save as `run_single_solution.sh`, set the four `← Edit` variables, and run.
818
+
819
+ ---
820
+
821
+ **END OF SKILL**
skills/add-flashinfer-solution/reference/definition_schema.md ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Definition JSON Schema (full reference)
2
+
3
+ Each Definition JSON file lives at `definitions/<op_type>/<def_name>.json` in the `flashinfer-trace` repo. It declares a kernel's parameter space and the reference (PyTorch) implementation used for correctness checking.
4
+
5
+ ## Top-level schema
6
+
7
+ ```json
8
+ {
9
+ "name": "<string>",
10
+ "description": "<string>",
11
+ "axes": { ... },
12
+ "inputs": [ ... ],
13
+ "outputs": [ ... ],
14
+ "constraints": [ ... ],
15
+ "tags": [ ... ],
16
+ "reference": { ... }
17
+ }
18
+ ```
19
+
20
+ | Field | Type | Required | Notes |
21
+ |---|---|---|---|
22
+ | `name` | string | yes | MUST equal filename stem (no `.json`) |
23
+ | `description` | string | yes | One-line natural language description: what the op does, source model, deployment context |
24
+ | `axes` | object | yes | Map of axis_name → axis spec |
25
+ | `inputs` | list of objects | yes | Input tensor declarations |
26
+ | `outputs` | list of objects | yes | Output tensor declarations |
27
+ | `constraints` | list of strings | optional | Inter-axis constraints (natural language or symbolic) |
28
+ | `tags` | list of strings | yes | Metadata; see Tag taxonomy below |
29
+ | `reference` | object | yes | PyTorch reference impl; sees `code` field |
30
+
31
+ ## `axes` field
32
+
33
+ ```json
34
+ "axes": {
35
+ "batch_size": {"type": "var", "description": "Number of sequences"},
36
+ "num_qo_heads": {"type": "const", "value": 16, "description": "Query/output heads"},
37
+ "num_kv_heads": {"type": "const", "value": 1, "description": "Grouped KV heads"},
38
+ "head_dim": {"type": "const", "value": 128},
39
+ "page_size": {"type": "const", "value": 64},
40
+ "num_pages": {"type": "var"},
41
+ "kv_seqlen": {"type": "var", "description": "KV cache length per sequence"},
42
+ ...
43
+ }
44
+ ```
45
+
46
+ Per-axis sub-schema:
47
+
48
+ | Sub-field | Type | When | Notes |
49
+ |---|---|---|---|
50
+ | `type` | `"const"` or `"var"` | always | `const` = compile-time fixed (e.g. head_dim, sm_arch), captured in the def name; `var` = workload-time variable (batch, seq_len) |
51
+ | `value` | int / float / string | when `type=="const"` | The fixed value |
52
+ | `description` | string | optional | Human-readable purpose |
53
+
54
+ ## `inputs` and `outputs` fields
55
+
56
+ Both are lists of tensor specs:
57
+
58
+ ```json
59
+ "inputs": [
60
+ {
61
+ "name": "q",
62
+ "dtype": "bfloat16",
63
+ "shape": ["batch_size", "num_qo_heads", "head_dim"]
64
+ },
65
+ {
66
+ "name": "k_cache",
67
+ "dtype": "bfloat16",
68
+ "shape": ["num_pages", "page_size", "num_kv_heads", "head_dim"]
69
+ },
70
+ {
71
+ "name": "kv_indptr",
72
+ "dtype": "int32",
73
+ "shape": ["len_indptr"]
74
+ },
75
+ {
76
+ "name": "sm_scale",
77
+ "dtype": "float32",
78
+ "shape": [] // scalar
79
+ }
80
+ ]
81
+ ```
82
+
83
+ Per-tensor sub-schema:
84
+
85
+ | Sub-field | Notes |
86
+ |---|---|
87
+ | `name` | Variable name in the reference code AND wrapper signature |
88
+ | `dtype` | Strings: `bfloat16`, `float16`, `float32`, `int32`, `int64`, `fp8_e4m3fn`, `fp8_e5m2`, … |
89
+ | `shape` | List of strings; each entry is either an axis name (resolved at runtime) or a literal integer; empty `[]` for scalars |
90
+
91
+ Special note: the input order is the function-signature order. Some tensor inputs may be passed via the workload `safetensors` `tensor_key` field; consult `reference.code` for the actual call.
92
+
93
+ ## `constraints` field
94
+
95
+ List of natural-language strings checked at runtime by the runner before launching:
96
+
97
+ ```json
98
+ "constraints": [
99
+ "len_indptr == batch_size + 1",
100
+ "num_kv_indices == kv_indptr[-1].item()"
101
+ ]
102
+ ```
103
+
104
+ These are not parsed; they are advisory comments. The runner doesn't enforce them — it's the workload generator's responsibility to satisfy them.
105
+
106
+ ## `tags` field — taxonomy
107
+
108
+ Tags are strings of the form `<prefix>:<value>`:
109
+
110
+ | Prefix | Allowed values | Purpose |
111
+ |---|---|---|
112
+ | `stage:` | `decode`, `prefill`, `mtp`, `sparse_attention`, `topk_indexer` | Inference stage |
113
+ | `status:` | `verified`, `unverified`, `reference` | Curation status (verified = was actually produced by an inference run with confirmed correctness) |
114
+ | `model:` | `deepseek-v3`, `deepseek-r1`, `qwen3-235b`, `llama-3.1-70b`, `llama-3.2-3b`, `gemma-3-27b`, `kimi-k2`, `qwen3-next`, `nemotron-h-8b`, ... | Source model(s); a Definition may serve multiple models |
115
+ | `fi_api:` | e.g. `flashinfer.mla.BatchMLAPagedAttentionWrapper`, `flashinfer.decode.BatchDecodeWithPagedKVCacheWrapper` | The FlashInfer Python API the def is modeled after |
116
+ | `tp:` | `1`, `2`, `4`, `8`, `16` | Assumed tensor-parallel slicing |
117
+
118
+ Additional tags occasionally seen but not formally part of the taxonomy: `quant:`, `fi_module:`, etc. These are advisory.
119
+
120
+ ## `reference` field
121
+
122
+ Embeds the PyTorch reference implementation as a string of source code:
123
+
124
+ ```json
125
+ "reference": {
126
+ "code": "import torch\n\ndef run(q, k_cache, v_cache, kv_indptr, kv_indices, sm_scale):\n ...\n return out, lse\n",
127
+ "language": "python"
128
+ }
129
+ ```
130
+
131
+ | Sub-field | Notes |
132
+ |---|---|
133
+ | `code` | Full Python source defining `run(...)` (or whatever the entry point is). Must be self-contained — runner will exec it in an isolated context |
134
+ | `language` | Currently only `python` is used |
135
+
136
+ Convention: the reference function is named `run`. Its signature is the canonical contract for any wrapper Solution.
137
+
138
+ ## Worked example: `mla_paged_decode_h16_ckv512_kpe64_ps1`
139
+
140
+ ```json
141
+ {
142
+ "name": "mla_paged_decode_h16_ckv512_kpe64_ps1",
143
+ "description": "Batched Multi-head Latent Attention decode with a paged KV cache. Captured from DeepSeek V3 at TP=8.",
144
+ "axes": {
145
+ "batch_size": {"type": "var"},
146
+ "num_qo_heads": {"type": "const", "value": 16},
147
+ "ckv_dim": {"type": "const", "value": 512},
148
+ "kpe_dim": {"type": "const", "value": 64},
149
+ "page_size": {"type": "const", "value": 1},
150
+ "num_pages": {"type": "var"},
151
+ "kv_seqlen": {"type": "var"}
152
+ },
153
+ "inputs": [
154
+ {"name": "q_nope", "dtype": "bfloat16", "shape": ["batch_size", "num_qo_heads", "ckv_dim"]},
155
+ {"name": "q_pe", "dtype": "bfloat16", "shape": ["batch_size", "num_qo_heads", "kpe_dim"]},
156
+ {"name": "ckv_cache", "dtype": "bfloat16", "shape": ["num_pages", "page_size", "ckv_dim"]},
157
+ {"name": "kpe_cache", "dtype": "bfloat16", "shape": ["num_pages", "page_size", "kpe_dim"]},
158
+ {"name": "kv_indptr", "dtype": "int32", "shape": ["len_indptr"]},
159
+ {"name": "kv_indices", "dtype": "int32", "shape": ["num_kv_indices"]},
160
+ {"name": "sm_scale", "dtype": "float32", "shape": []}
161
+ ],
162
+ "outputs": [
163
+ {"name": "output", "dtype": "bfloat16", "shape": ["batch_size", "num_qo_heads", "ckv_dim"]},
164
+ {"name": "lse", "dtype": "float32", "shape": ["batch_size", "num_qo_heads"]}
165
+ ],
166
+ "constraints": [
167
+ "len_indptr == batch_size + 1",
168
+ "num_kv_indices == kv_indptr[-1].item()"
169
+ ],
170
+ "tags": [
171
+ "stage:decode",
172
+ "status:verified",
173
+ "model:deepseek-v3",
174
+ "model:deepseek-r1",
175
+ "fi_api:flashinfer.mla.BatchMLAPagedAttentionWrapper",
176
+ "tp:8"
177
+ ],
178
+ "reference": {
179
+ "language": "python",
180
+ "code": "import torch\n\ndef run(q_nope, q_pe, ckv_cache, kpe_cache, kv_indptr, kv_indices, sm_scale):\n ..."
181
+ }
182
+ }
183
+ ```
184
+
185
+ ---
186
+
187
+ ## Quick lookup: where to find what when writing a Solution
188
+
189
+ | Question while writing wrapper | Look in Definition JSON at |
190
+ |---|---|
191
+ | What are the function args? | `inputs[].name` (in order) |
192
+ | What dtype must I produce as output? | `outputs[].dtype` |
193
+ | What's the LSE shape? | `outputs[]` where `name == "lse"` |
194
+ | Is sm_scale a scalar I receive, or do I compute it? | `inputs[]` — if `sm_scale` is in inputs, USE it; do NOT recompute |
195
+ | What's the KV layout? | `inputs[].shape` for the cache tensors (paged: `[P, ps, H_kv, D]`; ragged: `[total, H_kv, D]`; MLA paged: `[P, ps, ckv_dim]` + `[P, ps, kpe_dim]`) |
196
+ | Does causal mask apply? | Definition `name` contains `causal` or `description` mentions it |
197
+ | Should I expand GQA `H_kv → H_q`? | Yes if your underlying lib only supports MHA; check `num_qo_heads` vs `num_kv_heads` axes |
198
+ | What does the reference impl look like? | `reference.code` — read it to understand exact semantics |
skills/add-flashinfer-solution/reference/solution_schema.md ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Solution JSON Schema (full reference)
2
+
3
+ Each Solution JSON file lives at `solutions/<author>/<op_type>/<def_name>/<solution_name>.json`. It declares one implementation of a Definition, including its source code (embedded in the JSON) and runtime spec.
4
+
5
+ ## Top-level schema
6
+
7
+ ```json
8
+ {
9
+ "name": "<string>",
10
+ "definition": "<string>",
11
+ "author": "<string>",
12
+ "spec": { ... },
13
+ "sources": [ ... ]
14
+ }
15
+ ```
16
+
17
+ | Field | Type | Required | Notes |
18
+ |---|---|---|---|
19
+ | `name` | string | yes | Solution identifier (unique within `<author>/<op_type>/<def_name>/`) |
20
+ | `definition` | string | yes | MUST equal a Definition `name` exactly |
21
+ | `author` | string | yes | Subdir name under `solutions/`; pick one stable identifier per team / lab |
22
+ | `spec` | object | yes | Runtime metadata |
23
+ | `sources` | list of objects | yes | Embedded source code files |
24
+
25
+ ## `name` conventions
26
+
27
+ Common patterns observed in the public dataset:
28
+
29
+ | Pattern | Used when |
30
+ |---|---|
31
+ | `flashinfer_wrapper_<6hex>` | Reserved for the official `baseline` author — calls FlashInfer Python API directly |
32
+ | `<lib>_<op_type>_v<N>` | Hand-written wrapper around a third-party lib, e.g. `fa3_gqa_paged_decode_v1`, `sglang_mla_decode_v1`, `fla_gdn_decode_v1` |
33
+ | `<author_short>_<lang>_<6hex>` | LLM-generated implementations, e.g. `gpt-5_cuda_5eb89c`, `claude-opus-4-1_triton_a98005` |
34
+
35
+ Pick a name pattern that conveys lib + op + variant; bump version (`v2`) when changing the underlying impl meaningfully.
36
+
37
+ ## `spec` field
38
+
39
+ ```json
40
+ "spec": {
41
+ "language": "python",
42
+ "target_hardware": ["NVIDIA H100", "NVIDIA B200"],
43
+ "entry_point": "main.py::run",
44
+ "dependencies": ["flash-attn>=3.0.0"],
45
+ "destination_passing_style": false
46
+ }
47
+ ```
48
+
49
+ | Sub-field | Type | Notes |
50
+ |---|---|---|
51
+ | `language` | string | `python` (most common, even when wrapping CUDA/Triton) / `triton` / `cuda` / `tilelang` / `tvm_ffi` |
52
+ | `target_hardware` | list of strings | Allowed GPU arches; runner refuses to run on unlisted hardware. Common values: `"NVIDIA H100"`, `"NVIDIA H200"`, `"NVIDIA B200"`, `"NVIDIA L40"`, `"NVIDIA A100"` |
53
+ | `entry_point` | string | `<file>::<function>`; default convention is `main.py::run` |
54
+ | `dependencies` | list of strings | Pip-installable packages required at runtime. Empty list `[]` if all needed code is vendored in `sources` |
55
+ | `destination_passing_style` | bool | `false` (default): entry function returns a tuple of output tensors. `true`: outputs are pre-allocated and passed in as additional args; entry function modifies in place and returns nothing |
56
+
57
+ ### Notes on each sub-field
58
+
59
+ #### `language`
60
+ The runner uses this only for documentation; the actual entry point loading uses `entry_point` and Python's import mechanism. Even Triton / CUDA solutions usually have `language: python` because their `main.py` is a Python wrapper that imports / launches the underlying kernel.
61
+
62
+ #### `target_hardware`
63
+ The runner introspects current GPU via `torch.cuda.get_device_name(0)`. Examples of returned strings:
64
+ - `"NVIDIA H100 PCIe"` — note: PCIe vs SXM both report `H100`-prefixed strings; matching is by prefix
65
+ - `"NVIDIA H100 80GB HBM3"`
66
+ - `"NVIDIA B200"`
67
+
68
+ Use `["NVIDIA H100", "NVIDIA B200"]` to allow both Hopper and Blackwell.
69
+
70
+ #### `entry_point`
71
+ Format: `<filename_relative_to_sources>::<function_name>`. The function is loaded via `importlib`. Default: `main.py::run`.
72
+
73
+ #### `dependencies`
74
+ Listed packages are NOT auto-installed by the runner; they must be present in the Python environment beforehand. Use `pip install --target /tmp/pip-pkgs <pkg>` and `export PYTHONPATH=/tmp/pip-pkgs:$PYTHONPATH` for ephemeral envs.
75
+
76
+ For a fully self-contained Solution, leave `dependencies: []` and embed all required source files into `sources` (vendor the kernel).
77
+
78
+ #### `destination_passing_style`
79
+ - `false` (default):
80
+ ```python
81
+ def run(q, k_cache, v_cache, ..., sm_scale):
82
+ out = ...
83
+ lse = ...
84
+ return out, lse
85
+ ```
86
+ - `true`:
87
+ ```python
88
+ def run(q, k_cache, v_cache, ..., sm_scale, output, lse):
89
+ output.copy_(...)
90
+ lse.copy_(...)
91
+ ```
92
+
93
+ Use `true` when working with kernels that strictly require pre-allocated output (e.g. some Triton kernels). Most wrappers prefer `false` for simplicity.
94
+
95
+ ## `sources` field
96
+
97
+ Embeds the entire source tree of the Solution as a JSON array:
98
+
99
+ ```json
100
+ "sources": [
101
+ {"path": "main.py", "content": "<full content as Python string>"},
102
+ {"path": "kernel.triton", "content": "..."},
103
+ {"path": "vendored.py", "content": "..."}
104
+ ]
105
+ ```
106
+
107
+ | Sub-field | Notes |
108
+ |---|---|
109
+ | `path` | Relative to the Solution's directory; use forward slashes for nested files |
110
+ | `content` | Raw file content as a UTF-8 string (escape backslashes and newlines per JSON spec) |
111
+
112
+ The runner extracts `sources` to a temp dir at run time; the entry function is loaded from there. Relative imports between files in `sources` work as expected if `main.py` includes:
113
+
114
+ ```python
115
+ import os, sys
116
+ _HERE = os.path.dirname(os.path.abspath(__file__))
117
+ if _HERE not in sys.path:
118
+ sys.path.insert(0, _HERE)
119
+ ```
120
+
121
+ ## Worked example: minimal Solution
122
+
123
+ For a Solution at `solutions/acme-research/gqa_paged/gqa_paged_decode_h32_kv8_d128_ps1/my_fa3_v1.json`:
124
+
125
+ ```json
126
+ {
127
+ "name": "my_fa3_v1",
128
+ "definition": "gqa_paged_decode_h32_kv8_d128_ps1",
129
+ "author": "acme-research",
130
+ "spec": {
131
+ "language": "python",
132
+ "target_hardware": ["NVIDIA H100", "NVIDIA B200"],
133
+ "entry_point": "main.py::run",
134
+ "dependencies": ["flash-attn>=3.0.0"],
135
+ "destination_passing_style": false
136
+ },
137
+ "sources": [
138
+ {
139
+ "path": "main.py",
140
+ "content": "import math\nimport torch\nfrom flash_attn_3 import flash_attn_with_kvcache\n\n\ndef run(q, k_cache, v_cache, kv_indptr, kv_indices, sm_scale):\n # ... wrapper body ...\n return out, lse\n"
141
+ }
142
+ ]
143
+ }
144
+ ```
145
+
146
+ ## Building a Solution JSON from on-disk files
147
+
148
+ There's no standalone CLI to do this in the public 0.6.x flashinfer-bench, so a tiny Python script is fine:
149
+
150
+ ```python
151
+ import json, os
152
+ from pathlib import Path
153
+
154
+ solution_dir = Path("solutions/acme-research/gqa_paged/gqa_paged_decode_h32_kv8_d128_ps1")
155
+ out_json = solution_dir / "my_fa3_v1.json"
156
+
157
+ sources = []
158
+ for p in sorted(solution_dir.glob("**/*")):
159
+ if p.is_file() and p.name != out_json.name and p.suffix in (".py", ".cu", ".triton", ".cpp", ".h"):
160
+ sources.append({
161
+ "path": str(p.relative_to(solution_dir)),
162
+ "content": p.read_text(),
163
+ })
164
+
165
+ doc = {
166
+ "name": "my_fa3_v1",
167
+ "definition": "gqa_paged_decode_h32_kv8_d128_ps1",
168
+ "author": "acme-research",
169
+ "spec": {
170
+ "language": "python",
171
+ "target_hardware": ["NVIDIA H100", "NVIDIA B200"],
172
+ "entry_point": "main.py::run",
173
+ "dependencies": ["flash-attn>=3.0.0"],
174
+ "destination_passing_style": False,
175
+ },
176
+ "sources": sources,
177
+ }
178
+
179
+ out_json.write_text(json.dumps(doc, indent=2))
180
+ ```
181
+
182
+ Run from the directory containing the Solution sources; produces a JSON ready for the runner.
183
+
184
+ ## Field-level checklist before committing a Solution JSON
185
+
186
+ - [ ] `name` is unique within the target def directory
187
+ - [ ] `definition` matches the actual Definition name exactly (no typos, no prefix/suffix drift)
188
+ - [ ] `author` matches an existing author dir (else create one)
189
+ - [ ] `spec.target_hardware` includes the hardware you actually tested on
190
+ - [ ] `spec.entry_point` resolves correctly (function exists in the named file)
191
+ - [ ] `spec.dependencies` list is honest — every `import` in `main.py` is either in `dependencies` or in `sources`
192
+ - [ ] `spec.destination_passing_style` matches the actual entry signature
193
+ - [ ] `sources` contains every file the entry function imports (use AST or `grep -E "^(import|from)"` to audit)
194
+ - [ ] `sources[].content` is valid UTF-8 and parses as the right language (`python -c "exec(open(p).read())"` for Python; CUDA / Triton parsing requires the relevant compiler)
195
+ - [ ] No absolute paths in source content — use `os.path.dirname(__file__)` for relative loads
skills/add-flashinfer-solution/reference/visualization.md ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Visualization Reference
2
+
3
+ Two paths: public site (read-only, official traces only) and local web UI (sees your local traces, full functionality).
4
+
5
+ ---
6
+
7
+ ## 1. Public site
8
+
9
+ URL: **https://bench.flashinfer.ai**
10
+
11
+ Reads the published `flashinfer-trace` HF dataset directly. Shows traces from authors that have been merged upstream:
12
+ - `baseline` (FlashInfer official)
13
+ - `claude-opus-4-1-20250805`, `gemini-2.5-pro`, `gpt-5-2025-08-07`, `gpt-o3` (LLM-generated)
14
+ - ... plus any author whose contributions land on the dataset's `main` branch
15
+
16
+ ### Pages
17
+ - `/` — homepage with three sections: Leaderboard / Models / Kernels
18
+ - `/kernels/<def_name>` — per-Definition page: Solutions table, fast_p curve over all workloads, top-5 by speedup
19
+ - `/models/<model_id>` — per-model coverage: which Definitions belong, status
20
+ - `/viewer` — paste a single Trace JSON to inspect the raw structure
21
+
22
+ ### `/viewer` page details
23
+ Accepts a **single** Trace JSON object. Most jsonl files have many lines (one Trace each); take just one line:
24
+
25
+ ```bash
26
+ sed -n '1p' traces/<author>/<op_type>/<def_name>.jsonl > /tmp/single.json
27
+ # Then copy /tmp/single.json contents into the textarea on /viewer
28
+ ```
29
+
30
+ Pasting the whole jsonl raises `Unexpected non-whitespace character after JSON at position …`.
31
+
32
+ ---
33
+
34
+ ## 2. Local web UI (recommended for local development)
35
+
36
+ The web UI is the production source of bench.flashinfer.ai, vendored under `flashinfer-bench/web/`. Running it locally lets you visualize traces from a local `flashinfer-trace` clone, including authors that haven't been merged upstream.
37
+
38
+ ### 2.1 Setup
39
+
40
+ ```bash
41
+ # 1. Get pnpm (the project uses pnpm workspaces)
42
+ mkdir -p ~/bin
43
+ curl -fsSL -o ~/bin/pnpm \
44
+ https://github.com/pnpm/pnpm/releases/download/v9.15.0/pnpm-linuxstatic-x64
45
+ chmod +x ~/bin/pnpm
46
+ export PATH=~/bin:$PATH
47
+
48
+ # 2. Configure pnpm to keep its store on scratch (~ 1 GB cache, plus 1.9 GB node_modules)
49
+ SCRATCH=/home/scratch.<user>
50
+ mkdir -p $SCRATCH/.pnpm-store
51
+ pnpm config set store-dir $SCRATCH/.pnpm-store
52
+
53
+ # 3. Clone flashinfer-bench codebase (if not already)
54
+ cd $SCRATCH/kernel_arena
55
+ git clone https://github.com/flashinfer-ai/flashinfer-bench.git
56
+
57
+ # 4. Install web app dependencies (~2-3 min)
58
+ cd $SCRATCH/kernel_arena/flashinfer-bench/web
59
+ pnpm install
60
+ ```
61
+
62
+ ### 2.2 Point data loader at your local dataset
63
+
64
+ The web app's data loader resolves the trace dataset path in this priority order (`apps/web/lib/data-loader.ts`):
65
+ 1. `FLASHINFER_TRACE_PATH` env var (explicit override)
66
+ 2. `FIB_DATASET_PATH` env var (set by the prebuild script)
67
+ 3. Local repo's `flashinfer_trace/` dir (`web/apps/web` → `../../../flashinfer_trace`)
68
+ 4. `/tmp/flashinfer-trace` (fallback)
69
+
70
+ Belt-and-suspenders: set the env var AND symlink at the fallback paths:
71
+
72
+ ```bash
73
+ export FIB_DATASET_PATH=$SCRATCH/kernel_arena/flashinfer-trace
74
+ ln -sfn $FIB_DATASET_PATH /tmp/flashinfer-trace
75
+ ln -sfn $FIB_DATASET_PATH $SCRATCH/kernel_arena/flashinfer-bench/flashinfer_trace
76
+ ```
77
+
78
+ ### 2.3 Start the dev server
79
+
80
+ ```bash
81
+ cd $SCRATCH/kernel_arena/flashinfer-bench/web/apps/web
82
+ nohup pnpm dev > /tmp/dev.log 2>&1 &
83
+
84
+ # Wait until ready (~60-90 s on a frontend-only host)
85
+ until grep -q "Ready in" /tmp/dev.log; do sleep 2; done
86
+ echo "Open http://localhost:3000"
87
+ ```
88
+
89
+ The dev server runs only `apps/web` (skip `apps/docs` to save resources).
90
+
91
+ ### 2.4 Caveats of dev mode
92
+
93
+ - **First page load is slow** — Next.js compiles each route on demand. The first `GET /` typically takes 200–400 s; the home page SSR fetches all 137+ Definitions × N solutions per Definition for the leaderboard. Subsequent loads are 5–20 s
94
+ - **Build process competing for CPU**: avoid running `pnpm build` in parallel with `pnpm dev`; it will stretch compile time to many minutes
95
+ - **Browser shows endless spinner**: usually first-load compilation. Check `tail -f /tmp/dev.log`; once you see `GET /<path> 200 in <ms>` the page is ready
96
+
97
+ ### 2.5 Production build (recommended for sustained use)
98
+
99
+ For more than ~30 minutes of use, build once and run a production server:
100
+
101
+ ```bash
102
+ cd $SCRATCH/kernel_arena/flashinfer-bench/web/apps/web
103
+
104
+ # Build (takes 8–15 min on a typical frontend host; produces .next/ ~1 GB)
105
+ pnpm build
106
+
107
+ # Start production server (instant; pages are SSG / ISR cached)
108
+ nohup pnpm start > /tmp/prod.log 2>&1 &
109
+ ```
110
+
111
+ Production mode:
112
+ - Pages render in <500 ms (vs 200+ s in dev)
113
+ - Hot-reload on file changes is OFF; rebuild required after data changes (re-run `pnpm build`)
114
+
115
+ ### 2.6 Page reference
116
+
117
+ | Path | Use |
118
+ |---|---|
119
+ | `http://localhost:3000` | Leaderboard table + fast_p curve + Models grid + Kernels list |
120
+ | `http://localhost:3000/kernels/<def_name>` | Per-Definition Solutions table + fast_p curve over workloads + top-5 by speedup |
121
+ | `http://localhost:3000/models/<model_id>` | Per-model coverage page |
122
+ | `http://localhost:3000/viewer` | Paste single Trace JSON for raw inspection |
123
+ | `http://localhost:3000/docs/api/python/` | Embedded Sphinx docs of `flashinfer_bench` Python API |
124
+
125
+ ---
126
+
127
+ ## 3. SSH port forwarding
128
+
129
+ If the dev server runs on a remote machine and you browse from your laptop:
130
+
131
+ ### 3.1 VS Code Remote-SSH (easiest)
132
+ - VS Code auto-detects port 3000 and forwards it to localhost on your laptop
133
+ - Look at the **PORTS** tab at the bottom; if not auto-forwarded, click `Forward a Port` and enter `3000`
134
+
135
+ ### 3.2 Manual SSH tunnel
136
+ ```bash
137
+ # From your laptop:
138
+ ssh -L 3000:localhost:3000 <user>@<remote-host>
139
+ # Then open http://localhost:3000 in your browser
140
+ ```
141
+
142
+ For HTTP keep-alive across the tunnel:
143
+ ```bash
144
+ ssh -L 3000:localhost:3000 -o ServerAliveInterval=60 -o ServerAliveCountMax=3 <user>@<remote-host>
145
+ ```
146
+
147
+ ---
148
+
149
+ ## 4. Sharing a trace with collaborators (no full UI required)
150
+
151
+ Three options:
152
+
153
+ ### 4.1 Send the jsonl file
154
+ ```bash
155
+ # One file per (author × op_type × def_name); typically 50-200 KB
156
+ scp $TRACE_ROOT/traces/<author>/<op_type>/<def_name>.jsonl reviewer@host:/tmp/
157
+ # Reviewer runs the local web UI or pastes individual rows into /viewer
158
+ ```
159
+
160
+ ### 4.2 Use the public Viewer
161
+ Take a single Trace JSON line and paste into https://bench.flashinfer.ai/viewer. Reviewer gets the same structured inspection without setup.
162
+
163
+ ```bash
164
+ sed -n '<row_number>p' $TRACE_ROOT/traces/<author>/<op_type>/<def_name>.jsonl > /tmp/single_trace.json
165
+ # Open the file, copy contents, paste at https://bench.flashinfer.ai/viewer
166
+ ```
167
+
168
+ ### 4.3 Open a PR to flashinfer-trace
169
+ Once the Solution is merged on `main`, the public site picks it up automatically (next dataset rebuild). Workflow:
170
+ - Fork `huggingface.co/datasets/flashinfer-ai/flashinfer-trace`
171
+ - Add the Solution JSON, run benchmark, commit produced traces
172
+ - Open a PR; maintainers review
173
+
174
+ ---
175
+
176
+ ## 5. Programmatic access to traces
177
+
178
+ If you want to build custom dashboards, just read the jsonl directly:
179
+
180
+ ```python
181
+ import json
182
+ from pathlib import Path
183
+
184
+ trace_root = Path("/home/scratch.<user>/kernel_arena/flashinfer-trace")
185
+ trace_file = trace_root / "traces/<author>/<op_type>/<def_name>.jsonl"
186
+
187
+ traces = [json.loads(l) for l in trace_file.read_text().splitlines()]
188
+ for t in traces:
189
+ print(
190
+ t["definition"], t["solution"],
191
+ t["evaluation"]["status"],
192
+ t["evaluation"].get("performance", {}).get("speedup_factor"),
193
+ )
194
+ ```
195
+
196
+ Or use the framework's helper:
197
+
198
+ ```python
199
+ from flashinfer_bench.data import TraceSet
200
+ ts = TraceSet.from_path(trace_root)
201
+ for def_name in ts.definitions:
202
+ best = ts.get_best_trace(def_name)
203
+ if best:
204
+ print(def_name, "→", best.solution, best.evaluation.performance.speedup_factor)
205
+ ```
206
+
207
+ `TraceSet` provides filter / best / score queries; see `flashinfer_bench/data/trace_set.py` for the full API.
skills/add-flashinfer-solution/reference/wrapper_gotchas.md ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Wrapper Gotchas (extended troubleshooting)
2
+
3
+ Catalogued issues that have surfaced when wrapping kernels for `flashinfer-bench`. Each entry has: symptom → root cause → fix → diagnostic command.
4
+
5
+ ---
6
+
7
+ ## 1. Numerical / contract mismatches
8
+
9
+ ### 1.1 LSE base mismatch (natural log vs base-2)
10
+
11
+ - **Symptom**: `INCORRECT_NUMERICAL`, `max_relative_error` ≈ `0.301` (i.e. `log10(2)`) on the LSE output specifically; output tensor itself is correct
12
+ - **Root cause**: FlashInfer uses **base-2** LSE by convention (`lse = log2(sum_exp(logits * log2(e)))`). Many third-party libs (Flash Attention, naive Triton) emit **natural-log** LSE
13
+ - **Fix**: in the wrapper, convert before returning:
14
+ ```python
15
+ import math
16
+ lse_b2 = lse_natural * (1.0 / math.log(2.0))
17
+ ```
18
+ - **Diagnostic**: print both LSEs side-by-side; ratio should be exactly `log_2(e)` ≈ `1.4427`
19
+
20
+ ### 1.2 Lost / overridden `sm_scale`
21
+
22
+ - **Symptom**: `INCORRECT_NUMERICAL` proportional to `1/sqrt(d)`; output is "almost right" but uniformly off
23
+ - **Root cause**: third-party API was called without explicitly passing the supplied `sm_scale`, so the lib defaulted to `1/sqrt(head_dim)`. FlashInfer Definitions sometimes use a different scale (e.g. for absorbed MLA prefill the scale includes the rope-dim mixing factor)
24
+ - **Fix**: always pass `sm_scale` (or whatever the lib calls it: `softmax_scale`, `scale`, `sm_scale_for_q`, …) explicitly:
25
+ ```python
26
+ out = F.scaled_dot_product_attention(q, k, v, scale=sm_scale)
27
+ out = flash_attn_with_kvcache(..., softmax_scale=sm_scale, ...)
28
+ ```
29
+ - **Diagnostic**: temporarily set `sm_scale = 1.0` in the workload; if the wrapper still produces non-trivially scaled output, scale is being silently overridden somewhere
30
+
31
+ ### 1.3 GQA expansion along wrong axis
32
+
33
+ - **Symptom**: `INCORRECT_NUMERICAL` only on long-KV workloads; short-KV passes
34
+ - **Root cause**: `repeat_interleave` to expand `H_kv → H_q` was applied along the wrong axis. Common confusion: `[B, S, H_kv, D]` vs `[B, H_kv, S, D]`
35
+ - **Fix**: always check the target lib's expected layout, then expand exactly along the head axis:
36
+ ```python
37
+ # If layout is [B, S, H, D]:
38
+ k = k.repeat_interleave(H_q // H_kv, dim=2) # not dim=1!
39
+ # If layout is [B, H, S, D]:
40
+ k = k.repeat_interleave(H_q // H_kv, dim=1)
41
+ ```
42
+ - **Diagnostic**: print `k.shape` vs `q.shape` after expansion — head dims must match
43
+
44
+ ### 1.4 KV layout direction (k-first vs k-last) for recurrent state kernels
45
+
46
+ - **Symptom**: Output garbage — recurrent state values look uniformly wrong, not just numerically off
47
+ - **Root cause**: FLA-family kernels accept state as `[B, HV, K, V]` (k-first, default) or `[B, HV, V, K]` (k-last). Many Definition specs use k-last layout (Qwen3-Next GDN), but FLA's default is k-first
48
+ - **Fix**: pass `transpose_state_layout=True` to the FLA op explicitly when the Definition uses k-last:
49
+ ```python
50
+ o, new_state = fused_recurrent_gated_delta_rule(
51
+ ..., transpose_state_layout=True
52
+ )
53
+ ```
54
+ - **Diagnostic**: check the Definition `inputs[]` shape for the state tensor; the last two dim names will tell you (e.g. `[batch, head, k_dim, v_dim]` = k-first)
55
+
56
+ ### 1.5 Custom gating not pre-applied
57
+
58
+ - **Symptom**: Output bias tracks closer to zero than expected
59
+ - **Root cause**: Some lib ops require a pre-computed gating value (e.g. `beta = sigmoid(b)` for FLA gated_delta_rule), but Definitions hand you the raw input
60
+ - **Fix**: do the activation in the wrapper:
61
+ ```python
62
+ beta = torch.sigmoid(b)
63
+ out, _ = fused_recurrent_gated_delta_rule(..., beta=beta, ...)
64
+ ```
65
+ - **Diagnostic**: read both the Definition `reference.code` AND the lib's docstring; differences in gating semantics are a common source of confusion
66
+
67
+ ### 1.6 Double L2-norm
68
+
69
+ - **Symptom**: Output magnitude consistently ~half of reference
70
+ - **Root cause**: Definition's `reference.code` already includes L2 norm, AND the lib's `use_qk_l2norm_in_kernel=True` flag was passed → applied twice
71
+ - **Fix**: confirm with one source of truth; either:
72
+ ```python
73
+ # Lib does the norm — don't pre-norm in wrapper
74
+ out = lib_op(q_raw, k_raw, ..., use_qk_l2norm_in_kernel=True)
75
+ # OR pre-norm in wrapper, lib doesn't
76
+ q_normed = F.normalize(q_raw, dim=-1)
77
+ k_normed = F.normalize(k_raw, dim=-1)
78
+ out = lib_op(q_normed, k_normed, ..., use_qk_l2norm_in_kernel=False)
79
+ ```
80
+ - **Diagnostic**: compare `out.abs().mean()` with reference; ratio of ~0.5 is the smoking gun
81
+
82
+ ### 1.7 Q tensor extra dim (4D vs 3D)
83
+
84
+ - **Symptom**: shape error `Expected 3-d but got 4-d` or vice versa
85
+ - **Root cause**: FlashInfer's decode wrappers use 3-D Q (`[B, H, D]`); FA3 expects 4-D Q (`[B, S=1, H, D]`). The wrapper needs to add or remove that S dim
86
+ - **Fix**:
87
+ ```python
88
+ q_4d = q.unsqueeze(1) # [B, H, D] -> [B, 1, H, D]
89
+ out_4d = flash_attn_with_kvcache(q_4d, ...)
90
+ out = out_4d.squeeze(1) # [B, 1, H, D] -> [B, H, D]
91
+ ```
92
+
93
+ ---
94
+
95
+ ## 2. Runtime / framework
96
+
97
+ ### 2.1 Worker subprocess swallowed traceback
98
+
99
+ - **Symptom**: Trace status `RUNTIME_ERROR` with no useful error message in logs (`--log-level DEBUG` shows the same)
100
+ - **Root cause**: `flashinfer-bench` runs each Solution in an isolated subprocess; uncaught exceptions become a status enum, the actual traceback is lost
101
+ - **Fix (diagnostic only)**: reproduce outside the runner. Write a minimal script that imports the wrapper directly and calls it with manually-loaded workload tensors:
102
+ ```python
103
+ # 17_direct_repro.py
104
+ import torch
105
+ from safetensors.torch import load_file
106
+ import sys; sys.path.insert(0, "solutions/acme/op/def_name")
107
+ from main import run
108
+
109
+ inputs = load_file("blob/workloads/op/def_name/def_name_<uuid>.safetensors")
110
+ q = inputs["q"]; k = inputs["k_cache"]; ...
111
+ out = run(q, k, ..., sm_scale=0.08838)
112
+ print(out)
113
+ ```
114
+ Run with `python -u 17_direct_repro.py` to see the real traceback.
115
+
116
+ ### 2.2 Three-strikes Solution skip
117
+
118
+ - **Symptom**: Mid-way through a long run, you see `Skipping solution X due to 3 consecutive failures`
119
+ - **Root cause**: `flashinfer-bench` short-circuits a Solution after 3 consecutive errors, treating it as broken — this affects all subsequent workloads for that Solution
120
+ - **Fix**: address the root error first; then either re-run with a smaller `--num-trials` to confirm, or delete the Solution's traces and re-run
121
+ - **Diagnostic**: count `RUNTIME_ERROR` rows in the trace jsonl per Solution; if the first 3 fail, expect skip thereafter
122
+
123
+ ### 2.3 PersistentRunner stale baseline cache
124
+
125
+ - **Symptom**: Re-running with a corrected Solution still shows the same speedup numbers
126
+ - **Root cause**: `PersistentRunner` (default for `flashinfer-bench run`) caches the reference baseline output keyed on `(definition, workload.uuid)`. If the worker subprocess crashed mid-run, that cache might be stale
127
+ - **Fix**: explicitly use the isolated runner:
128
+ ```bash
129
+ flashinfer-bench run --runner=isolated ...
130
+ ```
131
+ Or simply delete the trace file for that solution before re-running (so cached comparisons are regenerated)
132
+
133
+ ### 2.4 Vendored module import error
134
+
135
+ - **Symptom**: `ModuleNotFoundError: No module named 'sglang_decode'` despite the file being in `sources`
136
+ - **Root cause**: When the runner extracts `sources` to a temp dir, that dir is not on `sys.path`
137
+ - **Fix**: at the top of `main.py`, add:
138
+ ```python
139
+ import os, sys
140
+ _HERE = os.path.dirname(os.path.abspath(__file__))
141
+ if _HERE not in sys.path:
142
+ sys.path.insert(0, _HERE)
143
+ from vendored_module import ...
144
+ ```
145
+
146
+ ### 2.5 `flashinfer-bench report visualize` AttributeError
147
+
148
+ - **Symptom**: Calling `flashinfer-bench report visualize --local .` raises `AttributeError: 'Evaluation' object has no attribute 'get'`
149
+ - **Root cause**: A bug in the public 0.6.x release: `cli/main.py:202` calls `trace.evaluation.get("status", ...)` but `trace.evaluation` is a Pydantic object, not a dict
150
+ - **Workaround**: skip the CLI `visualize` subcommand; use `report best` / `report summary` for CLI-level inspection, and use the local web UI (Step 7 in the main SKILL doc) for the full visualization
151
+
152
+ ### 2.6 No `--max-workloads` flag
153
+
154
+ - **Symptom**: You want to run only the first N workloads of a large Definition for quick iteration; flag does not exist
155
+ - **Workaround**: temp-trim the workloads jsonl:
156
+ ```bash
157
+ WL=workloads/op/def.jsonl
158
+ cp "$WL" "$WL.bak"
159
+ head -10 "$WL.bak" > "$WL"
160
+ flashinfer-bench run ...
161
+ mv "$WL.bak" "$WL"
162
+ ```
163
+ Use a `bash trap "mv \"$WL.bak\" \"$WL\"" EXIT` to restore on script exit (including failure).
164
+
165
+ ---
166
+
167
+ ## 3. Environment / disk
168
+
169
+ ### 3.1 git-lfs returns pointer files instead of tensors
170
+
171
+ - **Symptom**: `safetensors.SafetensorError: invalid header` when loading a workload tensor
172
+ - **Root cause**: `git-lfs install --local` was not run; the file is the LFS pointer, not the actual tensor
173
+ - **Fix**:
174
+ ```bash
175
+ cd flashinfer-trace
176
+ git-lfs install --local
177
+ git-lfs pull --include="blob/workloads/<op>/<def>/*"
178
+ ```
179
+ Verify: the file size should be > 1KB (pointer files are ~130 bytes):
180
+ ```bash
181
+ find blob/workloads -name "*.safetensors" -size +1k | wc -l
182
+ ```
183
+
184
+ ### 3.2 home quota full mid-run
185
+
186
+ - **Symptom**: `OSError: [Errno 122] Disk quota exceeded` or `pip install` fails with `No space left on device`
187
+ - **Root cause**: Many corporate environments have a 5-GB home quota
188
+ - **Fix**: relocate everything to scratch:
189
+ ```bash
190
+ SCRATCH=/home/scratch.<user>/kernel_arena
191
+ mkdir -p $SCRATCH
192
+ mv ~/kernel_arena/flashinfer-trace $SCRATCH/
193
+ ln -sfn $SCRATCH/flashinfer-trace ~/kernel_arena/flashinfer-trace
194
+ # Also pip target:
195
+ export PIP_TARGET=/tmp/pip-pkgs # /tmp is usually large
196
+ ```
197
+
198
+ ### 3.3 Stale flashinfer-bench install
199
+
200
+ - **Symptom**: `ImportError: cannot import name 'apply' from 'flashinfer_bench'`
201
+ - **Root cause**: pip cache picked up an older version
202
+ - **Fix**:
203
+ ```bash
204
+ rm -rf $PIP_TARGET/flashinfer_bench*
205
+ pip install --target $PIP_TARGET --no-cache-dir flashinfer-bench
206
+ ```
207
+
208
+ ---
209
+
210
+ ## 4. Hardware-specific
211
+
212
+ ### 4.1 FlashInfer GDN CuTe DSL ABI mismatch (NGC PyTorch 24.10)
213
+
214
+ - **Symptom**: `flashinfer.gdn` import succeeds but calling `gdn_decode(...)` raises `TypeError: 'NoneType' object is not callable`; introspection shows `flashinfer.gdn.run_pretranspose_decode is None`
215
+ - **Root cause**: FlashInfer 0.6.x GDN uses CuTe DSL kernels that require NVRTC + a specific PyTorch ABI. NGC PyTorch 24.10 ships torch 2.11 with `_GLIBCXX_USE_CXX11_ABI=1`, mismatching the FlashInfer-shipped ABI; the kernel registry silently leaves the entry as `None`
216
+ - **Workaround**: use FLA's `fused_recurrent_gated_delta_rule` instead (see `templates/linear_attention_main.py`); FLA is pure Triton, no ABI dependency
217
+
218
+ ### 4.2 FA3 wheel `undefined symbol`
219
+
220
+ - **Symptom**: `import flash_attn_3` raises `undefined symbol: _ZNxxxxx` or similar
221
+ - **Root cause**: The prebuilt FA3 wheel was compiled against a different libstdc++ ABI than the PyTorch in your container
222
+ - **Fix**: source-build FA3:
223
+ ```bash
224
+ git clone https://github.com/Dao-AILab/flash-attention.git
225
+ cd flash-attention/hopper
226
+ python setup.py install
227
+ ```
228
+ This compiles against the active PyTorch's ABI. Takes ~15–25 min on H100 with 64 cores; one-time cost.
229
+
230
+ ### 4.3 FA3 page_size=1 slow path
231
+
232
+ - **Symptom**: FA3 GQA decode passes correctness but is slower than FlashInfer baseline at page_size=1
233
+ - **Root cause**: FA3 supports arbitrary page_size, but the TMA fast path requires `page_size % kBlockN == 0` (kBlockN typically 64 or 128). page_size=1 falls back to a `cp.async`-based slow path
234
+ - **Fix / workaround**: this is a known limitation; benchmark both ps=1 and ps=64 variants of the Definition and report both. For production deployment with FA3, prefer ps=64 if the workload allows.
235
+
236
+ ### 4.4 SM-arch wrapper hardcoded but runtime is different SM
237
+
238
+ - **Symptom**: Solution `RUNTIME_ERROR` only on B200 / SM100, works on H100
239
+ - **Root cause**: Wrapper hardcodes `arch_capability(9, 0)` or builds a Triton kernel without `tl.constexpr` arch dispatch
240
+ - **Fix**:
241
+ - In `spec.target_hardware`, include only the GPUs you actually verified
242
+ - If wrapping a Triton kernel, ensure all `triton.autotune` configs cover the target archs; or use `triton.heuristics`
243
+ - For CUDA: build with `-gencode arch=compute_90,code=sm_90 -gencode arch=compute_100,code=sm_100`
skills/add-flashinfer-solution/templates/dense_baseline_main.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Template A: Dense Baseline Wrapper
3
+ ==================================
4
+
5
+ Use this template when wrapping a generic dense attention impl (PyTorch SDPA,
6
+ cuDNN frontend, etc.) as a reference baseline Solution. Demonstrates:
7
+
8
+ * paged KV cache → contiguous batch (per-sequence index lookup)
9
+ * GQA expansion (replicate kv heads to query heads via repeat_interleave)
10
+ * sm_scale forwarding
11
+ * 3-D Q tensor (FlashInfer convention) — no S=1 unsqueeze needed
12
+ * No LSE output (this template is decode-only, no LSE)
13
+
14
+ Target Definition example: gqa_paged_decode_h32_kv8_d128_ps1
15
+ inputs: q [B, H_q, D], k_cache [P, ps, H_kv, D], v_cache [P, ps, H_kv, D],
16
+ kv_indptr [B+1], kv_indices [num_kv_indices], sm_scale (scalar)
17
+ outputs: output [B, H_q, D]
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import torch
22
+ import torch.nn.functional as F
23
+
24
+
25
+ def run(
26
+ q, # [B, H_q, D] bfloat16
27
+ k_cache, # [num_pages, page_size, H_kv, D] bfloat16
28
+ v_cache, # [num_pages, page_size, H_kv, D] bfloat16
29
+ kv_indptr, # [B+1] int32 — flat index into kv_indices
30
+ kv_indices, # [num_kv_indices] int32 — physical page numbers
31
+ sm_scale, # scalar float32
32
+ ):
33
+ B, H_q, D = q.shape
34
+ _, page_size, H_kv, _ = k_cache.shape
35
+ assert H_q % H_kv == 0, f"GQA: H_q ({H_q}) must be multiple of H_kv ({H_kv})"
36
+ G = H_q // H_kv # group size
37
+
38
+ # --- 1. Paged → contiguous: gather pages per batch and concat ---
39
+ # SDPA wants dense [B, H, S, D]; we build it from the paged store.
40
+ # No batching of variable-length sequences is supported by SDPA, so we
41
+ # process each batch row separately and pad to max length, OR we loop.
42
+ # Looping is simplest for a baseline:
43
+ outs = []
44
+ for b in range(B):
45
+ s_start = kv_indptr[b].item()
46
+ s_end = kv_indptr[b + 1].item()
47
+ seq_pages = kv_indices[s_start:s_end] # [n_pages_b]
48
+
49
+ # Gather pages → [n_pages_b * page_size, H_kv, D]
50
+ k_b = k_cache[seq_pages].reshape(-1, H_kv, D) # [S_b, H_kv, D]
51
+ v_b = v_cache[seq_pages].reshape(-1, H_kv, D)
52
+
53
+ # GQA expand: [S_b, H_kv, D] → [S_b, H_q, D]
54
+ k_b = k_b.repeat_interleave(G, dim=1)
55
+ v_b = v_b.repeat_interleave(G, dim=1)
56
+
57
+ # Reshape for SDPA: [B=1, H, S, D]
58
+ q_b = q[b : b + 1].unsqueeze(2) # [1, H_q, 1, D]
59
+ k_b = k_b.permute(1, 0, 2).unsqueeze(0) # [1, H_q, S_b, D]
60
+ v_b = v_b.permute(1, 0, 2).unsqueeze(0) # [1, H_q, S_b, D]
61
+
62
+ # --- 2. SDPA call (decode = causal mask is irrelevant since we have S_kv >> S_q=1) ---
63
+ out_b = F.scaled_dot_product_attention(
64
+ q_b, k_b, v_b,
65
+ attn_mask=None,
66
+ dropout_p=0.0,
67
+ is_causal=False,
68
+ scale=float(sm_scale), # ← MUST pass; SDPA defaults to 1/sqrt(d)
69
+ ) # [1, H_q, 1, D]
70
+
71
+ outs.append(out_b.squeeze(2).squeeze(0)) # [H_q, D]
72
+
73
+ output = torch.stack(outs, dim=0) # [B, H_q, D]
74
+ return output
75
+
76
+
77
+ # Notes on adapting this template:
78
+ #
79
+ # * For GQA paged PREFILL (instead of decode):
80
+ # - Q is [total_q, H_q, D] (ragged), or [B, S_q, H_q, D] (paged); check
81
+ # the Definition `inputs[0].shape`.
82
+ # - Apply causal mask: `is_causal=True` in F.scaled_dot_product_attention,
83
+ # or build a custom mask if the def specifies one.
84
+ #
85
+ # * For MLA paged decode (no head dim in cache):
86
+ # - cache layout is [P, ps, ckv_dim] + [P, ps, kpe_dim], not [P, ps, H, D]
87
+ # - Q has 2 components: q_nope [B, H, ckv_dim] and q_pe [B, H, kpe_dim]
88
+ # - Reference pseudo-code: out = softmax(q_nope @ k_nope^T / sqrt(d)) @ v
89
+ # + softmax(q_pe @ k_pe^T / sqrt(d)) @ v
90
+ # (Read Definition.reference.code for exact formula.)
91
+ #
92
+ # * If the def expects an LSE output:
93
+ # - SDPA does not return LSE; switch to FA / cuDNN / manual softmax + log
94
+ # - Remember LSE base-2: lse_b2 = lse_natural / math.log(2)
skills/add-flashinfer-solution/templates/dense_baseline_solution.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "sdpa_paged_decode_v1",
3
+ "definition": "gqa_paged_decode_h32_kv8_d128_ps1",
4
+ "author": "<your-author-tag>",
5
+ "spec": {
6
+ "language": "python",
7
+ "target_hardware": ["NVIDIA H100", "NVIDIA H200", "NVIDIA B200", "NVIDIA L40", "NVIDIA A100"],
8
+ "entry_point": "main.py::run",
9
+ "dependencies": [],
10
+ "destination_passing_style": false
11
+ },
12
+ "sources": [
13
+ {
14
+ "path": "main.py",
15
+ "content": "<replace with full text of templates/dense_baseline_main.py, JSON-escaped (use python: json.dumps(open('main.py').read()))>"
16
+ }
17
+ ]
18
+ }
skills/add-flashinfer-solution/templates/linear_attention_main.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Template B: External Python Lib Wrapper (FLA-style linear attention)
3
+ ====================================================================
4
+
5
+ Use this template when wrapping a pip-installable third-party Python lib
6
+ (`flash-linear-attention` aka `fla-core`, `flash-attn`, `xformers`, etc.) as
7
+ a Solution. Demonstrates:
8
+
9
+ * Calling a third-party op via Python API
10
+ * Pre-activations the lib expects (e.g. sigmoid for beta gating)
11
+ * Fused-mode flags that must be set explicitly (e.g. use_gate_in_kernel)
12
+ * Layout flags (k-first vs k-last)
13
+ * Recurrent state input/output handling
14
+
15
+ Target Definition example: gdn_decode_qk4_v8_d128_k_last
16
+ inputs: q [B, T=1, HQ=4, K=128], k [B, T=1, HQ=4, K=128], v [B, T=1, HV=8, V=128],
17
+ state [B, HV, V, K] (k-last layout!), A_log [HV], a [B, T=1, HV],
18
+ dt_bias [HV], b [B, T=1, HV], scale (scalar)
19
+ outputs: output [B, T=1, HV, V], new_state [B, HV, V, K]
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import torch
24
+
25
+ # fla-core comes from: pip install fla-core
26
+ from fla.ops.gated_delta_rule import fused_recurrent_gated_delta_rule
27
+
28
+
29
+ def run(
30
+ q, # [B, T, H_q, K]
31
+ k, # [B, T, H_q, K]
32
+ v, # [B, T, H_v, V]
33
+ state, # [B, H_v, V, K] ← k-last layout
34
+ A_log, # [H_v]
35
+ a, # [B, T, H_v]
36
+ dt_bias, # [H_v]
37
+ b, # [B, T, H_v]
38
+ scale, # scalar float32
39
+ ):
40
+ # --- 1. Pre-compute beta = sigmoid(b) (FLA's op does NOT do this internally) ---
41
+ beta = torch.sigmoid(b)
42
+
43
+ # --- 2. Call the FLA op with explicit fused-mode flags ---
44
+ output, new_state = fused_recurrent_gated_delta_rule(
45
+ q, k, v,
46
+ state, # initial state, in-place updated by op
47
+ g=a, A_log=A_log, # gating raw inputs (NOT pre-applied)
48
+ dt_bias=dt_bias,
49
+ beta=beta,
50
+ scale=float(scale),
51
+
52
+ # ↓ All four flags below MUST be set explicitly for the standard def:
53
+ use_gate_in_kernel=True, # let FLA fuse g_eff = exp(-exp(A_log)*softplus(g+dt_bias))
54
+ use_qk_l2norm_in_kernel=True, # FLA does the qk l2norm; do NOT pre-norm in this wrapper
55
+ transpose_state_layout=True, # def uses k-last layout; FLA's default is k-first
56
+ )
57
+
58
+ # output: [B, T, H_v, V]
59
+ # new_state: [B, H_v, V, K] (k-last, in-place modified)
60
+ return output, new_state
61
+
62
+
63
+ # Notes on adapting this template to other linear-attention variants:
64
+ #
65
+ # * For Mamba2 SSU (selective state update): use `fla.layers.mamba2`, but FLA
66
+ # delegates Mamba2 to upstream `mamba_ssm`. Install both: `pip install mamba-ssm fla-core`
67
+ #
68
+ # * For RetNet, GLA, RWKV4/6/7: use the corresponding op under `fla.ops.<name>`,
69
+ # e.g. `fla.ops.rwkv7.fused_recurrent_rwkv7`. Each variant has its own gating
70
+ # semantics; consult the FLA docs.
71
+ #
72
+ # * For DeltaNet (non-gated): use `fla.ops.delta_rule.fused_recurrent_delta_rule`,
73
+ # drop the `beta` and `g` / `A_log` / `dt_bias` args.
74
+ #
75
+ # * For PREFILL (T > 1): switch to `fla.ops.gated_delta_rule.chunk_gated_delta_rule`
76
+ # instead of `fused_recurrent_*`. The chunk variant is faster for long sequences.
77
+ #
78
+ # * For MTP (multi-token prediction): pass `cu_seqlens` to handle variable-length;
79
+ # note FLA does not have a dedicated MTP entry, but vLLM's fork adds
80
+ # `num_accepted_tokens` and `ssm_state_indices` parameters for spec decode.
81
+ #
82
+ # Common mistakes:
83
+ # * Forgetting `transpose_state_layout=True` → state values silently corrupted
84
+ # * Forgetting `use_gate_in_kernel=True` → gating not applied, output drifts
85
+ # * Pre-applying L2 norm in wrapper while also setting `use_qk_l2norm_in_kernel=True`
86
+ # → output magnitude is half of reference
skills/add-flashinfer-solution/templates/linear_attention_solution.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "fla_gdn_decode_v1",
3
+ "definition": "gdn_decode_qk4_v8_d128_k_last",
4
+ "author": "<your-author-tag>",
5
+ "spec": {
6
+ "language": "python",
7
+ "target_hardware": ["NVIDIA H100", "NVIDIA H200", "NVIDIA B200"],
8
+ "entry_point": "main.py::run",
9
+ "dependencies": ["fla-core>=0.5.0"],
10
+ "destination_passing_style": false
11
+ },
12
+ "sources": [
13
+ {
14
+ "path": "main.py",
15
+ "content": "<replace with full text of templates/linear_attention_main.py, JSON-escaped>"
16
+ }
17
+ ]
18
+ }
skills/add-flashinfer-solution/templates/vendored_kernel_main.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Template C: Vendored Kernel Wrapper (SGLang-style MLA decode)
3
+ =============================================================
4
+
5
+ Use this template when bringing in a Triton (or CUDA) kernel from another
6
+ project (SGLang / vLLM / private) WITHOUT depending on the upstream package.
7
+ The kernel source is co-located in the Solution sources.
8
+
9
+ Demonstrates:
10
+
11
+ * Vendored module import (sys.path manipulation for runner-extracted dirs)
12
+ * Workspace caching (avoid re-allocating per call)
13
+ * Split-K + LSE reduction (typical MLA decode pattern)
14
+ * MLA-specific tensor fusion (ckv + kpe → fused k buffer)
15
+ * LSE base conversion (natural-log → base-2)
16
+
17
+ Target Definition example: mla_paged_decode_h16_ckv512_kpe64_ps1
18
+ inputs: q_nope [B, H=16, ckv_dim=512], q_pe [B, H=16, kpe_dim=64],
19
+ ckv_cache [P, ps=1, 512], kpe_cache [P, ps=1, 64],
20
+ kv_indptr [B+1], kv_indices [num_kv_indices], sm_scale (scalar)
21
+ outputs: output [B, H=16, ckv_dim=512], lse [B, H=16] (base-2)
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import math
26
+ import os
27
+ import sys
28
+ from typing import Tuple
29
+
30
+ import torch
31
+
32
+ # --- Vendored module loading ---
33
+ # When the runner extracts this Solution's `sources` to a temp dir, that dir
34
+ # is NOT on sys.path automatically. Insert it so we can import sibling files.
35
+ _HERE = os.path.dirname(os.path.abspath(__file__))
36
+ if _HERE not in sys.path:
37
+ sys.path.insert(0, _HERE)
38
+
39
+ from sglang_decode import decode_attention_fwd_grouped_split_k_lse # noqa: E402
40
+
41
+ # --- Per-process state (workspace cache + constants) ---
42
+ _MAX_KV_SPLITS = 8
43
+ _MIN_BLOCK_KV = 64
44
+ _LOG2 = math.log(2.0)
45
+ _ws_cache: dict = {}
46
+
47
+
48
+ def _get_workspace(B: int, H: int, V: int, device, dtype) -> dict:
49
+ """Cache pre-allocated work tensors keyed on (B, H, V, device, dtype)."""
50
+ key = (B, H, V, str(device), dtype)
51
+ ws = _ws_cache.get(key)
52
+ if ws is None:
53
+ ws = {
54
+ "q_fused": torch.empty((B, H, V + 64), dtype=dtype, device=device),
55
+ "attn_logits": torch.empty((B, H, _MAX_KV_SPLITS, V), dtype=torch.float32, device=device),
56
+ "attn_lse": torch.empty((B, H, _MAX_KV_SPLITS), dtype=torch.float32, device=device),
57
+ "num_kv_splits": torch.empty((B,), dtype=torch.int32, device=device),
58
+ }
59
+ _ws_cache[key] = ws
60
+ return ws
61
+
62
+
63
+ def run(
64
+ q_nope, # [B, H, ckv_dim]
65
+ q_pe, # [B, H, kpe_dim]
66
+ ckv_cache, # [num_pages, page_size, ckv_dim]
67
+ kpe_cache, # [num_pages, page_size, kpe_dim]
68
+ kv_indptr, # [B+1]
69
+ kv_indices, # [num_kv_indices]
70
+ sm_scale, # scalar
71
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
72
+ B, H, ckv_dim = q_nope.shape
73
+ kpe_dim = q_pe.shape[-1]
74
+ assert ckv_dim == 512 and kpe_dim == 64, "MLA decode template assumes ckv=512, kpe=64"
75
+
76
+ device = q_nope.device
77
+ dtype = q_nope.dtype
78
+ ws = _get_workspace(B, H, ckv_dim, device, dtype)
79
+
80
+ # --- Fuse Q ---
81
+ # MLA needs Q to be a single [B, H, ckv+kpe] tensor; we concat once.
82
+ ws["q_fused"][:, :, :ckv_dim].copy_(q_nope)
83
+ ws["q_fused"][:, :, ckv_dim:].copy_(q_pe)
84
+
85
+ # --- Determine kv_splits per batch ---
86
+ # SGLang uses a heuristic: split count grows with KV length; capped at MAX.
87
+ seq_lens = kv_indptr[1:] - kv_indptr[:-1] # [B]
88
+ ws["num_kv_splits"].copy_((seq_lens.float() / _MIN_BLOCK_KV).clamp(min=1, max=_MAX_KV_SPLITS).int())
89
+
90
+ # --- Output buffer ---
91
+ output = torch.empty((B, H, ckv_dim), dtype=dtype, device=device)
92
+
93
+ # --- Launch the vendored kernel ---
94
+ # Note: kernel uses ckv_cache as the V buffer (zero-copy, MLA's compressed-V property).
95
+ decode_attention_fwd_grouped_split_k_lse(
96
+ ws["q_fused"], # [B, H, ckv+kpe]
97
+ ckv_cache, # K (ckv) cache
98
+ ckv_cache, # V buffer = ckv (MLA compressed)
99
+ kpe_cache, # KPE component
100
+ output,
101
+ kv_indices, kv_indptr,
102
+ ws["num_kv_splits"], _MAX_KV_SPLITS,
103
+ ws["attn_logits"], ws["attn_lse"],
104
+ page_size=1,
105
+ sm_scale=float(sm_scale),
106
+ )
107
+
108
+ # --- Reduce per-split LSE to final LSE, in base-2 (FlashInfer convention) ---
109
+ # `attn_lse` stores natural-log LSE per split; reduce + convert.
110
+ lse_natural_per_split = ws["attn_lse"] # [B, H, splits], natural log
111
+ # logsumexp across split dim:
112
+ lse_natural = torch.logsumexp(lse_natural_per_split, dim=2) # [B, H], natural log
113
+ # Convert to base-2:
114
+ lse_b2 = lse_natural / _LOG2 # [B, H], base-2
115
+
116
+ return output, lse_b2
117
+
118
+
119
+ # Notes on adapting this template:
120
+ #
121
+ # * For NON-MLA vendored kernels: drop the q_nope / q_pe fusion, keep the
122
+ # workspace caching pattern and split-K LSE reduction (most modern decode
123
+ # kernels use split-K).
124
+ #
125
+ # * If the vendored kernel returns base-2 LSE already, skip the `/ _LOG2` step.
126
+ #
127
+ # * If the kernel does not produce LSE, change the function signature to
128
+ # return only output. (Check Definition.outputs to confirm.)
129
+ #
130
+ # * For multi-file vendored sources: list every file in solution.json
131
+ # "sources"; the runner unpacks all of them to the same temp dir.
132
+ #
133
+ # * For CUDA kernels (vs Triton): vendor a pre-built .so file or compile at
134
+ # import time via cppimport / torch.utils.cpp_extension. Avoid blocking
135
+ # in run(); compile in module load time.
136
+ #
137
+ # * The `_ws_cache` global persists across run() calls within one process,
138
+ # speeding up repeated benchmarks. Be careful: in multi-process testing
139
+ # each worker has its own cache (which is what you want).
skills/add-flashinfer-solution/templates/vendored_kernel_solution.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "sglang_mla_decode_v1",
3
+ "definition": "mla_paged_decode_h16_ckv512_kpe64_ps1",
4
+ "author": "<your-author-tag>",
5
+ "spec": {
6
+ "language": "python",
7
+ "target_hardware": ["NVIDIA H100", "NVIDIA H200", "NVIDIA B200"],
8
+ "entry_point": "main.py::run",
9
+ "dependencies": [],
10
+ "destination_passing_style": false
11
+ },
12
+ "sources": [
13
+ {
14
+ "path": "main.py",
15
+ "content": "<full content of templates/vendored_kernel_main.py>"
16
+ },
17
+ {
18
+ "path": "sglang_decode.py",
19
+ "content": "<full content of the vendored Triton kernel — copy from upstream sglang/python/sglang/srt/layers/attention/triton_ops/decode_attention.py and trim to just the function you need>"
20
+ }
21
+ ]
22
+ }