add add-flashinfer-solution skill (end-to-end Solution authoring)

#6
skills/add-flashinfer-solution/PR_DESCRIPTION.md ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PR: add-flashinfer-solution skill
2
+
3
+ > Copy-paste artifacts for opening the PR upstream against
4
+ > https://github.com/flashinfer-ai/flashinfer-bench
5
+
6
+ ---
7
+
8
+ ## Suggested branch name
9
+
10
+ ```
11
+ yyang/add-solution-skill
12
+ ```
13
+
14
+ (or `<your-handle>/add-solution-skill` matching your contributor pattern)
15
+
16
+ ---
17
+
18
+ ## Suggested PR title
19
+
20
+ ```
21
+ feat: add add-flashinfer-solution skill (end-to-end Solution authoring + benchmarking + visualization)
22
+ ```
23
+
24
+ Per `CONTRIBUTING.md` `<type>: <brief description>`:
25
+ - `feat:` — adds a new agent capability (parallel to existing `onboard-model`, `extract-kernel-definitions`, `collect-workloads`)
26
+ - alternative: `docs:` — if reviewers prefer skills be classified as docs
27
+
28
+ ---
29
+
30
+ ## Suggested commit message (single squashed commit)
31
+
32
+ ```
33
+ feat: add add-flashinfer-solution skill (end-to-end Solution authoring)
34
+
35
+ Adds a new agent skill under .claude/skills/add-flashinfer-solution/ that
36
+ covers the Solution-side workflow: pick a Definition → wrap a kernel →
37
+ write Solution JSON → run flashinfer-bench → inspect traces → visualize.
38
+
39
+ This complements the existing skill suite, which covers Definition extraction
40
+ (extract-kernel-definitions), workload capture (collect-workloads), and
41
+ end-to-end model onboarding (onboard-model). Solution authoring previously
42
+ had no skill-level documentation; this fills that gap.
43
+
44
+ Skill contents:
45
+ SKILL.md 7-step end-to-end workflow + gotchas + quick-run script
46
+ reference/
47
+ definition_schema.md Full Definition JSON schema reference
48
+ solution_schema.md Full Solution JSON schema reference
49
+ wrapper_gotchas.md 17+ catalogued failure modes with diagnostics
50
+ visualization.md Local web UI + public site + SSH forwarding
51
+ templates/
52
+ dense_baseline_* PyTorch SDPA-style reference baseline
53
+ linear_attention_* External Python lib wrapper (FLA / fla-core)
54
+ vendored_kernel_* Vendored Triton / CUDA kernel (SGLang-style)
55
+
56
+ Verified end-to-end on H100 PCIe and B200 with three reference Solutions:
57
+ - sdpa_paged_decode_v1 (gqa_paged_decode_h32_kv8_d128_ps1)
58
+ - fla_gdn_decode_v1 (gdn_decode_qk4_v8_d128_k_last)
59
+ - sglang_mla_decode_v1 (mla_paged_decode_h16_ckv512_kpe64_ps1)
60
+
61
+ All three were verified using the workflow documented in SKILL.md
62
+ Section 3.3 + Step 5.1a: `crun -img nvcr.io/nvidia/pytorch:24.10-py3 -r /tmp
63
+ <script>.sh` with per-run pip-install into /tmp/pip-pkgs (no NGC API key
64
+ required; no custom container image; ~5 min pip install per invocation).
65
+ Pre-built `.sqsh` images were considered as an optimization but rejected
66
+ because the build path is blocked by computelab front-end constraints
67
+ (no user docker daemon; cgroup namespace mismatch under VS Code SSH session;
68
+ NGC private blob auth). SKILL.md documents this trade-off explicitly.
69
+
70
+ Note on layout: existing skills are single SKILL.md files. This skill
71
+ introduces sub-directories (reference/, templates/) because the content
72
+ includes schema references and runnable Python / JSON templates that are
73
+ more discoverable as separate artifacts than embedded in a long monolith.
74
+ Open to flattening if upstream prefers strict one-file convention.
75
+ ```
76
+
77
+ ---
78
+
79
+ ## PR description (paste into GitHub)
80
+
81
+ ```markdown
82
+ ## Summary
83
+
84
+ Adds a new agent skill `add-flashinfer-solution` under `.claude/skills/`
85
+ covering the **Solution authoring side** of the flashinfer-bench workflow:
86
+
87
+ > pick a Definition → wrap a kernel → write Solution JSON → run benchmark
88
+ > → inspect traces → visualize
89
+
90
+ The existing skill suite covers the **Definition / Workload / model side**
91
+ (`extract-kernel-definitions`, `collect-workloads`, `onboard-model`,
92
+ `add-reference-tests`, `track-models`, `clone-repos`,
93
+ `collect-workloads-bench`). Solution authoring had no skill-level
94
+ documentation; this PR fills that gap.
95
+
96
+ ## Motivation
97
+
98
+ Three real Solutions were authored end-to-end during this work:
99
+
100
+ | Solution | Definition | Verified on |
101
+ |---|---|---|
102
+ | `sdpa_paged_decode_v1` | `gqa_paged_decode_h32_kv8_d128_ps1` | H100 PCIe |
103
+ | `fla_gdn_decode_v1` | `gdn_decode_qk4_v8_d128_k_last` | H100 PCIe |
104
+ | `sglang_mla_decode_v1` | `mla_paged_decode_h16_ckv512_kpe64_ps1` | H100 PCIe + B200 |
105
+
106
+ Recurring patterns surfaced — KV-cache layout conversion, LSE base-2 vs
107
+ base-e, GQA `H_kv → H_q` expansion, FLA's `transpose_state_layout` flag,
108
+ vendored-Triton sys.path, NGC PyTorch + CuTe DSL ABI mismatch — were
109
+ costly to re-derive each time. This skill captures them as a reusable
110
+ playbook so subsequent Solution contributors don't relive the debug loops.
111
+
112
+ ## What's added
113
+
114
+ ```
115
+ .claude/skills/add-flashinfer-solution/
116
+ ├── SKILL.md 7-step workflow + gotchas
117
+ ├── reference/
118
+ │ ├── definition_schema.md Definition JSON full schema
119
+ │ ├── solution_schema.md Solution JSON full schema
120
+ │ ├── wrapper_gotchas.md 17+ failure modes with diagnostics
121
+ │ └── visualization.md Web UI / public site / SSH forwarding
122
+ └── templates/
123
+ ├── dense_baseline_main.py + .json PyTorch SDPA-style baseline
124
+ ├── linear_attention_main.py + .json External lib wrapper (FLA)
125
+ └── vendored_kernel_main.py + .json Vendored Triton kernel (SGLang-style)
126
+ ```
127
+
128
+ ### Verified environment
129
+
130
+ All three reference Solutions were verified using the workflow in
131
+ **SKILL.md Section 3.3 + Step 5.1a**:
132
+
133
+ ```bash
134
+ crun -q 'gpu.chip=gh100 and cpu.arch=x86_64' --gpus=1 -C \
135
+ -img nvcr.io/nvidia/pytorch:24.10-py3 \
136
+ -r /tmp <user_script>.sh
137
+ ```
138
+
139
+ Inside `<user_script>.sh`, the pinned dependency stack:
140
+
141
+ ```bash
142
+ pip install --target /tmp/pip-pkgs --no-cache-dir \
143
+ flashinfer-python==0.6.9 \
144
+ "flashinfer-bench>=0.6.0,<0.7" \
145
+ "flash-linear-attention>=0.5.0" \
146
+ "nvidia-cutlass-dsl[cu13]" \
147
+ cuda-python safetensors huggingface-hub
148
+ ```
149
+
150
+ No NGC API key required (crun authenticates against NGC via the compute
151
+ node's docker daemon credentials), no custom container image needed.
152
+ Per-invocation cost: ~5 min pip install. SKILL.md explains why a pre-built
153
+ `.sqsh` was considered as an optimization and why it is not included
154
+ (computelab front-end build constraints).
155
+
156
+ ## Layout note for reviewers
157
+
158
+ Existing skills are single-file `SKILL.md`. This one uses subdirectories
159
+ (`reference/`, `templates/`) because:
160
+
161
+ 1. Schema reference docs (~200 lines each) are more useful as standalone
162
+ linkable artifacts than as inline sections of a longer SKILL.md
163
+ 2. Wrapper templates need to be **runnable** as `.py` / `.json` for the
164
+ "copy → modify" use case, not as inline code blocks
165
+
166
+ Total content is ~1500 lines distributed across 11 purposeful files. Happy
167
+ to flatten into a single SKILL.md if maintainers prefer strict one-file
168
+ convention; in that case the wrapper templates would still need to live as
169
+ separate executable artifacts somewhere.
170
+
171
+ ## How to test
172
+
173
+ ### 1. Skill metadata sanity
174
+ ```bash
175
+ head -4 .claude/skills/add-flashinfer-solution/SKILL.md
176
+ # Expect valid YAML frontmatter with name + description
177
+ ```
178
+
179
+ ### 2. End-to-end Solution run on a computelab GPU node
180
+ Follow SKILL.md Section 3.3 + Step 5.1a to author a trivial Solution
181
+ against any existing Definition (e.g. `gqa_paged_decode_h32_kv8_d128_ps1`)
182
+ and confirm `flashinfer-bench run --solutions <yours>` produces PASSED
183
+ traces.
184
+
185
+ ### 3. Lint / format
186
+ No code changes; only markdown + Python + JSON templates.
187
+
188
+ ## Checklist
189
+
190
+ - [x] PR title follows `<type>: <description>` convention
191
+ - [x] Skill metadata (`name`, `description`) follows existing skill pattern
192
+ - [x] No changes to `flashinfer_bench/` Python package
193
+ - [x] No changes to existing skills (additive only)
194
+ - [x] No CI / build system changes required
195
+ - [x] CONTRIBUTING.md workflow followed (fork → branch → PR)
196
+ - [ ] Reviewers comfortable with subdir layout (else willing to flatten)
197
+
198
+ ## Related
199
+
200
+ - Existing skills suite: see `.claude/skills/` and CLAUDE.md
201
+ - Last skill-related PR: #384 (docs: add skill summaries and
202
+ cross-references)
203
+ - Prior skill-restructure PR: #224 (referenced in #384)
204
+ ```
205
+
206
+ ---
207
+
208
+ ## How to actually open the PR
209
+
210
+ ```bash
211
+ # 0. set git identity if not yet (replace with yours)
212
+ cd /home/scratch.yuny_wwfo/kernel_arena/flashinfer-bench
213
+ git config user.name "Your Name"
214
+ git config user.email "your@email"
215
+
216
+ # 1. fork on GitHub, then add as an additional remote
217
+ git remote add fork https://github.com/<your-gh-handle>/flashinfer-bench.git
218
+
219
+ # 2. create a clean branch from current main
220
+ git fetch origin
221
+ git checkout -b yyang/add-solution-skill origin/main
222
+
223
+ # 3. copy the skill in place
224
+ mkdir -p .claude/skills/add-flashinfer-solution
225
+ cp -r /home/yuny/kernel_arena/skills/add-flashinfer-solution/* \
226
+ .claude/skills/add-flashinfer-solution/
227
+ # NB: PR_DESCRIPTION.md is the source for the PR body itself — don't ship
228
+ # it as part of the skill. Remove it from the staged copy:
229
+ rm .claude/skills/add-flashinfer-solution/PR_DESCRIPTION.md
230
+
231
+ # 4. confirm only the skill files are staged (the working tree currently has
232
+ # unrelated 'deleted' entries from the flashinfer_trace symlink — DO NOT
233
+ # stage those)
234
+ git add .claude/skills/add-flashinfer-solution
235
+ git status
236
+
237
+ # 5. commit (paste the suggested commit message above)
238
+ git commit # then paste the commit message body in the editor
239
+
240
+ # 6. push to your fork
241
+ git push -u fork yyang/add-solution-skill
242
+
243
+ # 7. open PR via gh CLI (or GitHub web)
244
+ gh pr create \
245
+ --repo flashinfer-ai/flashinfer-bench \
246
+ --base main \
247
+ --head <your-gh-handle>:yyang/add-solution-skill \
248
+ --title "feat: add add-flashinfer-solution skill (end-to-end Solution authoring + benchmarking + visualization)" \
249
+ --body-file <(sed -n '/^## PR description/,/^---$/p' /home/yuny/kernel_arena/skills/add-flashinfer-solution/PR_DESCRIPTION.md | sed -n '/```markdown/,/^```$/p' | grep -v '^```')
250
+ ```
251
+
252
+ ---
skills/add-flashinfer-solution/SKILL.md ADDED
@@ -0,0 +1,702 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 — verified workflow on NVIDIA computelab / SLURM clusters
86
+
87
+ This is the path actually used to verify the three reference Solutions
88
+ end-to-end. Zero NGC API key setup, zero docker daemon, zero custom
89
+ container image. Each `crun` invocation pulls the NGC base on the compute
90
+ node (which has cluster-configured NGC credentials), and the user script
91
+ installs pip dependencies into `/tmp/pip-pkgs` inside that container.
92
+
93
+ Per-run cost: ~5 min pip install at start of every `crun` invocation. The
94
+ torch 2.5 → 2.11 upgrade triggered by `fla-core` is the dominant time.
95
+
96
+ ```bash
97
+ crun -q 'gpu.chip=gh100 and cpu.arch=x86_64' --gpus=1 -C \
98
+ -img nvcr.io/nvidia/pytorch:24.10-py3 \
99
+ -r /tmp <your_script>.sh
100
+ ```
101
+
102
+ Inside `<your_script>.sh`, install the exact stack used to verify the
103
+ reference Solutions:
104
+
105
+ ```bash
106
+ PIP_TARGET=/tmp/pip-pkgs
107
+ mkdir -p "$PIP_TARGET"
108
+ export PYTHONPATH="$PIP_TARGET:$PYTHONPATH"
109
+ export PATH="$PIP_TARGET/bin:$PATH"
110
+
111
+ pip install --target "$PIP_TARGET" --no-cache-dir \
112
+ flashinfer-python==0.6.9 \
113
+ "flashinfer-bench>=0.6.0,<0.7" \
114
+ "flash-linear-attention>=0.5.0" \
115
+ "nvidia-cutlass-dsl[cu13]" \
116
+ cuda-python \
117
+ safetensors huggingface-hub
118
+ ```
119
+
120
+ **Version pin rationale**:
121
+ - `flashinfer-python==0.6.9` — pinned for CuTe DSL GDN kernel ABI compatibility; do not drop the pin
122
+ - `flashinfer-bench<0.7` — paired with flashinfer-python 0.6.9
123
+ - `flash-linear-attention>=0.5.0` — only required if your wrapper uses FLA; safe to keep in the install list either way
124
+ - `nvidia-cutlass-dsl[cu13] + cuda-python` — CuTe DSL backend deps; required even if you only run FLA (FlashInfer GDN baseline pulls them in)
125
+
126
+ For wrappers that need additional libraries:
127
+ - **FA3**: add a source-build step inside the script (`cd /tmp && git clone https://github.com/Dao-AILab/flash-attention.git && cd flash-attention/hopper && python setup.py install`)
128
+ - **SGLang vendored kernel**: vendor the kernel file into your Solution's `sources/` — no pip install required
129
+
130
+ > **Why not a pre-built `.sqsh` / docker image to skip the 5-minute pip install?**
131
+ > Building a custom container in the computelab front-end environment is
132
+ > blocked by multiple constraints: no user-accessible docker daemon, no
133
+ > permission to `unshare --cgroup`, `enroot start` fails inside the
134
+ > front-end's VS Code SSH session cgroup namespace, and NGC private blob
135
+ > layers require an API key. The "pip install on every run" pattern adds
136
+ > ~5 min per invocation but needs zero setup and is what the three
137
+ > reference Solutions actually used.
138
+ >
139
+ > If your team will run benchmarks dozens of times against the same stack
140
+ > and the ~5 min adds up, the recommended path is to build a custom image
141
+ > on an **external** build host (a personal docker workstation, or a
142
+ > dedicated cluster build farm with sudo) and drop the resulting `.sqsh`
143
+ > at a shared scratch path. That work is out of scope for this skill.
144
+
145
+ ### 3.4 Clone the dataset
146
+ ```bash
147
+ cd /home/scratch.<user>/kernel_arena
148
+ git clone https://huggingface.co/datasets/flashinfer-ai/flashinfer-trace
149
+ cd flashinfer-trace
150
+ git-lfs install --local
151
+ # Don't pull all LFS yet — pull only the Workloads you need (Step 2)
152
+ ```
153
+
154
+ ### 3.5 (Optional) Clone the framework codebase for the local web UI
155
+ ```bash
156
+ git clone https://github.com/flashinfer-ai/flashinfer-bench.git
157
+ ```
158
+
159
+ ## 4. Workflow overview
160
+
161
+ ```
162
+ Step 1 ── Pick a Definition + audit existing solutions
163
+ Step 2 ── Pull workload LFS data (just for that Definition)
164
+ Step 3 ── Write wrapper (main.py)
165
+ Step 4 ── Write Solution JSON
166
+ Step 5 ── Run benchmark with `flashinfer-bench run`
167
+ Step 6 ── Inspect generated traces
168
+ Step 7 ── Visualize (web UI / public site)
169
+ ```
170
+
171
+ Estimated time for an experienced contributor:
172
+ - First time end-to-end: **half a day to a full day** (env setup dominates)
173
+ - Subsequent solutions on same env: **1–2 hours per Solution**
174
+
175
+ ---
176
+
177
+ ## Step 1 — Pick a Definition + audit existing solutions
178
+
179
+ ### 1.1 Find candidate Definition
180
+
181
+ Browse `flashinfer-trace/definitions/<op_type>/` and pick a JSON file. The filename matches the Definition `name`.
182
+
183
+ ```bash
184
+ ls /home/scratch.<user>/kernel_arena/flashinfer-trace/definitions/
185
+ # dsa_paged gdn gemm gqa_paged gqa_ragged mamba_ssu
186
+ # mla_paged mla_ragged moe rmsnorm rope sampling
187
+ ls /home/scratch.<user>/kernel_arena/flashinfer-trace/definitions/gqa_paged/
188
+ # gqa_paged_decode_h32_kv8_d128_ps1.json
189
+ # gqa_paged_decode_h32_kv8_d128_ps64.json
190
+ # ...
191
+ ```
192
+
193
+ ### 1.2 Read the Definition JSON
194
+
195
+ Field semantics → see [`reference/definition_schema.md`](reference/definition_schema.md). Key fields to confirm before writing the wrapper:
196
+
197
+ | Field | What to confirm |
198
+ |---|---|
199
+ | `axes` | Which dims are `const` (compile-time) vs `var` (runtime). Wrapper signature must accept all `var` axes |
200
+ | `inputs` | Tensor names + dtypes + shapes. Wrapper signature must match exactly |
201
+ | `outputs` | Whether output is allocated by wrapper (return) or pre-allocated (`destination_passing_style: true`) |
202
+ | `tags` | `fi_api:` tells you which FlashInfer API the Definition was modeled after — your Solution may want to follow the same contract |
203
+ | `reference.code` | The PyTorch reference implementation. Read it to understand semantics (sm_scale, masking, LSE base, etc.) |
204
+
205
+ ### 1.3 Audit existing solutions for that Definition
206
+
207
+ ```bash
208
+ DEF=mla_paged_decode_h16_ckv512_kpe64_ps1
209
+ OP=mla_paged
210
+ TRACE=/home/scratch.<user>/kernel_arena/flashinfer-trace
211
+ for author in baseline claude-opus-4-1-20250805 gemini-2.5-pro gpt-5-2025-08-07 gpt-o3; do
212
+ p="$TRACE/solutions/$author/$OP/$DEF"
213
+ if [ -d "$p" ]; then
214
+ echo "$author:"
215
+ ls "$p"
216
+ fi
217
+ done
218
+ ```
219
+
220
+ Why: read existing Solutions' `main.py` to understand:
221
+ - How they map `axes` / `inputs` to function arguments
222
+ - How they handle paged KV layout (flat indices vs 2D page table)
223
+ - How they convert LSE base, sm_scale, dtype
224
+ - Whether they pre-allocate output (`destination_passing_style`)
225
+
226
+ The `baseline/` solution (FlashInfer wrapper) is the ground-truth reference — match its function signature.
227
+
228
+ ---
229
+
230
+ ## Step 2 — Pull workload LFS data
231
+
232
+ Workload tensors live in `blob/workloads/<op_type>/<def_name>/<def_name>_<uuid>.safetensors`, stored as Git-LFS. Pull selectively to save disk:
233
+
234
+ ### 2.1 Pull all workloads for one Definition
235
+ ```bash
236
+ cd /home/scratch.<user>/kernel_arena/flashinfer-trace
237
+ DEF=mla_paged_decode_h16_ckv512_kpe64_ps1
238
+ OP=mla_paged
239
+ git-lfs pull --include="blob/workloads/$OP/$DEF/*"
240
+ ```
241
+
242
+ ### 2.2 Pull only N workloads (for quick iteration on a tight quota)
243
+
244
+ Each Workload UUID is one entry in `workloads/<op>/<def>.jsonl`. Use head to take the first N:
245
+
246
+ ```bash
247
+ WL_FILE=workloads/$OP/$DEF.jsonl
248
+ UUIDS=$(head -5 "$WL_FILE" | python3 -c "import json,sys; [print(json.loads(l)['uuid']) for l in sys.stdin]")
249
+ INCLUDES=""
250
+ for u in $UUIDS; do
251
+ INCLUDES="${INCLUDES}${INCLUDES:+,}blob/workloads/$OP/$DEF/${DEF}_${u}.safetensors"
252
+ done
253
+ git-lfs pull --include="$INCLUDES"
254
+ ```
255
+
256
+ ### 2.3 Temp-trim the workloads jsonl to N entries (so the runner only sees those N)
257
+ ```bash
258
+ WL_FILE=workloads/$OP/$DEF.jsonl
259
+ cp "$WL_FILE" "$WL_FILE.bak"
260
+ head -5 "$WL_FILE.bak" > "$WL_FILE"
261
+ # After your run, restore:
262
+ # mv "$WL_FILE.bak" "$WL_FILE"
263
+ ```
264
+
265
+ Tip: a `bash trap` cleanup line is the safest way to ensure the original jsonl is restored even on script failure.
266
+
267
+ ### 2.4 Verify workloads exist
268
+ ```bash
269
+ find blob/workloads/$OP/$DEF -name "*.safetensors" -size +1k | head -5
270
+ ```
271
+
272
+ ---
273
+
274
+ ## Step 3 — Write the wrapper (`main.py`)
275
+
276
+ The wrapper is a single Python file at:
277
+ ```
278
+ solutions/<author>/<op_type>/<def_name>/main.py
279
+ ```
280
+
281
+ ### 3.1 Wrapper signature contract
282
+
283
+ Function signature must match the Definition's `inputs` exactly:
284
+ - Each `inputs[].name` becomes a positional or keyword argument
285
+ - Each `axes[].name` (the `var` ones) is also passed
286
+ - Tensor dtypes / shapes match `inputs[].dtype` / `inputs[].shape`
287
+
288
+ Default entry point is `main.py::run`. Function returns the output tensor(s) in the order declared by `outputs[]`.
289
+
290
+ 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.
291
+
292
+ ### 3.2 Three wrapper patterns (templates)
293
+
294
+ Pick the template closest to your situation:
295
+
296
+ | Pattern | When to use | Template |
297
+ |---|---|---|
298
+ | **Dense baseline** | Wrapping a generic dense impl (PyTorch SDPA / cuDNN frontend) for reference | [`templates/dense_baseline_main.py`](templates/dense_baseline_main.py) |
299
+ | **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) |
300
+ | **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) |
301
+
302
+ ### 3.3 Writing checklist
303
+
304
+ - [ ] Function signature matches Definition `inputs` + `var` axes
305
+ - [ ] Output shape / dtype matches Definition `outputs`
306
+ - [ ] LSE (if produced) uses **base-2** convention (FlashInfer convention; convert from natural-log via `* (1.0 / math.log(2.0))`)
307
+ - [ ] `sm_scale` is taken from the input parameter, NOT recomputed as `1/sqrt(d)`
308
+ - [ ] Paged KV cache is read using the supplied `kv_indices` / `kv_indptr` flat layout (not assumed dense)
309
+ - [ ] GQA: kv heads broadcasted to query heads if the underlying lib expects MHA (`repeat_interleave(H_q // H_kv, dim=-2)`)
310
+ - [ ] Persistent state (e.g. recurrent kernels) returns the new state in the order Definition declares
311
+ - [ ] No global state mutation across batches (avoid using cached buffers keyed only on shape — also key on device + dtype)
312
+
313
+ See [`reference/wrapper_gotchas.md`](reference/wrapper_gotchas.md) for a full list of common pitfalls.
314
+
315
+ ---
316
+
317
+ ## Step 4 — Write the Solution JSON
318
+
319
+ Create `solutions/<author>/<op_type>/<def_name>/<solution_name>.json`:
320
+
321
+ ```json
322
+ {
323
+ "name": "my_solution_v1",
324
+ "definition": "mla_paged_decode_h16_ckv512_kpe64_ps1",
325
+ "author": "<your-author-tag>",
326
+ "spec": {
327
+ "language": "python",
328
+ "target_hardware": ["NVIDIA H100", "NVIDIA B200"],
329
+ "entry_point": "main.py::run",
330
+ "dependencies": [],
331
+ "destination_passing_style": false
332
+ },
333
+ "sources": [
334
+ {"path": "main.py", "content": "<full content of main.py>"}
335
+ ]
336
+ }
337
+ ```
338
+
339
+ ### 4.1 Field semantics
340
+
341
+ Full schema → [`reference/solution_schema.md`](reference/solution_schema.md). Quick reference:
342
+
343
+ | Field | Notes |
344
+ |---|---|
345
+ | `name` | Solution identifier. Convention: `<lib_or_method>_<op_type>_<variant_or_hash>`, e.g. `fa3_gqa_paged_decode_v1`, `sglang_mla_decode_v1` |
346
+ | `definition` | MUST exactly match the Definition `name` |
347
+ | `author` | Subdir name under `solutions/`. Pick a stable identifier for your team / lab (e.g. `acme-research`) |
348
+ | `spec.language` | `python` (most common) / `triton` / `cuda` / `tilelang` / `tvm_ffi` |
349
+ | `spec.target_hardware` | List of strings; framework checks current GPU is in this list before running |
350
+ | `spec.entry_point` | `<file>::<function>`; default is `main.py::run` |
351
+ | `spec.dependencies` | pip-installable packages required at runtime (e.g. `["flash-attn>=3.0.0", "fla-core"]`); leave `[]` if everything is vendored |
352
+ | `spec.destination_passing_style` | `true` if outputs are pre-allocated and passed in; `false` (default) if the entry function returns the outputs |
353
+ | `sources` | List of `{path, content}` dicts; include `main.py` plus any vendored `.py` / `.cu` / `.triton` files |
354
+
355
+ ### 4.2 Multi-file Solution
356
+
357
+ For vendored kernels or multi-module wrappers, list every file in `sources`:
358
+
359
+ ```json
360
+ "sources": [
361
+ {"path": "main.py", "content": "..."},
362
+ {"path": "vendored_kernel.py", "content": "..."},
363
+ {"path": "kernel.cu", "content": "..."}
364
+ ]
365
+ ```
366
+
367
+ Files are extracted to a temp dir at run time; relative imports work as expected.
368
+
369
+ ### 4.3 Tooling
370
+
371
+ `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.
372
+
373
+ ---
374
+
375
+ ## Step 5 — Run benchmark with `flashinfer-bench run`
376
+
377
+ ### 5.1 Bare `flashinfer-bench run` command (inside the container)
378
+
379
+ ```bash
380
+ cd /home/scratch.<user>/kernel_arena/flashinfer-trace
381
+
382
+ flashinfer-bench run \
383
+ --local . \
384
+ --definitions <def_name> \
385
+ --solutions <solution_name_1> [<solution_name_2> ...] \
386
+ --warmup-runs 5 \
387
+ --iterations 20 \
388
+ --num-trials 1 \
389
+ --timeout 600 \
390
+ --log-level INFO
391
+ ```
392
+
393
+ ### 5.1a Full `crun` invocation (computelab / SLURM cluster) — what to actually type
394
+
395
+ On computelab and similar clusters, wrap the command in a shell script and
396
+ launch via `crun`. The script reproduces the exact path used to verify the
397
+ three reference Solutions:
398
+
399
+ ```bash
400
+ #!/bin/bash
401
+ # my_run.sh
402
+ set -e
403
+ LOGFILE=/home/yuny/kernel_arena/results/my_run_$(date +%Y%m%d_%H%M%S).log
404
+ mkdir -p $(dirname $LOGFILE)
405
+ exec > >(tee -a "$LOGFILE") 2>&1
406
+
407
+ echo "=== HOST: $(hostname) TIME: $(date) ==="
408
+
409
+ # 1. Install dependency stack into ephemeral /tmp/pip-pkgs
410
+ PIP_TARGET=/tmp/pip-pkgs
411
+ mkdir -p $PIP_TARGET
412
+ pip install --target $PIP_TARGET --no-cache-dir \
413
+ flashinfer-python==0.6.9 \
414
+ "flashinfer-bench>=0.6.0,<0.7" \
415
+ "flash-linear-attention>=0.5.0" \
416
+ "nvidia-cutlass-dsl[cu13]" \
417
+ cuda-python \
418
+ safetensors huggingface-hub 2>&1 | tail -3
419
+ export PYTHONPATH=$PIP_TARGET:$PYTHONPATH
420
+ export PATH=$PIP_TARGET/bin:$PATH
421
+
422
+ # 2. (Optional) Deploy your solution into the dataset before running
423
+ DATASET=/home/scratch.yuny_wwfo/kernel_arena/flashinfer-trace
424
+ DST=$DATASET/solutions/<your-author>/<op_type>/<def_name>
425
+ mkdir -p $DST
426
+ cp /home/yuny/kernel_arena/solutions/<your-solution>/*.json $DST/
427
+ cp /home/yuny/kernel_arena/solutions/<your-solution>/main.py $DST/
428
+
429
+ # 3. Run the benchmark
430
+ cd $DATASET
431
+ flashinfer-bench run \
432
+ --local . \
433
+ --definitions <def_name> \
434
+ --solutions <your-solution-name> \
435
+ --warmup-runs 5 \
436
+ --iterations 20 \
437
+ --num-trials 1 \
438
+ --timeout 600 \
439
+ --log-level INFO
440
+ ```
441
+
442
+ Then submit:
443
+
444
+ ```bash
445
+ crun -q 'gpu.chip=gh100 and cpu.arch=x86_64' --gpus=1 -C \
446
+ -img nvcr.io/nvidia/pytorch:24.10-py3 \
447
+ -r /tmp /home/yuny/kernel_arena/scripts/my_run.sh
448
+ ```
449
+
450
+ GPU chip query examples:
451
+ - `gpu.chip=gh100` → H100 (PCIe / SXM)
452
+ - `gpu.chip=gb200` → B200
453
+ - `gpu.chip=ga100` → A100
454
+
455
+ ### 5.2 Key flags
456
+
457
+ | Flag | Meaning |
458
+ |---|---|
459
+ | `--local <path>` | Point to a local trace dataset clone (not HF) |
460
+ | `--definitions` | Whitelist Definitions to run (space-separated; can also pass `--definitions all`) |
461
+ | `--solutions` | Whitelist Solutions to run; `baseline` (FlashInfer wrapper) typically runs as the comparison reference automatically |
462
+ | `--warmup-runs` | Forward passes before timing (default 10) |
463
+ | `--iterations` | Forward passes for timing each trial |
464
+ | `--num-trials` | Repeat trials, take median (default 3) |
465
+ | `--timeout` | Per-(solution × workload) wall time, seconds |
466
+ | `--log-level` | `DEBUG` / `INFO` / `WARNING` / `ERROR` |
467
+ | `--no-save-results` | Don't write traces (only print summary). Omit to write traces |
468
+
469
+ ### 5.3 What happens
470
+
471
+ For each (Solution × Workload) pair the runner:
472
+ 1. Loads input tensors from the workload `safetensors`
473
+ 2. Builds a baseline output via Definition `reference.code` (PyTorch)
474
+ 3. Calls the Solution's `entry_point`
475
+ 4. Compares Solution output vs baseline (rtol=1e-2, atol=1e-2 by default → status PASSED / INCORRECT_NUMERICAL)
476
+ 5. Times `iterations` warmup + measured passes → reports latency, ref_latency, speedup
477
+
478
+ Result is a row in `traces/<author>/<op_type>/<def_name>.jsonl`.
479
+
480
+ ### 5.4 Status enum
481
+
482
+ | Status | Meaning |
483
+ |---|---|
484
+ | `PASSED` | Output within tolerance, latency measured |
485
+ | `INCORRECT_NUMERICAL` | rtol / atol exceeded |
486
+ | `RUNTIME_ERROR` | Exception during execution (true exception is hidden by worker isolation — see Common gotchas) |
487
+ | `TIMEOUT` | Exceeded `--timeout` |
488
+ | `SETUP_FAILED` | Failed to set up baseline / solution before measurement |
489
+
490
+ ---
491
+
492
+ ## Step 6 — Inspect generated traces
493
+
494
+ After `flashinfer-bench run`, check:
495
+
496
+ ```bash
497
+ TRACE=/home/scratch.<user>/kernel_arena/flashinfer-trace
498
+ find $TRACE/traces -name "*.jsonl" -newer $TRACE/run.log 2>/dev/null
499
+ # Or just list everything:
500
+ find $TRACE/traces -name "*<def_name>*.jsonl" -size +100c
501
+ ```
502
+
503
+ ### 6.1 Per-trace inspection
504
+ ```bash
505
+ head -1 $TRACE/traces/<author>/<op>/<def>.jsonl | python3 -m json.tool | head -40
506
+ ```
507
+
508
+ Key fields per trace row:
509
+ - `definition`, `solution`, `workload.uuid`
510
+ - `evaluation.status` (PASSED / RUNTIME_ERROR / …)
511
+ - `evaluation.environment.hardware` (e.g. `NVIDIA H100 PCIe`)
512
+ - `evaluation.performance.speedup_factor`, `latency_ms`, `reference_latency_ms`
513
+ - `evaluation.correctness.max_absolute_error`, `max_relative_error`
514
+
515
+ ### 6.2 Quick stats from CLI
516
+ ```bash
517
+ flashinfer-bench report best --local . 2>&1 | head -40
518
+ flashinfer-bench report summary --local . 2>&1 | head -40
519
+ ```
520
+
521
+ > 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.
522
+
523
+ ---
524
+
525
+ ## Step 7 — Visualize
526
+
527
+ Two paths:
528
+
529
+ ### 7.1 Public site (read-only, official traces only)
530
+
531
+ https://bench.flashinfer.ai
532
+
533
+ 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.
534
+
535
+ ### 7.2 Local web UI (sees your traces)
536
+
537
+ The local Next.js dev server reads traces from the local `flashinfer-trace` clone:
538
+
539
+ ```bash
540
+ # Install pnpm (if not already; standalone binary is the simplest path)
541
+ curl -fsSL -o ~/bin/pnpm \
542
+ https://github.com/pnpm/pnpm/releases/download/v9.15.0/pnpm-linuxstatic-x64
543
+ chmod +x ~/bin/pnpm
544
+ export PATH=~/bin:$PATH
545
+
546
+ # Configure pnpm to store packages on scratch (avoids home-quota issues)
547
+ mkdir -p /home/scratch.<user>/.pnpm-store
548
+ pnpm config set store-dir /home/scratch.<user>/.pnpm-store
549
+
550
+ # Install web app dependencies
551
+ cd /home/scratch.<user>/kernel_arena/flashinfer-bench/web
552
+ pnpm install # ~2-3 minutes; produces ~1.9 GB node_modules
553
+
554
+ # Point the data loader at your local dataset
555
+ export FIB_DATASET_PATH=/home/scratch.<user>/kernel_arena/flashinfer-trace
556
+ # Belt-and-suspenders: the data loader also looks at three fallback paths;
557
+ # the surest cover is to symlink one of the fallback locations:
558
+ ln -sfn $FIB_DATASET_PATH /tmp/flashinfer-trace
559
+ ln -sfn $FIB_DATASET_PATH /home/scratch.<user>/kernel_arena/flashinfer-bench/flashinfer_trace
560
+
561
+ # Start the dev server (apps/web only; skip apps/docs to save resources)
562
+ cd apps/web
563
+ nohup pnpm dev > /tmp/dev.log 2>&1 &
564
+
565
+ # Wait until ready (typically 60–90 s on a frontend-only machine)
566
+ until grep -q "Ready in" /tmp/dev.log; do sleep 2; done
567
+ echo "Open http://localhost:3000"
568
+ ```
569
+
570
+ Notes on the web UI:
571
+ - Default port 3000 (web app), 3030 (docs)
572
+ - VS Code Remote-SSH auto-forwards port 3000 to local; otherwise set up an SSH tunnel
573
+ - **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
574
+ - For a faster experience: `pnpm build && pnpm start` produces a production bundle (~10 min build, then sub-second navigation forever)
575
+
576
+ ### 7.3 Pages worth opening
577
+
578
+ | Path | Contents |
579
+ |---|---|
580
+ | `http://localhost:3000` | Leaderboard / kernel list / model list (homepage) |
581
+ | `http://localhost:3000/kernels/<def_name>` | Per-Definition page: Solutions table, fast_p curve over workloads, top-5 by speedup |
582
+ | `http://localhost:3000/models/<model_id>` | Per-model coverage page (which Definitions belong to this model, status) |
583
+ | `http://localhost:3000/viewer` | Paste a single Trace JSON to inspect raw structure |
584
+
585
+ ### 7.4 Sharing traces with collaborators
586
+
587
+ Traces are jsonl files in `traces/<author>/<op_type>/<def_name>.jsonl`. To share:
588
+ - Copy the jsonl directly (one file per (author, op_type, def))
589
+ - Open the public Viewer (https://bench.flashinfer.ai/viewer) and paste a single line of jsonl as a Trace JSON
590
+ - Or commit + push to a branch of `flashinfer-trace` and open a PR (then the public site updates after merge)
591
+
592
+ ---
593
+
594
+ ## Common gotchas
595
+
596
+ Curated from real run failures. Full list with diagnostics → [`reference/wrapper_gotchas.md`](reference/wrapper_gotchas.md).
597
+
598
+ ### Numerical / contract mismatches
599
+
600
+ | Symptom | Likely cause | Fix |
601
+ |---|---|---|
602
+ | `INCORRECT_NUMERICAL` with `max_rel_error` ~ 1e0 | LSE base mismatch (natural log vs base-2) | Multiply natural-log LSE by `1 / math.log(2)` |
603
+ | `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 |
604
+ | `INCORRECT_NUMERICAL` only on long-KV workloads | GQA expansion (`repeat_interleave`) mis-axis | Expand `H_kv → H_q` along the *head* axis only |
605
+ | 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 |
606
+ | 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 |
607
+
608
+ ### Runtime / framework
609
+
610
+ | Symptom | Likely cause | Fix |
611
+ |---|---|---|
612
+ | `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) |
613
+ | 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 |
614
+ | 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 |
615
+ | `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 |
616
+
617
+ ### Environment / disk
618
+
619
+ | Symptom | Likely cause | Fix |
620
+ |---|---|---|
621
+ | `git-lfs pull` fails or outputs only pointers | git-lfs not installed locally | `git-lfs install --local`, then re-pull |
622
+ | Disk-full mid-run | Home quota too small | Move repo + scripts + results to scratch (Section 3.3) |
623
+ | `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` |
624
+
625
+ ### Hardware-specific
626
+
627
+ | Symptom | Likely cause | Fix |
628
+ |---|---|---|
629
+ | `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 |
630
+ | 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` |
631
+ | 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 |
632
+
633
+ ---
634
+
635
+ ## Reference & templates
636
+
637
+ ### Reference docs (deep dives)
638
+
639
+ - [`reference/definition_schema.md`](reference/definition_schema.md) — full Definition JSON schema with field semantics
640
+ - [`reference/solution_schema.md`](reference/solution_schema.md) — full Solution JSON schema
641
+ - [`reference/wrapper_gotchas.md`](reference/wrapper_gotchas.md) — extended troubleshooting list
642
+ - [`reference/visualization.md`](reference/visualization.md) — full web-UI / viewer setup notes including production build path
643
+
644
+ ### Wrapper templates (copy-paste starting points)
645
+
646
+ - [`templates/dense_baseline_main.py`](templates/dense_baseline_main.py) — PyTorch SDPA-style dense baseline (paged GQA decode example)
647
+ - [`templates/dense_baseline_solution.json`](templates/dense_baseline_solution.json) — matching Solution JSON
648
+ - [`templates/linear_attention_main.py`](templates/linear_attention_main.py) — third-party Python lib wrapper (FLA-style; recurrent state, gated delta rule)
649
+ - [`templates/linear_attention_solution.json`](templates/linear_attention_solution.json) — matching Solution JSON
650
+ - [`templates/vendored_kernel_main.py`](templates/vendored_kernel_main.py) — vendored Triton kernel (SGLang-style; MLA decode with split-K + LSE reduction)
651
+ - [`templates/vendored_kernel_solution.json`](templates/vendored_kernel_solution.json) — matching Solution JSON
652
+
653
+ Each template is heavily commented; the comments mark the lines you typically need to change for a new Definition.
654
+
655
+ ---
656
+
657
+ ## Quick reference: end-to-end run script
658
+
659
+ A complete script for running a single (Definition, Solution) pair from scratch:
660
+
661
+ ```bash
662
+ #!/bin/bash
663
+ set -e
664
+ USER_NAME=$(whoami)
665
+ SCRATCH=/home/scratch.${USER_NAME}_*
666
+ TRACE_ROOT=$SCRATCH/kernel_arena/flashinfer-trace
667
+ DEF=mla_paged_decode_h16_ckv512_kpe64_ps1 # ← Edit
668
+ OP=mla_paged # �� Edit
669
+ SOL=my_solution_v1 # ← Edit
670
+ AUTHOR=acme-research # ← Edit
671
+
672
+ export PIP_TARGET=/tmp/pip-pkgs
673
+ mkdir -p "$PIP_TARGET"
674
+ export PYTHONPATH="$PIP_TARGET:$PYTHONPATH"
675
+ export PATH="$PIP_TARGET/bin:$PATH"
676
+ pip install --target "$PIP_TARGET" --no-cache-dir flashinfer-bench 2>&1 | tail -2
677
+
678
+ cd "$TRACE_ROOT"
679
+ git-lfs install --local
680
+ git-lfs pull --include="blob/workloads/$OP/$DEF/*"
681
+
682
+ # (Solution files at solutions/$AUTHOR/$OP/$DEF/ are assumed already created)
683
+
684
+ flashinfer-bench run \
685
+ --local . \
686
+ --definitions "$DEF" \
687
+ --solutions "$SOL" \
688
+ --warmup-runs 5 \
689
+ --iterations 20 \
690
+ --num-trials 1 \
691
+ --timeout 600 \
692
+ --log-level INFO
693
+
694
+ # Inspect
695
+ find traces -name "*${DEF}*.jsonl" -size +100c | xargs wc -l
696
+ ```
697
+
698
+ Save as `run_single_solution.sh`, set the four `← Edit` variables, and run.
699
+
700
+ ---
701
+
702
+ **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
+ }