Experiment 008

One Decision / One Decider

FlyDSL is a Python language for writing AMD GPU kernels. AI agents now write many of these kernels. This post asks which parts of the FlyDSL compiler to keep and which parts to remove. Then it tests the answer with 29 experiments on MI355X GPUs.

FlyDSL 是一种用 Python 写 AMD GPU kernel 的语言。 现在很多 kernel 由 AI agent 来写。 本文讨论 FlyDSL 编译器的哪些部分该保留、 哪些可以去掉。 然后在 MI355X GPU 上用 29 组实验检验这个答案。

Hardware硬件MI355X · gfx950 · overlay
FlyDSL under test被测 FlyDSLcb770e9a (FlyBench v1)
Code reading读代码fe81c407 (v0.5.2)
Timing计时FlyBench v1 · 6 ABBA pairsFlyBench v1 · 6 组 ABBA
Agent dataagent 数据98 runs · 676 receipts · 827 traces98 次运行 · 676 张回执 · 827 份轨迹
Data数据data/flydsl-compiler-redesign

01The question问题

My mentor asked me to think about the FlyDSL compiler chain. The previous post asked where a compiler can help in the kernel optimization loop. This post asks a more basic question.

mentor 让我想清楚 FlyDSL 的编译链。 上一篇讨论的是编译器能在 kernel 优化循环的哪个环节帮忙。 这一篇问一个更基础的问题。

FlyDSL lets an author write a GPU kernel in Python. A kernel is a function that runs on thousands of GPU threads at the same time. The FlyDSL compiler changes the Python code into machine instructions for the GPU. For this work, it uses two large compiler projects: MLIR and LLVM.

FlyDSL 让作者用 Python 写 GPU kernel。 kernel 是在 GPU 上由几千个线程同时执行的函数。 FlyDSL 编译器把 Python 代码转换成 GPU 的机器指令。 为此, 它用了两个大型编译器项目: MLIR 和 LLVM。

The question is: if we can remove MLIR, and even LLVM, what must a kernel language for agents keep, and what can it remove? A design argument is easy to write. Thus we also ran experiments that could show that the argument is wrong. We used the same GPUs and the same evaluator that score the agents.

问题是: 如果可以去掉 MLIR, 甚至去掉 LLVM, 一个给 agent 用的 kernel 语言必须保留什么、 可以去掉什么? 设计论证很容易写。 所以我们还做了实验, 这些实验有可能证明论证是错的。 实验用的是给 agent 打分的同一批 GPU 和同一个评测器。

Short answer.

  1. The main problem is not the size of the compiler. The main problem is that two parties make the same decisions. The kernel author decides part of the instruction stream. Then LLVM decides the same part again with general rules (heuristics). An author who needs a specific result must override LLVM with special markers, inline assembly or LLVM patches.
  2. We removed one decision of the author at a time and let LLVM decide. Six kernels became 5–16% slower. One more kernel became about 1% slower or less.
  3. In two kernels, the results became wrong. The markers that we removed were not only for speed. They also kept the results correct.
  4. AI agents got most of their speedups from other decisions, for example the tile size and the memory access. In 69% of the agent command logs, the agent read the compiler output to learn what the compiler did.
  5. Our proposal: each decision gets exactly one decider. The compiler reports each choice that it makes. MLIR is removed. LLVM is removed in two steps.

简短回答。

  1. 主要问题不是编译器太大, 而是同一件事有两方在决定。 kernel 作者决定了指令流的一部分。 然后 LLVM 用通用规则(启发式规则)把这一部分再决定一遍。 需要特定结果的作者, 只能用特殊标记、 inline 汇编或者 LLVM 补丁去覆盖 LLVM 的决定。
  2. 我们每次去掉作者的一个决策, 让 LLVM 来决定。 结果 6 个 kernel 慢了 5–16%。 另一个 kernel 慢了约 1% 或更少。
  3. 有两个 kernel 的结果变错了。 被去掉的标记不只是为了速度, 也在保证结果正确。
  4. AI agent 的提速主要来自其他决策, 例如 tile 大小和访存方式。 在 69% 的 agent 命令记录里, agent 读过编译器的输出, 为的是弄清编译器做了什么。
  5. 我们的方案: 每个决策只有一个决策者。 编译器报告它做的每个选择。 去掉 MLIR。 分两步去掉 LLVM。

02Terms used in this post本文用到的术语

You do not need a compiler background to read this post. The two tables below define the terms that it uses. Each term has only one meaning in this post.

读这篇文章不需要编译器背景。 下面两张表定义了文中用到的术语。 每个术语在本文里只有一个意思。

GPU and compiler terms

GPU 和编译器术语

Term术语Meaning in this post在本文中的意思
kernelkernelA function that runs on the GPU. Many threads run it at the same time.在 GPU 上运行的函数。 很多线程同时执行它。
wavewaveA group of 64 threads that run the same instruction together on an AMD GPU.AMD GPU 上一起执行同一条指令的 64 个线程。
register寄存器The fastest storage in the GPU. Each wave can use only a limited number of registers. VGPRs and AGPRs are two kinds of registers. Matrix instructions on MI355X can keep their results in AGPRs.GPU 里最快的存储。 每个 wave 能用的寄存器数量有限。 VGPR 和 AGPR 是两种寄存器。 MI355X 的矩阵指令可以把结果放在 AGPR 里。
spillspillWhen a kernel needs more registers than it has, the compiler moves some values to slow memory. The kernel then becomes slower.kernel 需要的寄存器比能用的多时, 编译器把一部分值放到慢速内存里。 kernel 因此变慢。
occupancyoccupancyThe number of waves that can run on one compute unit at the same time. When each wave uses more registers, fewer waves fit.一个计算单元上能同时运行的 wave 数。 每个 wave 用的寄存器越多, 能放下的 wave 越少。
instruction order指令顺序The order in which the GPU runs the instructions. A good order keeps the math units busy while data loads.GPU 执行指令的先后顺序。 好的顺序让计算单元在加载数据时也不空闲。
wait (s_waitcnt)wait(s_waitcnt)An instruction that stops a wave until its earlier memory operations are complete.一条指令: 让 wave 停下, 直到它之前发出的访存操作完成。
barrier (s_barrier)barrier(s_barrier)An instruction that stops each wave of a workgroup until all of these waves arrive at it.一条指令: 让一个 workgroup 里的每个 wave 停下, 直到所有 wave 都执行到这里。
fence (sched_barrier)fence(sched_barrier)A marker for the compiler, not an instruction for the GPU. The compiler must not move instructions across it.给编译器的标记, 不是给 GPU 的指令。 编译器不能把指令移过它。
interleave group (sched_group_barrier)交错组(sched_group_barrier)A marker that gives the compiler an order pattern, for example "one matrix instruction, then one load".给编译器的顺序模板, 例如 "一条矩阵指令, 然后一条加载指令"。
wave priority (s_setprio)wave 优先级(s_setprio)An instruction that tells the GPU which waves to run first.一条指令: 告诉 GPU 先执行哪些 wave。
pinpinA hint that forces a value into one kind of register, for example into AGPRs.强制把某个值放进指定寄存器(例如 AGPR)的提示。
hazardhazardA pair of instructions that must have a gap between them. The compiler fills the gap with s_nop, an instruction that does nothing.两条之间必须留出间隔的指令。 编译器用 s_nop(什么都不做的指令)填这个间隔。
heuristic启发式规则A general rule that a compiler uses to make a choice automatically. It works well on average, but it does not know what the author wants.编译器自动做选择时用的通用规则。 平均效果不错, 但它不知道作者想要什么。
LLVMLLVMA large, general compiler project. FlyDSL uses its AMD GPU part to make the final machine instructions.一个大型通用编译器项目。 FlyDSL 用它的 AMD GPU 部分生成最终的机器指令。
MLIRMLIRA framework for building compiler steps. FlyDSL uses it between Python and LLVM.一个用来搭建编译步骤的框架。 FlyDSL 在 Python 和 LLVM 之间使用它。
ISAISAThe machine instructions that the GPU runs. We read the ISA to see what the compiler did.GPU 真正执行的机器指令。 我们读 ISA 来确认编译器做了什么。
tracetraceFlyDSL runs the Python code of a kernel once and records its operations. It does this before each launch.FlyDSL 先把 kernel 的 Python 代码执行一遍, 记录其中的操作。 每次启动 kernel 前都要做一次。
layoutlayoutA rule that says which thread holds which element of a data tile.一条规则: 说明数据 tile 的哪个元素由哪个线程持有。
race竞争A bug in which the result depends on which wave runs first. The wrong output can change from run to run.一种 bug: 结果取决于哪个 wave 先执行。 错误的输出每次运行都可能不同。

Experiment terms

实验术语

Term术语Meaning in this post在本文中的意思
agentagentAn AI model that writes and tests code by itself, in many steps.能自己分很多步写代码、 测代码的 AI 模型。
overlayoverlayThe AMD Pilot v2 job system. It runs our jobs on MI355X GPUs in the same way as agent jobs.AMD Pilot v2 的作业系统。 它在 MI355X GPU 上运行我们的作业, 方式和运行 agent 作业相同。
FlyBench evaluatorFlyBench 评测器The program that scores agent submissions. First it checks the results. Then it compares the speed of a change with the stock kernel.给 agent 提交打分的程序。 它先检查结果是否正确, 再把改动后的速度和 stock kernel 比较。
stock kernelstock kernelThe unchanged kernel from FlyDSL. Each comparison uses it as the baseline.FlyDSL 原来的、 没有修改过的 kernel。 所有比较都以它为基准。
attempt尝试One agent that works on one kernel, within one time limit. One FlyBench run has many attempts.一个 agent 在一个时间限制内处理一个 kernel。 一次 FlyBench 运行包含很多次尝试。
armarmOne variant in an experiment: the stock kernel with one change.实验里的一个变体: stock kernel 加上一个改动。
speed ratio速度比Stock time divided by arm time. Below 1.0 means that the arm is slower. In this post, "12% slower" means a speed ratio of 0.88×.stock 用时除以 arm 用时。 小于 1.0 表示 arm 更慢。 本文说 "慢了 12%", 指速度比是 0.88×。
noise level噪声下限The smallest change that the evaluator can separate from random variation. FlyBench measures it with the stock kernel against itself.评测器能和随机波动区分开的最小变化。 FlyBench 用 stock kernel 和它自己比较来测得。
null control空白对照An arm that changes nothing that matters. Its result shows the noise of the measurement.一个没有实质改动的 arm。 它的结果显示测量本身的噪声。

03Five decisions, two deciders五类决策, 两个决策者

The speed of an AMD GPU kernel depends on five kinds of decisions. This is true for each language that makes kernels, not only for FlyDSL:

AMD GPU kernel 的速度取决于五类决策。 这一点对所有写 kernel 的语言都成立, 不只是 FlyDSL:

  • Work split: how to cut the problem into tiles, and how many workgroups to start.
  • Data movement: which thread moves which data through which memory.
  • Instruction choice: which matrix instruction does the math.
  • Register use: which register holds each value. This sets the occupancy.
  • Instruction order: the order of the instructions, the position of the waits, and the wave priority.
  • 工作划分: 问题怎样切成 tile, 启动多少个 workgroup。
  • 数据搬运: 哪个线程通过哪一级存储搬哪些数据。
  • 指令选择: 用哪条矩阵指令做运算。
  • 寄存器使用: 每个值放在哪种寄存器里。 它决定了 occupancy。
  • 指令顺序: 指令的先后、 wait 的位置和 wave 优先级。

In FlyDSL, the author makes the first three decisions in Python. The compiler only translates them. The heuristics of LLVM make the last two decisions.

在 FlyDSL 里, 前三类决策由作者在 Python 里做出, 编译器只负责翻译。 后两类决策由 LLVM 的启发式规则来做。

Plate I · five decisions and who makes them in FlyDSL today五类决策, 以及今天在 FlyDSL 里由谁来做
five decisions and who makes them work split · grid · tiles · split-K 工作划分 · grid · tile · split-K data movement · layouts 数据搬运 · layout instruction choice 指令选择 register use · occupancy 寄存器使用 · occupancy instruction order · waits · priority 指令顺序 · wait · 优先级 kernel author kernel 作者 Python · layout algebra Python · layout 代数 atoms · explicit hints atom · 显式提示 LLVM heuristics LLVM 启发式规则 instruction order 指令顺序 registers · waits 寄存器 · wait final ISA 最终 ISA what the GPU runs GPU 真正执行的 fences · inline asm pins · LLVM patches fence · inline 汇编 pin · LLVM 补丁

The author makes the first three decisions directly. LLVM makes the last two with its heuristics. When an author needs a specific result for the last two, the author overrides LLVM through the red path.

前三类决策由作者直接做出。 后两类由 LLVM 用启发式规则来做。 作者如果需要后两类的特定结果, 就通过红色路径覆盖 LLVM 的决定。

The red path is common. In the FlyDSL kernels at fe81c407, 34 of 180 kernel files use fences (257 times in total). 44 files place waits by hand (186 times). 13 files use inline assembly, and 12 files set the wave priority.

红色路径很常见。 在 fe81c407 的 FlyDSL kernel 里, 180 个 kernel 文件中有 34 个使用 fence(共 257 次)。 44 个文件手工放置 wait(共 186 次)。 13 个文件使用 inline 汇编, 12 个文件设置 wave 优先级。

The kernel comments give the reasons. One kernel uses inline assembly so that LLVM does not see a memory operation and does not add a wait (fp4_gemm_4wave.py). Another kernel adds a fence and gives this reason: "the scheduler may hoist them above s_barrier: a race" (mega_moe_tp/gemm.py). That is, LLVM can move the reads before the barrier, and the kernel then reads data that is not ready.

kernel 里的注释写明了原因。 一个 kernel 用 inline 汇编, 是为了让 LLVM 看不到一次访存, 从而不插入 wait(fp4_gemm_4wave.py)。 另一个 kernel 加了 fence, 注释写的是: "调度器可能把它们提到 s_barrier 之前: 这是竞争"(mega_moe_tp/gemm.py)。 意思是: LLVM 可能把读取移到 barrier 之前, kernel 就会读到还没准备好的数据。

Sometimes the override needs a change to LLVM itself. To keep one accumulator in AGPRs, FlyDSL patched the register allocator and the instruction selector of LLVM (#1368). Then the patch was reverted, because it caused spills in a kernel of another team (#1477).

有时覆盖 LLVM 需要修改 LLVM 本身。 为了把一个累加器固定在 AGPR 里, FlyDSL 修改了 LLVM 的寄存器分配和指令选择(#1368)。 后来这个补丁被回滚, 因为它让另一个团队的 kernel 出现了 spill(#1477)。

This problem is larger for an agent than for a person. An agent improves a kernel with small edits and measurements. This method works only if a small edit has a small, local effect. A heuristic that decides again for the whole kernel breaks this condition.

这个问题对 agent 比对人更严重。 agent 靠小改动加测量来改进 kernel。 这个方法只有在 "小改动只产生小的局部影响" 时才有效。 一个会对整个 kernel 重新做决定的启发式规则, 破坏了这个条件。

Here is an example from our experiments. The FP8 8-wave GEMM has four s_setprio instructions. Their documented job is only to set the wave priority. When we removed them, the register use changed, and the kernel got 6 spills. The cause is one line in LLVM: LLVM treats s_setprio as a hard limit for instruction order (SIInstrInfo.cpp). Thus one hint has two effects, and the kernel source does not show the second effect.

下面是我们实验里的一个例子。 FP8 8-wave GEMM 里有 4 条 s_setprio 指令。 按文档, 它们只负责设置 wave 优先级。 我们去掉它们之后, 寄存器使用发生了变化, kernel 多出 6 个 spill。 原因是 LLVM 里的一行代码: LLVM 把 s_setprio 当作指令顺序的硬边界(SIInstrInfo.cpp)。 所以一个提示有两种效果, 而 kernel 源码里看不到第二种。

04Where the compiler repeats work编译器在哪里重复工作

The decision table also explains other repeated work in the compiler. In each item below, the compiler keeps the same information twice, or makes the same decision twice.

这张决策表也能解释编译器里其他的重复工作。 下面每一项里, 编译器都把同一份信息保存了两次, 或者把同一个决定做了两次。

Two languages in one function, with a hidden rule

一个函数里有两种语言, 靠隐藏规则区分

A FlyDSL kernel mixes two kinds of Python. Some Python runs once, when the compiler reads the kernel. Other Python becomes loops and branches on the GPU. A tool of 1,928 lines decides which is which from the type of each value (ast_rewriter.py). The source code does not show this rule, and the rule can fail without an error.

For example, #1436 fixed a case in which if flag: return a, followed by return b, always returned b. Because of this bug, one production kernel ignored one of its inputs from the day it was written. The agent guide of the repository lists four rules that exist only because of this tool (CLAUDE.md).

一个 FlyDSL kernel 里混着两种 Python。 一种在编译器读 kernel 时执行一次。 另一种会变成 GPU 上的循环和分支。 一个 1928 行的工具根据每个值的类型来判断哪段属于哪种(ast_rewriter.py)。 源码里看不出这条规则, 规则出错时也不报错。

例如, #1436 修复了这样一个问题: if flag: return a 后面接 return b 时, 总是返回 b。 因为这个 bug, 一个生产 kernel 从写成那天起就一直忽略它的一个输入。 仓库给 agent 的指南列出了四条规则, 它们只因为这个工具才存在(CLAUDE.md)。

Layouts built as compiler objects, then deleted

layout 先建成编译器对象, 再删掉

Most layouts are known before the kernel runs. Thus the compiler can calculate them with simple integer arithmetic. Instead, FlyDSL records each layout step as an MLIR operation, and later deletes most of these operations. For fp8_gemm_4wave, the trace builds 61,989 operations, and only 9,907 remain after the layout steps. This build-and-delete work is most of the 0.80 s of the trace. A pure-Python version of the same layout algebra, pycute, has about 760 lines.

大多数 layout 在 kernel 运行之前就已经确定, 所以编译器用简单的整数运算就能算出来。 但 FlyDSL 把每一步 layout 运算都记录成一个 MLIR 操作, 之后再删掉其中的大部分。 对 fp8_gemm_4wave, trace 建出 61,989 个操作, layout 步骤之后只剩 9,907 个。 这些先建后删的工作占了 0.80 s trace 时间的大部分。 同一套 layout 代数的纯 Python 版本 pycute 只有大约 760 行。

Registers stored as memory, then converted back

寄存器先当成内存, 再转换回来

FlyDSL first creates register data as memory objects in a special register address space. Then two compiler steps (about 900 lines) convert these objects back to register values before LLVM sees them (Passes.td). This copies a habit of C++ CuTe, which declares register arrays. A compiler can treat a register tile as a value from the start.

FlyDSL 先把寄存器数据建成特殊寄存器地址空间里的内存对象。 然后用两个编译步骤(约 900 行)在交给 LLVM 之前把它们转换回寄存器值(Passes.td)。 这是照搬 C++ CuTe 声明寄存器数组的习惯。 编译器完全可以从一开始就把寄存器 tile 当作一个值。

Each call traces again, and each process compiles the launcher again

每次调用都重新 trace, 每个进程都重新编译启动代码

Before each launch, a @flyc.jit call traces the launcher and the kernel, prints the result as text and hashes the text. Only then can it look in the compile cache (jit_function.py). This makes the cache key correct. But a cache hit on fp8_gemm_4wave still costs 0.96 s. Also, each process compiles the host launcher again with MLIR and LLVM at full optimization, 22–33 ms per kernel. The launcher only fills an argument buffer and calls hipModuleLaunchKernel.

每次启动前, @flyc.jit 都要先 trace 启动代码和 kernel, 把结果打印成文本, 再对文本做哈希。 然后才能查编译缓存(jit_function.py)。 这样缓存 key 是正确的, 但 fp8_gemm_4wave 命中缓存的一次调用仍要 0.96 s。 另外, 每个进程都要用 MLIR 和 LLVM 以最高优化级别重新编译一次 host 端启动代码, 每个 kernel 22–33 ms。 而启动代码只做两件事: 填写参数缓冲区, 调用 hipModuleLaunchKernel。

Settings reach LLVM through four paths, and some have no effect

设置通过四条路径到达 LLVM, 有的没有效果

The LLVM skill file of the repository describes four paths that send settings from Python to LLVM. On AMD GPUs, one of these paths is ignored without a message. The compile-hint dictionary accepts misspelled keys, and a misspelled key still changes the cache key. An optimization-level variable is checked but never used (llvm skill §3, §8). Our experiment found one more case: in fp8_gemm_4wave, the occupancy hints give the same ISA as no hints.

仓库里的 llvm skill 文件描述了从 Python 向 LLVM 传递设置的四条路径。 在 AMD GPU 上, 其中一条会被直接忽略, 没有任何提示。 compile-hint 字典接受拼错的 key, 而拼错的 key 仍会改变缓存 key。 一个优化级别变量会被检查, 但从来没有被使用(llvm skill §3、§8)。 我们的实验又发现一个: 在 fp8_gemm_4wave 里, 写了 occupancy 提示和不写生成的 ISA 完全相同。

05The redesign: one decider for each decision重新设计: 每个决策只有一个决策者

The redesign follows from the decision table. Each decision has two options. In the first option, the author makes the decision, and the compiler obeys and checks it. In the second option, the author leaves the decision to the compiler. The compiler then makes it in a fixed, repeatable way and reports its choice. A decision never has two deciders.

重新设计直接从决策表推出。 每个决策有两种选择。 第一种: 作者做决定, 编译器照做并检查。 第二种: 作者把决定交给编译器, 编译器用固定、 可重复的方式做出决定, 并报告它的选择。 一个决策永远不会有两个决策者。

Plate II · the current path, and the path after the redesign现在的路径, 以及重新设计后的路径
today's pipeline and the redesigned one TODAY · FLYDSL 0.4 / 0.5 现在 · FLYDSL 0.4 / 0.5 Python hidden rule隐藏规则 trace every call每次调用 Fly MLIR layout objectslayout 对象 14 steps14 个步骤 convert转换 LLVM IR LLVM AMDGPU order · regs · waits顺序 · 寄存器 · wait binary二进制 re-run on every call 每次调用都重跑 62K objects built, 9.9K kept 建 62K 个对象, 只留 9.9K 42–60% of cold compile 冷编译的 42–60% the author overrides register use and order: fences, inline asm, pins, LLVM patches 作者覆盖寄存器使用和指令顺序: fence、 inline 汇编、 pin、 LLVM 补丁 REDESIGN · ONE DECIDER PER DECISION 重新设计 · 每个决策一个决策者 machine tables: AMD ISA files · latencies · hazards · atoms 机器描述表: AMD ISA 文件 · 延迟 · hazard · atom Python generates only只做生成 KIR typed · tokens类型 · token verify检查 select选指令 by table查表 order排顺序 explicit|auto显式|自动 registers分寄存器 pins kept保留 pin waits插 wait from tokens由 token 推出 encode编码 → binary→ 二进制 report: resources · pressure · waits · checks · settings 报告: 资源 · 压力 · wait 来源 · 检查 · 设置 each step writes one section; no decision is hidden 每个步骤写一节; 没有隐藏的决定 interpret(): KIR on the CPU interpret(): 在 CPU 上跑 KIR per-thread run · race checks 逐线程执行 · 检查竞争

Top: the current path. It shows the costs from section 10, and the red path where the author overrides LLVM. Bottom: the redesign. Python only generates the kernel. A small instruction format close to the hardware (KIR) goes through a series of steps. Each step makes one decision and writes it into a report.

上: 现在的路径。 图中标出了第 10 节测到的开销, 以及作者覆盖 LLVM 的红色路径。 下: 重新设计后的路径。 Python 只负责生成 kernel。 一种接近硬件的小型指令格式(KIR)依次经过若干步骤。 每个步骤只做一个决定, 并把它写进报告。

Five design rules follow from this principle:

由这个原则可以得出五条设计规则:

  1. Python only generates the kernel. Python loops and branches always run at compile time. GPU loops and branches use explicit functions: fx.loop and fx.cond. A GPU value in a Python if causes an error. JAX uses the same model (JAX control flow). This rule removes the 1,928-line tool and its four extra rules.
  2. Python calculates the layouts. Most layouts are known at compile time, so Python calculates them. Each layout is then a value that you can print and test. Only the parts that depend on runtime values become compiler operations.
  3. A small instruction format close to the hardware, here called KIR. The type of each value tells if all threads of a wave share it (an SGPR) or each thread has its own copy (a VGPR). A register tile records which thread holds which element. A memory copy returns a token, and each wait names the token that it waits for. Thus the compiler knows which data each wait protects, and it never moves a read before its wait.
  4. A repeatable backend that reports. The backend selects instructions from a table. The table comes from AMD's machine-readable ISA files, which already cover CDNA3, CDNA4 and CDNA5. In explicit code, where the author sets the order, the backend keeps that order. In automatic code, where the author does not, it uses a standard list scheduler with a published table of instruction costs. It assigns registers and keeps the pins of the author. It adds waits from the tokens, and it uses a table to keep the gaps that hazards need. Each step writes its choices into a report that the agent can read.
  5. Only settings that cannot change the results. The results then depend only on data flow and tokens. Thus the instruction order, the pins, the number of pipeline stages and the loop unrolling can change only the speed. Agents and autotuners can search these settings without a correctness check for each setting.
  1. Python 只负责生成 kernel。 Python 的循环和分支永远在编译期执行。 GPU 上的循环和分支用显式函数 fx.loop 和 fx.cond 表示。 在 Python 的 if 里用 GPU 上的值会报错。 JAX 用的是同样的模型(JAX control flow)。 这条规则让那个 1928 行的工具和它带来的四条规则一起消失。
  2. layout 由 Python 计算。 大多数 layout 在编译期就确定了, 所以由 Python 来算。 这样每个 layout 都是一个可以打印、 可以测试的值。 只有依赖运行时值的部分才变成编译器操作。
  3. 一种接近硬件的小型指令格式, 这里叫 KIR。 每个值的类型说明它是整个 wave 共享(SGPR), 还是每个线程各有一份(VGPR)。 寄存器 tile 记录哪个线程持有哪个元素。 一次内存拷贝会返回一个 token, 每个 wait 写明它等待哪个 token。 所以编译器知道每个 wait 保护的是哪些数据, 永远不会把读取移到对应的 wait 之前。
  4. 一个可重复、 会报告的后端。 后端从一张表里选择指令。 这张表来自 AMD 的机器可读 ISA 文件, 它已经覆盖 CDNA3、 CDNA4 和 CDNA5。 在显式代码里(由作者决定顺序), 后端保持作者写下的顺序。 在自动代码里(作者不决定顺序), 后端使用标准的列表调度方法和一张公开的指令开销表。 后端分配寄存器, 并保留作者的 pin。 它根据 token 插入 wait, 并按表格留出 hazard 需要的间隔。 每个步骤都把自己的选择写进 agent 能读的报告。
  5. 只保留不能改变结果的设置。 这样结果只取决于数据流和 token。 所以指令顺序、 pin、 流水线级数和循环展开只会改变速度。 agent 和 autotuner 可以搜索这些设置, 不需要对每个设置做一次正确性检查。

What this means for MLIR and LLVM:

这对 MLIR 和 LLVM 意味着什么:

  • MLIR can be removed. Its compiler steps take only 11–12% of the cold compile of the large kernels (section 10). Its real costs are the trace of each operation, the build-and-delete layout work, and a C++ rebuild for each change to a compiler step.
  • LLVM can be removed in two steps. Step 1: for explicit kernels, stop using the heuristics of LLVM, and use LLVM only to encode the instructions. AMD's hipBLASLt TensileLite already works this way: Python writes assembly, and amdclang++ -x assembler encodes it (Component.py). Step 2: when the new backend passes the kernel test set, generate an encoder from the ISA files, and stop using LLVM for these kernels.
  • MLIR 可以去掉。 它的编译步骤只占大 kernel 冷编译时间的 11–12%(第 10 节)。 它真正的成本是逐个操作的 trace、 先建后删的 layout 工作, 以及每改一个编译步骤都要重新编译 C++。
  • LLVM 分两步去掉。 第一步: 对显式 kernel, 不再使用 LLVM 的启发式规则, 只用 LLVM 给指令编码。 AMD 的 hipBLASLt TensileLite 已经这样做了: Python 写汇编, amdclang++ -x assembler 负责编码(Component.py)。 第二步: 等新后端通过 kernel 测试集之后, 从 ISA 文件生成编码器, 这些 kernel 就不再使用 LLVM。

What we did not do. We did not build KIR or the new backend. The experiments below test the facts that the design depends on. They do not measure the speed of the new design.

我们没有做的事。 我们没有实现 KIR 和新后端。 下面的实验检验的是这个设计所依赖的事实, 不是新设计本身的速度。

06How we tested it on the overlay怎样在 overlay 上检验

The design depends on four premises. Each premise can be false. For each one, we name the result that would show that it is false:

这个设计依赖四个前提。 每个前提都可能是错的。 对每个前提, 我们写出能证明它错误的结果:

  • A. The decisions that authors make by hand about register use and instruction order give real speed. LLVM does not find this speed by itself. False if: removing these decisions changes nothing.
  • B. Where authors made no such decision, safe settings that nobody tuned still give extra speed. False if: no setting changes the time.
  • C. Agents spend most of their effort on things that a compiler could show or check. False if: agents rarely read compiler output, and their speedups come from compiler settings.
  • D. The compile work before each launch costs time in each iteration of an agent. False if: a cache hit costs no time.
  • A. 作者手工做出的寄存器使用和指令顺序决策带来了实际的速度, LLVM 自己找不到这部分速度。 证伪条件: 去掉这些决策后什么都没变。
  • B. 在作者没有做这类决策的地方, 没人调过的安全设置仍能带来额外的速度。 证伪条件: 没有哪个设置能改变耗时。
  • C. agent 的大部分精力花在编译器本可以展示或检查的事情上。 证伪条件: agent 很少读编译器输出, 而且提速来自编译器设置。
  • D. 每次启动前的编译工作, 在 agent 的每次迭代里都要花时间。 证伪条件: 命中缓存不花时间。

How we measured experiments A and B

实验 A 和 B 怎样测量

  • Each arm is one patch to FlyDSL cb770e9a, the version that FlyBench v1 uses.
  • Arms that remove hints add a few lines to kernels/__init__.py. These lines change one kind of hint into an operation that does nothing, or they change the LLVM options. The register and occupancy arms change one line of the kernel.
  • The FlyBench v1 evaluator scored each arm. It is the same program that scores agent submissions.
  • The evaluator runs the stock kernel and the arm in new processes, in the order stock, arm, arm, stock (ABBA). It does this six times. This order cancels slow changes in GPU speed.
  • Before each cold call, it reads 512 MB of other data. Thus the caches do not keep data from the previous call.
  • It uses the public test shapes and new random shapes in each run.
  • An arm must pass the tests of FlyDSL and a correctness check on the new shapes. If it fails, it gets no speed result.
  • Each arm ran as one job on one MI355X GPU through the overlay. The job did not call an AI model.
  • 每个 arm 是针对 FlyDSL cb770e9a 的一个补丁, 这是 FlyBench v1 使用的版本。
  • 去掉提示的 arm 在 kernels/__init__.py 里加几行代码。 这几行代码把某一类提示变成什么都不做的操作, 或者修改 LLVM 选项。 寄存器和 occupancy 两个 arm 修改 kernel 里的一行。
  • 每个 arm 都由 FlyBench v1 评测器打分, 也就是给 agent 提交打分的同一个程序。
  • 评测器在新进程里按 stock、 arm、 arm、 stock 的顺序(ABBA)运行, 一共重复 6 次。 这个顺序能抵消 GPU 速度的缓慢变化。
  • 每次冷调用前, 评测器先读 512 MB 其他数据, 这样缓存里不会留下上一次调用的数据。
  • 每次运行都使用公开的测试 shape 和新随机抽取的 shape。
  • arm 必须通过 FlyDSL 自己的测试和新 shape 上的正确性检查, 否则不给速度结果。
  • 每个 arm 作为一个作业, 通过 overlay 在一张 MI355X GPU 上运行。 作业不调用 AI 模型。

Controls

对照

Each job also compiled the stock kernel and the arm at two shapes, and compared the ISA. All arms changed the ISA except three. The first is the occupancy arm (section 07). The other two are null controls: RMSNorm, which has no hints to remove, and the A16W16 GEMM with the added lines but nothing removed.

The null controls measured 1.004× and 0.998×. This is the noise of our setup. Thus we cannot see effects smaller than about 0.5%.

每个作业还在两个 shape 上分别编译 stock kernel 和 arm, 并比较 ISA。 除了三个 arm, 其他 arm 都改变了 ISA。 第一个是 occupancy arm(第 07 节)。 另外两个是空白对照: 一个是没有提示可去的 RMSNorm, 另一个是加了那几行代码、 但什么都没去掉的 A16W16 GEMM。

两个空白对照测得 1.004× 和 0.998×。 这就是我们这套测量的噪声, 所以小于约 0.5% 的效果看不出来。

The register arm changes code only for 256×256 tiles. Only two of its 19 timed shapes use these tiles. Thus we report this arm at these two shapes.

寄存器 arm 只改变 256×256 tile 的代码。 它的 19 个计时 shape 里只有 2 个用这种 tile, 所以我们只在这两个 shape 上报告它。

Limit. The overlay puts single-GPU jobs next to other jobs on the same node, so we did not measure on idle GPUs. The ABBA order removes slow drift between stock and arm. It does not remove noise from other jobs. The intervals below include this noise. The agent data in experiment C comes from earlier FlyBench runs, not from new agent jobs.

局限。 overlay 会把单卡作业和其他作业放在同一个节点上, 所以我们不是在空闲的 GPU 上测量的。 ABBA 顺序能消除 stock 和 arm 之间的缓慢漂移, 但消除不了其他作业带来的噪声。 下面的区间已经包含这部分噪声。 实验 C 的 agent 数据来自之前的 FlyBench 运行, 不是新跑的 agent 作业。

07Experiment A · take one decision away from the author实验 A · 拿走作者的一个决策

What we did. Each arm removes one decision that the author made about register use or instruction order. Then the default heuristics of LLVM make that decision. If these heuristics were as good as the author, each bar in Plate III would be at 1.0.

做了什么。 每个 arm 去掉作者在寄存器使用或指令顺序上的一个决策, 改由 LLVM 的默认启发式规则来做。 如果这些规则和作者一样好, Plate III 里的每根条都应该在 1.0。

Plate III · speed ratio when one decision of the author is removed去掉作者的一个决策后的速度比
speed relative to the stock kernel 0.80× 0.85× 0.90× 0.95× 1.00× 1.05× 1.10× ← slower than stock ← 比 stock 慢 faster than stock → 比 stock 快 → preshuffle-a8 · fences + groups preshuffle-a8 · fence + 交错组 0.882× preshuffle-a8 · groups only preshuffle-a8 · 只去交错组 0.883× mx-preshuffle-a8w8 · fences + groups mx-preshuffle-a8w8 · fence + 交错组 0.947× swa-gqa · fences + groups swa-gqa · fence + 交错组 0.840× a16w16 · fences a16w16 · fence ✕ wrong results: 1 of 880 tests fail ✕ 结果错误: 880 个测试里 1 个失败 a16w16 · fences (repeat) a16w16 · fence(重复) ✕ wrong results: 1 of 880 tests fail ✕ 结果错误: 880 个测试里 1 个失败 flash-fwd-dense · fences + groups flash-fwd-dense · fence + 交错组 ✕ wrong results: 28 of 1039 tests fail ✕ 结果错误: 1039 个测试里 28 个失败 flash-fwd-dense · groups only flash-fwd-dense · 只去交错组 0.990× fp8-rowscale-8wave · s_setprio fp8-rowscale-8wave · s_setprio 0.862× mxfp8-8wave · s_setprio mxfp8-8wave · s_setprio 0.902× flash-fwd-dense · s_setprio flash-fwd-dense · s_setprio 0.998× flash-fwd-dense · post-RA scheduler on flash-fwd-dense · 打开 post-RA 调度 1.006× fp8-rowscale-4wave · AGPR pin (16384³) fp8-rowscale-4wave · AGPR pin(16384³) 0.864× fp8-rowscale-4wave · AGPR pin (8192³) fp8-rowscale-4wave · AGPR pin(8192³) 0.911× fp8-rowscale-4wave · occupancy hints fp8-rowscale-4wave · occupancy 提示 1.000× rmsnorm-fwd · null control rmsnorm-fwd · 空白对照 1.004× a16w16 · null control a16w16 · 空白对照 0.998×

instruction order: fences, groups指令顺序: fence、 交错组wave prioritywave 优先级register use寄存器使用null control空白对照

Each bar is the speed ratio over all timed and new shapes. The black line is the 95% interval over the six ABBA pairs. The two register rows show the only two shapes that this arm changes. A cross means that the tests of FlyDSL or the correctness check rejected the output.

每根条是所有计时 shape 和新 shape 上的速度比。 黑线是 6 组 ABBA 的 95% 区间。 两行寄存器结果是这个 arm 唯一会改变的两个 shape。 叉号表示 FlyDSL 的测试或正确性检查拒绝了输出。

KernelKernelWhat we removed去掉了什么Speed ratio [95% interval]速度比 [95% 区间]ISA at the largest shape最大 shape 的 ISA
gemm.preshuffle-a8fences + interleave groupsfence + 交错组0.882× [0.879, 0.885]VGPR 190→220, spills 0→0VGPR 190→220, spill 0→0
gemm.preshuffle-a8interleave groups only只去交错组0.883× [0.880, 0.886]VGPR 190→156, spills 0→0VGPR 190→156, spill 0→0
gemm.mx-preshuffle-a8w8fences + interleave groupsfence + 交错组0.947× [0.946, 0.949]VGPR 216→216, spills 0→0VGPR 216→216, spill 0→0
attention.swa-gqafences + interleave groupsfence + 交错组0.840× [0.839, 0.842]VGPR 246→256, spills 0→4VGPR 246→256, spill 0→4
gemm.a16w16fencesfencewrong · 1/880 tests错误 · 1/880 测试VGPR 232→254, spills 0→12VGPR 232→254, spill 0→12
gemm.a16w16fences (repeat)fence(重复)wrong · 1/880 tests错误 · 1/880 测试VGPR 232→254, spills 0→12VGPR 232→254, spill 0→12
attention.flash-fwd-densefences + interleave groupsfence + 交错组wrong · 28/1039 tests错误 · 28/1039 测试VGPR 246→250, spills 0→0VGPR 246→250, spill 0→0
attention.flash-fwd-denseinterleave groups only只去交错组0.990× [0.989, 0.991]VGPR 246→242, spills 0→0VGPR 246→242, spill 0→0
gemm.fp8-rowscale-8waves_setprios_setprio0.862× [0.860, 0.864]VGPR 255→256, spills 0→6VGPR 255→256, spill 0→6
gemm.mxfp8-8waves_setprios_setprio0.902× [0.900, 0.904]VGPR 256→256, spills 3→7VGPR 256→256, spill 3→7
attention.flash-fwd-denses_setprios_setprio0.998× [0.997, 0.999]VGPR 246→246, spills 0→0VGPR 246→246, spill 0→0
attention.flash-fwd-densethe setting that turns off the post-RA scheduler关掉 post-RA 调度器的设置1.006× [1.004, 1.008]VGPR 246→246, spills 0→0VGPR 246→246, spill 0→0
gemm.fp8-rowscale-4waveAGPR pin (inline assembly)AGPR pin(inline 汇编)0.983× [0.978, 0.989]VGPR 512→512, spills 10→92VGPR 512→512, spill 10→92
gemm.fp8-rowscale-4waveoccupancy hintsoccupancy 提示1.000× [0.997, 1.003]ISA identicalISA 完全相同
norm.rmsnorm-fwdnothing (null control)无(空白对照)1.004× [1.001, 1.007]ISA identicalISA 完全相同
gemm.a16w16nothing, lines added (null control)无, 只加了那几行代码(空白对照)0.998× [0.993, 1.002]ISA identicalISA 完全相同

Result 1: the decisions of the author give 5–16%, and LLVM does not find this speed

结果 1: 作者的决策值 5–16%, LLVM 找不到这部分速度

Without the fences and interleave groups, the preshuffle GEMM became 12% slower (0.882×). The MX preshuffle GEMM became 5% slower, and the sliding-window attention became 16% slower. In the preshuffle GEMM, the interleave groups cause all of the loss. Without only the groups, the speed ratio is 0.883×, the same as without all hints.

去掉 fence 和交错组之后, preshuffle GEMM 慢了 12%(0.882×)。 MX preshuffle GEMM 慢了 5%, 滑窗 attention 慢了 16%。 在 preshuffle GEMM 里, 全部损失都来自交错组: 只去掉交错组时速度比是 0.883×, 和去掉全部提示一样。

Without s_setprio, the two 8-wave GEMMs became 14% and 10% slower. For the first one, the ISA shows more than a priority change: the kernel got VGPR spills, and it had no spills before.

去掉 s_setprio 之后, 两个 8-wave GEMM 分别慢了 14% 和 10%。 对第一个 kernel, ISA 显示的不只是优先级变化: 原来没有 spill, 现在出现了 VGPR spill。

In the FP8 4-wave GEMM, we let LLVM assign the registers of the accumulators, instead of the AGPR pins of the author. The kernel became 14% slower at 16384³ and 9% slower at 8192³. The spills went from 10 to 92, and the moves between AGPRs and VGPRs went from 796 to 6,437. The ISA also shows a fact that nobody had reported: even the pinned kernel has 10 spills at that size.

在 FP8 4-wave GEMM 里, 我们让 LLVM 来分配累加器的寄存器, 不再使用作者的 AGPR pin。 kernel 在 16384³ 上慢了 14%, 在 8192³ 上慢了 9%。 spill 从 10 个增加到 92 个, AGPR 和 VGPR 之间的搬运指令从 796 条增加到 6,437 条。 ISA 还显示了一个之前没人报告过的事实: 即使用了 pin, 这个尺寸上也有 10 个 spill。

Without the occupancy hints of the same kernel, nothing changed. The ISA was the same at both shapes, so the default of LLVM already matched the hints. A hint with no effect does no harm. But no tool tells the author or the agent that the hint has no effect.

去掉同一个 kernel 的 occupancy 提示后, 什么都没变。 两个 shape 上的 ISA 完全相同, 说明 LLVM 的默认值本来就和这些提示一致。 没有效果的提示不会造成损害, 但没有任何工具告诉作者或 agent 它没有效果。

Result 2: in two kernels, the "scheduling" fences kept the results correct

结果 2: 两个 kernel 的"调度" fence 在保证结果正确

Without the fences, the A16W16 GEMM failed 1 of 880 FlyDSL tests. The dense flash attention failed 28 of 1039 tests: some log-sum-exp values (a value for each row that attention saves for later steps) were off by up to 0.43, and some outputs were NaN (not a number).

去掉 fence 之后, A16W16 GEMM 在 FlyDSL 的 880 个测试里失败了 1 个。 dense flash attention 的 1039 个测试里失败了 28 个。 部分 log-sum-exp 值(attention 为后续步骤保存的每行数值)最多差 0.43, 部分输出是 NaN(无效数值)。

We repeated the A16W16 arm in a new job. The same test failed, but with different wrong elements: 182 and 31 of 163,840. A rounding error gives the same wrong elements in each run. A race gives different ones. With the added lines but nothing removed, the same kernel passed all of its tests (null control, 0.998×).

我们在新作业里重复了 A16W16 这个 arm。 失败的是同一个测试, 但错的元素不同: 163,840 个元素里分别错了 182 个和 31 个。 舍入误差每次错的是同样的元素, 竞争每次错的元素不同。 加了那几行代码、 但什么都不去掉时, 同一个 kernel 通过了全部测试(空白对照, 0.998×)。

A scheduling hint should change only the speed. Here it changed the results. We did not find which instruction moved.

But the kernels show the probable cause. They control the order of memory copies and shared-memory reuse with waits and barriers that the author placed by hand. LLVM does not connect these waits and barriers to the reads that they protect. A FlyDSL comment in another kernel describes this risk: "the scheduler may hoist them above s_barrier: a race" (mega_moe_tp/gemm.py).

调度提示本应只改变速度, 这里却改变了结果。 我们没有找出具体是哪条指令被移动了。

但 kernel 本身指出了可能的原因: 它们用作者手工放置的 wait 和 barrier 来控制内存拷贝和共享内存复用的顺序。 LLVM 不会把这些 wait 和 barrier 与它们保护的读取联系起来。 FlyDSL 另一个 kernel 的注释写的正是这种风险: "调度器可能把它们提到 s_barrier 之前: 这是竞争"(mega_moe_tp/gemm.py)。

In the flash attention, we also removed only the interleave groups and kept the fences. The kernel stayed correct, at 0.990× [0.989, 0.991]. Thus the fences, not the groups, keep the results correct.

在 flash attention 里, 我们还试了只去掉交错组、 保留 fence。 kernel 的结果仍然正确, 速度比是 0.990× [0.989, 0.991]。 所以保证结果正确的是 fence, 不是交错组。

This is the most important result of this post, and it is not about speed. Today, an autotuner or an agent cannot safely change a scheduling hint, because some of these hints are correctness rules that look like speed hints.

这是本文最重要的结果, 而且它和速度无关。 今天, autotuner 或 agent 不能放心地修改调度提示, 因为其中一些提示看起来是为了速度, 实际上是保证正确性的规则。

Result 3: on single shapes, the free order of LLVM is sometimes better

结果 3: 在单个 shape 上, LLVM 的自由排序有时更好

The same preshuffle arm is 12% slower in total. But it is 3.4% faster at 16384³ and 2.1% faster at 8192³. Thus the interleave pattern of the author is a good fixed rule, but it is not the best rule for each shape. Plate V shows this for all public shapes.

同一个 preshuffle arm 整体慢了 12%, 但在 16384³ 上快了 3.4%, 在 8192³ 上快了 2.1%。 所以作者的交错模板是一个不错的固定规则, 但不是每个 shape 上最好的规则。 Plate V 显示了所有公开 shape 的情况。

Result 4: two small effects on the flash attention

结果 4: flash attention 上的两个小效果

Without s_setprio, the flash attention ran at 0.998× [0.997, 0.999] in total. But it was up to 4.3% slower on single shapes, and 5 shapes were slower by more than their noise level.

去掉 s_setprio 后, flash attention 整体速度比是 0.998× [0.997, 0.999]。 但在单个 shape 上最多慢 4.3%, 有 5 个 shape 的变慢超出了噪声下限。

The author of this kernel turned off the post-RA scheduler of LLVM to protect the order that the author wrote (flash_attn_gfx950.py). The post-RA scheduler is a second LLVM step that changes the instruction order after register assignment. When we turned it on again, the kernel ran at 1.006× [1.004, 1.008]. No shape was slower by more than its noise level, and the best shape was 6.7% faster. The ISA has 22 fewer s_nop instructions (185 → 163). An s_nop is an empty instruction that fills a hazard gap.

这个 kernel 的作者关掉了 LLVM 的 post-RA 调度器, 用来保护作者写下的顺序(flash_attn_gfx950.py)。 post-RA 调度器是 LLVM 在分配寄存器之后再调整一次指令顺序的步骤。 我们重新打开它之后, kernel 的速度比是 1.006× [1.004, 1.008]。 没有 shape 的变慢超出噪声下限, 最好的 shape 快了 6.7%。 ISA 里少了 22 条 s_nop(185 → 163)。 s_nop 是填充 hazard 间隔的空指令。

This gain is about the size of the 0.5% noise level of this kernel. Thus FlyBench would not count it as an improvement. The author could not see if this setting helps. The notes of FlyDSL say that three related flash attention kernels use different values for this setting, with no comment (arch-gfx950.md).

这个收益和这个 kernel 0.5% 的噪声下限差不多大, 所以 FlyBench 不会把它算作提升。 作者看不到这个设置到底有没有帮助。 FlyDSL 自己的笔记写着: 三个相关的 flash attention kernel 在这个设置上取值不同。 这些 kernel 里也没有注释说明原因(arch-gfx950.md)。

08Experiment B · settings that nobody tuned实验 B · 没人调过的设置

What we did. The normalization, softmax and MoE kernels have no hints about instruction order. LLVM makes all of these decisions with its default heuristics. We tried two other LLVM scheduling strategies, max-ilp and max-memory-clause. We also turned off the instruction schedulers of LLVM. The instruction order is then close to the order in the source.

做了什么。 normalization、 softmax 和 MoE 这些 kernel 没有任何关于指令顺序的提示。 这些决策全部由 LLVM 用默认的启发式规则来做。 我们试了 LLVM 另外两种调度策略: max-ilp 和 max-memory-clause。 我们还关掉了 LLVM 的指令调度器, 这时指令顺序接近源码里的顺序。

Plate IV · speed ratio with one LLVM setting that nobody tuned换一个没人调过的 LLVM 设置后的速度比
speed relative to the stock kernel 0.85× 0.90× 0.95× 1.00× 1.05× ← slower than stock ← 比 stock 慢 faster than stock → 比 stock 快 → rmsnorm-fwd · max-memory-clause rmsnorm-fwd · max-memory-clause 1.000× rmsnorm-fwd · max-ilp rmsnorm-fwd · max-ilp 1.002× rmsnorm-fwd · LLVM schedulers off rmsnorm-fwd · 关掉 LLVM 调度器 0.899× layernorm-fwd · max-memory-clause layernorm-fwd · max-memory-clause 1.000× layernorm-fwd · max-ilp layernorm-fwd · max-ilp 1.012× softmax-fwd · max-memory-clause softmax-fwd · max-memory-clause 0.955× softmax-fwd · max-ilp softmax-fwd · max-ilp 0.951× moe.reduce · max-memory-clause moe.reduce · max-memory-clause 1.001× moe gemm1 · max-memory-clause moe gemm1 · max-memory-clause 0.965× moe gemm1 · max-ilp moe gemm1 · max-ilp ✕ one wrong output ✕ 一次输出错误 moe gemm1 · max-ilp (repeat) moe gemm1 · max-ilp(重复) ✕ stock itself failed ✕ stock 自己出错 preshuffle-a8 · max-ilp preshuffle-a8 · max-ilp 1.018× preshuffle-a8 · LLVM schedulers off preshuffle-a8 · 关掉 LLVM 调度器 1.025×

Green: a different amdgpu-sched-strategy. Red: the schedulers of LLVM turned off. A cross means that the evaluator rejected an output. In the repeated MoE run, the rejected output came from the stock kernel. Most bars are inside the noise level of each kernel.

绿色: 换一种 amdgpu-sched-strategy。 红色: 关掉 LLVM 的调度器。 叉号表示评测器拒绝了某次输出。 在 MoE 的重复实验里, 被拒绝的输出来自 stock kernel。 大多数条都在各自 kernel 的噪声下限以内。

KernelKernelSetting设置Speed ratio [95% interval]速度比 [95% 区间]ISA at the largest shape最大 shape 的 ISA
norm.rmsnorm-fwdmax-memory-clausemax-memory-clause1.000× [0.994, 1.006]VGPR 40→40, spills 0→0VGPR 40→40, spill 0→0
norm.rmsnorm-fwdmax-ilpmax-ilp1.002× [0.999, 1.004]VGPR 40→39, spills 0→0VGPR 40→39, spill 0→0
norm.rmsnorm-fwdLLVM schedulers off关掉 LLVM 调度器0.899× [0.896, 0.901]VGPR 40→30, spills 0→0VGPR 40→30, spill 0→0
norm.layernorm-fwdmax-memory-clausemax-memory-clause1.000× [0.996, 1.004]VGPR 60→60, spills 0→0VGPR 60→60, spill 0→0
norm.layernorm-fwdmax-ilpmax-ilp1.012× [1.006, 1.017]VGPR 60→86, spills 0→0VGPR 60→86, spill 0→0
norm.softmax-fwdmax-memory-clausemax-memory-clause0.955× [0.950, 0.959]ISA identicalISA 完全相同
norm.softmax-fwdmax-ilpmax-ilp0.951× [0.949, 0.952]VGPR 45→53, spills 0→0VGPR 45→53, spill 0→0
moe.reducemax-memory-clausemax-memory-clause1.001× [0.995, 1.008]VGPR 65→65, spills 0→0VGPR 65→65, spill 0→0
moe.2stage-gemm1max-memory-clausemax-memory-clause0.965× [0.952, 0.979]VGPR 70→70, spills 0→0VGPR 70→70, spill 0→0
moe.2stage-gemm1max-ilpmax-ilpwrong output输出错误VGPR 70→70, spills 0→0VGPR 70→70, spill 0→0
moe.2stage-gemm1max-ilp (repeat)max-ilp(重复)stock failedstock 出错VGPR 70→70, spills 0→0VGPR 70→70, spill 0→0
gemm.preshuffle-a8max-ilpmax-ilp1.018× [1.014, 1.022]VGPR 190→198, spills 0→0VGPR 190→198, spill 0→0
gemm.preshuffle-a8LLVM schedulers off关掉 LLVM 调度器1.025× [1.021, 1.029]VGPR 190→190, spills 0→0VGPR 190→190, spill 0→0

What we saw.

看到了什么。

  1. For kernels without a hand-written order, the default of LLVM is good. No strategy was faster by more than the noise level on the normalization kernels and the MoE reduce kernel. Without the schedulers, RMSNorm became 10% slower. Thus the automatic mode of a new compiler needs a real scheduler.
  2. For the hand-ordered preshuffle GEMM, the result is different. Without the schedulers of LLVM, it ran at 1.025× [1.021, 1.029], faster than stock. With max-ilp, it ran at 1.018×. But neither result is a clean gain: 3 and 5 shapes became slower by more than the noise level (worst 0.92× and 0.93×). Thus FlyBench would reject both arms. Even with the hints of the author, the heuristic scheduler of LLVM costs this kernel time. An explicit mode, which keeps the order of the author, predicts this result.
  3. The MoE GEMM sometimes returns wrong results, even without a change. With max-ilp, one timed call failed the correctness check (cosine similarity 0.989; the limit is 0.99). We repeated the arm. In the repeat, the stock kernel itself returned a wrong output (cosine similarity 0.977). Thus we cannot blame the setting. The cause is probably a race, but we did not find it. The case shows a different problem: the evaluator catches this bug only in some runs. A race check in the compiler can find this kind of bug before the kernel runs.
  1. 对没有手工排序的 kernel, LLVM 的默认值是好的。 在 normalization 和 MoE reduce kernel 上, 没有哪种策略的提速超出噪声下限。 关掉调度器后, RMSNorm 慢了 10%。 所以新编译器的自动模式需要一个真正的调度器。
  2. 对手工排序的 preshuffle GEMM, 结果不同。 关掉 LLVM 的调度器后, 速度比是 1.025× [1.021, 1.029], 比 stock 快。 用 max-ilp 时是 1.018×。 但两者都不是干净的提升: 分别有 3 个和 5 个 shape 的变慢超出噪声下限(最差 0.92× 和 0.93×), 所以 FlyBench 会拒绝这两个 arm。 即使有作者的提示, LLVM 的启发式调度器仍让这个 kernel 变慢。 保持作者顺序的显式模式预言的正是这个结果。
  3. MoE GEMM 即使不做任何改动, 有时也会返回错误结果。 用 max-ilp 时, 有一次计时调用没有通过正确性检查(余弦相似度 0.989, 门限是 0.99)。 我们重复了这个 arm。 在重复实验里, stock kernel 自己返回了错误的输出(余弦相似度 0.977)。 所以不能怪这个设置。 原因可能是竞争, 但我们没有找到。 这个例子说明了另一个问题: 评测器只能在部分运行里抓到这个 bug。 编译器里的竞争检查能在 kernel 运行之前发现这类 bug。
Plate V · preshuffle-a8, shape by shape: no single order wins on all shapespreshuffle-a8 逐个 shape 看: 没有哪种顺序在所有 shape 上都赢
per-shape speed of each arm on preshuffle-a8 0.75× 0.80× 0.85× 0.90× 0.95× 1.00× 1.05× 1.10× 1.15× 4 8 13 14 20 39 128 286 public shapes, sorted by stock time (µs) 公开 shape, 按 stock 耗时排序(µs)

no fences or groups去掉 fence 和交错组no groups去掉交错组max-ilpmax-ilpLLVM schedulers off关掉 LLVM 调度器

Each dot is one public shape in one arm. 1.0 is the stock kernel. For each shape, pick the best of these four arms and stock. Then the 32 public shapes get 1.041× on average (geometric mean). If we count an arm only where its interval is above 1.0, and use only the lower end of the interval, they get 1.027×.

每个点是一个公开 shape 在一个 arm 下的速度比。 1.0 是 stock kernel。 为每个 shape 在这四个 arm 和 stock 之间选出最好的一个, 32 个公开 shape 平均得到 1.041×(几何平均)。 如果只在区间整体高于 1.0 时才计入某个 arm, 并且只计区间的下限, 平均得到 1.027×。

This choice for each shape gives the minimum gain that a search over safe order settings can find in this one kernel. Today, this search is not safe in kernels where the fences keep the results correct (experiment A).

这种按 shape 的选择, 给出了在这一个 kernel 里搜索安全的顺序设置所能得到的最小收益。 今天, 在 fence 保证结果正确的 kernel 里, 这种搜索并不安全(见实验 A)。

09Experiment C · what agents did in 671 attempts实验 C · agent 在 671 次尝试里做了什么

What we did. The overlay has already run FlyBench many times. In each run, an agent gets one FlyDSL kernel and a time limit. It must make the kernel faster and keep the same results.

We read all the records that still exist. These are 98 runs with 671 attempts, 676 evaluator receipts, 89 independent reviews of the best patches and 827 command logs with 285,091 commands. We publish only totals.

做了什么。 overlay 已经跑过很多次 FlyBench。 每次运行中, agent 拿到一个 FlyDSL kernel 和一个时间限制, 要在结果不变的前提下让 kernel 变快。

我们读了所有留存下来的记录。 其中有 98 次运行(共 671 次尝试)、 676 张评测回执、 89 份对最好补丁的独立 review, 以及 827 份命令记录(共 285,091 条命令)。 我们只公开汇总数据。

Plate VI · where the accepted speedups came from, and what agents spent their commands on被认可的提速来自哪里, 以及 agent 把命令花在了什么上

Share of the 39 reviews that accept the speedup, by the source that each review names. One patch can name more than one source.

在 39 份认可提速的 review 里, 提到每种来源的比例。 一个补丁可以有多个来源。

bar chart wider memory access 更宽的访存 74% tile choice per shape 按 shape 选 tile 56% new algorithm 新算法 44% more work splits 更多工作切分 44% order setting 顺序设置 8% register setting 寄存器设置 5%

Share of all 285,091 commands, by purpose. Most of the other commands run scripts.

全部 285,091 条命令按用途的比例。 其余命令大多是运行脚本。

bar chart edit code 改代码 25.9% read code 读代码 12.4% own timing, profiling 自己测时、 profile 7.6% read IR or ISA 读 IR 或 ISA 4.0% run ./evaluate 跑 ./evaluate 3.6% clear the compile cache 清编译缓存 3.3% run tests 跑测试 1.4%

Where the speedups come from. The accepted speedups have a median of 1.46×, as reproduced by the reviewer. They come from four kinds of change: wider memory access, a tile choice per shape, more work splits, and new algorithms. These changes are work split, data movement and instruction choice, the decisions that the author already makes. Order settings and register settings appear in only 8% and 5% of the reviews.

Thus the redesign must keep what agents use: Python metaprogramming, layout algebra and atoms (ready-made blocks for copies and matrix instructions). It does not give agents a new source of speed.

提速来自哪里。 被认可的提速经 review 复现, 中位数是 1.46×。 它们来自四类改动: 更宽的访存、 按 shape 选择 tile、 更多的工作切分以填满 GPU, 以及新算法。 这些都属于工作划分、 数据搬运和指令选择, 也就是作者本来就在做的决策。 顺序设置和寄存器设置分别只出现在 8% 和 5% 的 review 里。

所以重新设计必须保留 agent 用到的东西: Python 元编程、 layout 代数和 atom(现成的拷贝和矩阵指令模块)。 它不会给 agent 带来新的提速来源。

Where the effort goes. A median attempt used 53.5M prompt tokens, 318 turns and 1.3 hours. In 69% of the 827 command logs, the agent read the IR or the ISA at least once. In 65%, it cleared the FlyDSL compile cache at least once (9,531 times in total). Agents do this when they cannot tell if the code that ran is the code that they wrote.

The most common failure in the reviews was a slower result on shapes that the agent did not time (35 of 89 reviews). A few reviews found problems that a compiler can find before the run. Some were correctness bugs, for example a missing barrier and an out-of-bounds read. Others were spills, for example a spill setting that made one shape 0.44× as fast. Nine reviews say that agents added their own launch caches to avoid the trace at each call.

精力花在哪里。 按中位数计, 一次尝试用了 53.5M prompt token、 318 轮对话、 1.3 小时。 在 827 份命令记录里, 有 69% 显示 agent 至少读过一次 IR 或 ISA。 有 65% 显示 agent 至少清过一次 FlyDSL 编译缓存(总共 9,531 次)。 agent 在无法确认 "运行的代码是不是自己写的代码" 时, 就会这样做。

review 里最常见的失败, 是 agent 没有计时的 shape 变慢了(89 份里有 35 份)。 少数 review 发现了编译器在运行前就能发现的问题。 有些是正确性 bug, 例如漏掉的 barrier 和越界读取。 有些是 spill, 例如一个让某个 shape 只剩 0.44× 速度的 spill 设置。 有 9 份 review 提到, agent 为了避开每次调用的 trace, 自己加了启动缓存。

What agents need from the compiler is mostly what the report and the checks of the redesign give:

  • registers, spills and occupancy for each shape, before a GPU run;
  • the waits that the compiler added, and the reason for each wait;
  • a race check and a bounds check for shared memory;
  • a correct cache key;
  • a launch path without a new trace.

None of these needs MLIR or the heuristics of LLVM. They need a compiler that is responsible for its own decisions.

agent 需要编译器提供的东西, 大多正是重新设计里的报告和检查能给的:

  • 上 GPU 运行之前, 就知道每个 shape 的寄存器、 spill 和 occupancy;
  • 编译器插入了哪些 wait, 以及每个 wait 的原因;
  • 共享内存的竞争检查和越界检查;
  • 正确的缓存 key;
  • 不需要重新 trace 的启动路径。

这些都不需要 MLIR, 也不需要 LLVM 的启发式规则。 它们需要的是一个对自己的决定负责的编译器。

10Experiment D · the compile cost before each launch实验 D · 每次启动前的编译开销

What we did. We measured the compile time on the CPU with FlyDSL 0.5.2. We compiled for gfx950 (MI355X) and did not run the kernels. We ran each case three times, and the runs were within 1% of each other.

做了什么。 我们在 CPU 上用 FlyDSL 0.5.2 测量编译时间。 目标是 gfx950(MI355X), 只编译, 不运行 kernel。 每种情况跑 3 次, 3 次结果相差在 1% 以内。

Plate VII · the parts of a cold compile, and the cost of a call on a cache hit冷编译由哪几部分组成, 以及命中缓存时一次调用的开销
cold compile time by stage 0.0 s 0.5 s 1.0 s 1.5 s 2.0 s 2.5 s 3.0 s trace + print trace + 打印 MLIR steps MLIR 步骤 LLVM backend LLVM 后端 a cached call 命中缓存的一次调用 vectorAdd 0.06 s 8 ms preshuffle FP8 GEMM 0.18 s 24 ms fp8_gemm_4wave 256×256 2.71 s 964 ms flash_attn_gfx950 D128 0.77 s 162 ms

Each bar shows the parts of one cold compile. The red line under each bar shows the time of one call on a cache hit.

每根条显示一次冷编译的各个部分。 每根条下面的红线, 是命中缓存时一次调用的时间。

KernelKernelCold compile冷编译Trace + printtrace + 打印MLIR stepsMLIR 步骤LLVM backendLLVM 后端Call on a cache hit命中缓存的一次调用Objects built → kept建出的对象 → 留下的
examples/01-vectorAdd0.06 s0.02 s0.01 s0.01 s8 ms110 → 109
preshuffle FP8 GEMM0.18 s0.02 s0.04 s0.09 s24 ms956 → 1,718
fp8_gemm_4wave 256×2562.71 s0.95 s0.29 s1.15 s964 ms61,989 → 9,907
flash_attn_gfx950 D1280.77 s0.16 s0.09 s0.46 s162 ms7,508 → 4,317

What we saw. The LLVM backend is the largest part of a cold compile: 42–60% for the GEMM and the attention kernel. The MLIR steps are small. For an agent, the trace is the important cost, because it comes at each call. It also comes on a cache hit: 0.96 s per call for the FP8 GEMM and 162 ms for the attention kernel. Each new test process also spends about 0.7 s to import FlyDSL.

看到了什么。 LLVM 后端是冷编译里最大的一块: 在 GEMM 和 attention kernel 上占 42–60%。 MLIR 步骤占比很小。 对 agent 来说, 重要的是 trace, 因为每次调用都要付这笔时间。 命中缓存也一样: FP8 GEMM 每次调用 0.96 s, attention kernel 162 ms。 另外, 每个新的测试进程还要花约 0.7 s 导入 FlyDSL。

11What the results mean结果说明了什么

  • Premise A is true, and stronger than we expected. In most arms that changed the code, removing one decision of the author cost 5–16% of speed. The heuristics of LLVM did not find this speed. In two of the five kernels whose fences we removed, the fences kept the results correct.
  • Premise B is partly true. Where nobody ordered the instructions by hand, the default of LLVM is good, and an automatic mode needs a scheduler like it. Where an author did, the heuristic of LLVM still costs time. A choice of order for each shape gives 2.7–4.1% on the one kernel that we measured.
  • Premise C is true, with a correction. Agents frequently read compiler output, and they do not trust the compile cache. But their speedups come from decisions that they already make.
  • Premise D is true. The trace costs time in each iteration.
  • 前提 A 成立, 而且比预想的更强。 在大多数改变了代码的 arm 里, 去掉作者的一个决策会损失 5–16% 的速度。 LLVM 的启发式规则找不到这部分速度。 在我们去掉 fence 的五个 kernel 里, 有两个的 fence 在保证结果正确。
  • 前提 B 部分成立。 在没人手工排序的地方, LLVM 的默认值是好的, 自动模式需要一个这样的调度器。 在作者手工排序的地方, LLVM 的启发式规则仍让 kernel 变慢。 在我们测的这一个 kernel 上, 按 shape 选择顺序能带来 2.7–4.1%。
  • 前提 C 成立, 但要修正。 agent 经常读编译器输出, 也不信任编译缓存。 但它们的提速来自本来就由它们做的决策。
  • 前提 D 成立。 trace 在每次迭代里都要花时间。

So, can the redesign make kernels much faster? Not every kernel. The large, measured effect is in expert kernels whose authors already override LLVM. There, a compiler that always keeps the explicit order, pins and waits protects the 5–16% that these decisions give. It also makes a search over order settings safe.

For simple kernels, the speed will stay about the same. The scheduler of LLVM is a good automatic mode until a new scheduler is as good. For agents, the larger gain is fewer wasted iterations, not a higher peak speed. Fewer runs only decode ISA or clear caches. Compile errors replace silent wrong results.

那么, 重新设计能不能让 kernel 快很多? 不是每个 kernel 都能。 实测到的大效果在专家 kernel 上, 这些 kernel 的作者本来就在覆盖 LLVM 的决定。 在那里, 一个始终遵守显式顺序、 pin 和 wait 的编译器, 能保住这些决策带来的 5–16%, 也让顺序设置的搜索变得安全。

对简单 kernel, 速度基本不会变。 在新调度器达到同样水平之前, LLVM 的调度器是一个好的自动模式。 对 agent 来说, 更大的收益是浪费的迭代更少, 而不是峰值速度更高。 只为解读 ISA 或清缓存的运行会更少。 原本不报错的错误结果会变成编译错误。

12What could prove us wrong什么会推翻这个结论

  • An explicit-order backend that is slower. Build KIR and the new backend for one GEMM. Use the FP8 4-wave GEMM, because all of its decisions are explicit. Compare its speed with the output of LLVM for the same source decisions. If the order of the author, with the pins kept, is slower than LLVM, then the scheduler of LLVM must stay in the explicit mode.
  • Agents that do not use the report. On the overlay, run the same FlyBench records with two arms. The only difference is a report command in one arm. The report gives registers, spills and occupancy for each shape, the waits, and the race and bounds checks. If the number of 1.2× results, the slower shapes and the tokens per record do not change, then the agent part of the argument is wrong.
  • Correctness fences that are rare. We found them in two of the five kernels whose fences we removed. A scan of all kernels, with one fence removed at a time, will show how common they are. If they are rare, waits based on tokens are less important than this post says.
  • 显式顺序的后端更慢。 为一个 GEMM 实现 KIR 和新后端。 选 FP8 4-wave GEMM, 因为它的决策全是显式的。 在源码决策相同的条件下, 和 LLVM 的输出比较速度。 如果 "作者的顺序加保留的 pin" 比 LLVM 慢, 那么显式模式下仍要保留 LLVM 的调度器。
  • agent 不用报告。 在 overlay 上用同样的 FlyBench record 跑两个 arm, 唯一的区别是其中一个有 report 命令。 报告给出每个 shape 的寄存器、 spill 和 occupancy, 插入的 wait, 以及竞争和越界检查。 如果达到 1.2× 的结果数、 变慢的 shape 数和每个 record 的 token 数都不变, 论证里关于 agent 的部分就是错的。
  • 保证正确性的 fence 其实很少。 在我们去掉 fence 的五个 kernel 里发现了两个。 对所有 kernel 每次去掉一个 fence 扫一遍, 就能知道它们有多常见。 如果很少, 基于 token 的 wait 就没有本文说的那么重要。

13Reproduce复现

All the numbers in this post come from the files in data/flydsl-compiler-redesign:

本文所有数字都来自 data/flydsl-compiler-redesign 里的文件:

The directory also has the 29 patches (patches/) and the scripts that built and summarized them (scripts/). scripts/make_page.py builds this page. Internal paths are replaced by placeholders. Each patch applies to FlyDSL cb770e9a, and the FlyBench v1 evaluator scores it on one MI355X.

目录里还有 29 个补丁(patches/)和构建、 汇总它们的脚本(scripts/)。 scripts/make_page.py 生成本页。 内部路径已经换成占位符。 每个补丁都可以打到 FlyDSL cb770e9a 上, 由 FlyBench v1 评测器在一张 MI355X 上打分。

14Epilogue结语

I started this work to show that LLVM is the problem. The experiments show something narrower and more useful. The heuristics of LLVM are good for the decisions that nobody makes. The problems start when an author makes these decisions, and the compiler cannot tell a speed preference from a correctness rule.

A compiler for agents must keep this difference clear. Each decision has one decider. Each rule is visible as data. The compiler writes down each choice where the agent can read it.

开始这项工作时, 我想证明 LLVM 是问题所在。 实验给出的结论更窄, 也更有用。 LLVM 的启发式规则很擅长做没人去做的决定。 问题出在作者做了这些决定, 而编译器分不清哪些是速度上的偏好, 哪些是正确性上的规则。

给 agent 用的编译器必须把这个区别保持清楚: 每个决策只有一个决策者; 每条规则都以数据的形式可见; 编译器做出的每个选择都写在 agent 读得到的地方。