怎么设计一个自动优化 CUDA kernel 的 agent?
先弄清楚:每个概念是什么
- 题目
- 给一个 PyTorch op,让 agent 写出又对又快的 CUDA 或 Triton kernel。
- One-shot
- LLM 只生成一次,不看任何执行结果。
- Harness
- agent 外面那层确定性的代码。它编译、查正确性、计时,并决定候选留不留(见 LLM harness)。
- Profiler feedback
- Nsight Compute 给的硬件指标,告诉 agent 瓶颈是 memory bound 还是 compute bound。
- fast_p
- KernelBench 的指标,既正确、又比 PyTorch 快 p 倍以上的题目比例。
看图:agent 的循环
30 秒回答
I'd start with one-shot generation, which rarely beats PyTorch. So I'd add a loop that feeds back compiler errors and correctness diffs, then timing and profiler metrics so the agent knows the bottleneck. A single chain gets stuck, so I'd keep several candidates with beam or evolutionary search. Stronger search finds holes in the harness, so I'd harden it. Finally, I'd train the model with RL in the same environment, so the skill lives in the model, not in expensive search. In production I'd keep search simple and put the effort into verification, as FlashVector does.
Version chain
| 版本 | 加了什么 | 还剩的问题 |
|---|---|---|
| v1 One-shot | LLM 直接写 kernel | KernelBench 上 frontier model 比 PyTorch 快的不到 20%,很多编译不过或数值不对 |
| v2 编译和 正确性循环 | 编译错误和数值 diff 喂回去重写。NVIDIA 的 DeepSeek-R1 加 verifier 闭环在 L1 上全部数值正确(怎么查正确性) | 对了,但不快 |
| v3 Benchmark 和 profiler | 给 runtime 和 Nsight Compute 指标。KernelBench 论文里 DeepSeek-R1 在 L2 的 fast_1 从 36% 升到 72%,只加 execution feedback 时是 62%(怎么计时) | 单条链容易困在第一个思路里 |
| v4 搜索 | 保留 top-K 候选,用 beam 或 evolution。AlphaEvolve 演化 matmul 的 tiling heuristic,kernel 平均快 23%(怎么选) | 搜得越狠,越会钻评测的漏洞。Sakana 的一个 kernel 报快 150x,实际慢 3x |
| v5 加固 harness | hidden shape、按 dtype 的容差、分进程跑、评测脚本只读,比物理上限还快就作废(漏洞、隔离) | 每个 kernel 都搜一遍,token 很贵 |
| v6 RL | 在同一个环境里做 multi-turn RL,把能力训进模型。例子是 Kevin 和 CUDA Agent(reward 怎么设计) | 训练不稳,hack 会被放大 |
FlashVector 的搜索很简单
FlashVector 有 v3 的 profile 循环和 v5 的 harness,没有 v4 的搜索,是一轮只做一个改动的单链循环。
Meta 的 KernelEvolve 用 MCTS 加 evolution,AlphaEvolve 用 evolution,Baseten 和 FlashVector 一样是带排序的贪心循环。四家都报告了生产落地,所以搜索的复杂度和进没进生产没有正相关。上生产先把 harness 做牢,搜索够用就行。
必答点
- 从 one-shot 讲起,每一版只解决上一版的一个问题
- 反馈先过编译和正确性,再给 runtime 和 profiler 指标
- agent 只提案,去留由它改不了的 harness 判定
- 搜索越强越会钻漏洞,所以 v4 和 v5 要连着讲
- RL 把能力训进模型,省掉每个 kernel 的搜索 token
- FlashVector 用单链循环进了生产,精力在 verify 和交付
追问
循环什么时候停?
结果接近硬件的物理上限(speed of light)、连续几轮没有提升或预算用完时停。FlashVector 的 Algorithm 1 只写了到迭代上限或优化目标达成。
没有 profiler feedback 会怎样?
LLM 会一直沿着第一版的写法改。Meta KernelAgent 的 matvec 例子里,不给硬件反馈的版本比 torch.compile 还慢(数字见 search 方法怎么选)。
让 agent 写 CUDA 还是 Triton?
DSL 更容易写对,μCUTLASS 论文的对比数字见 Triton 和 CUDA。
循环的控制流放在 LLM 里还是代码里?
放在确定性的代码里,LLM 只提案和写代码,这是 Meta KernelFalcon 的做法(见 sub-agent)。
来源ml-八股 08 第 19 题 · KernelBench(不到 20%;DeepSeek-R1 在 L2 的 36%、62%、72% 见 Table 1)· NVIDIA:R1 加 verifier · AlphaEvolve · TechCrunch 2025-02-21(Sakana 的 150x)· Kevin-32B · CUDA Agent · FlashVector Algorithm 1、Figure 3 · KernelAgent · μCUTLASS · 同类系统的对照见 调研笔记第 4 节 · 牛客原帖见“考过”行