使用 SGLang-TorchTPU 在 TPU v7 上优化 Muse Spark Open
原题Optimizing Muse Spark Open on TPU v7 with SGLang-TorchTPU
读前速览
本文详细介绍 PyTorch 的 TorchTPU 与 SGLang 如何借助巨核架构,在 TPU v7 上为 Meta 的 816B 参数 Muse Spark Open MoE 模型实现高性能推理;该架构通过流水化处理权重、KV 缓存和集合通信,将解码延迟减半。
巨核架构
每台设备将解码或验证步骤中的全部 62 层作为单个 Pallas 程序运行,消除会中断权重流式读取的程序边界,从而实现从 HBM 到 MXU 的连续数据流。
集合通信折叠
将 all-gather 操作折叠进矩阵乘法,使投影计算能够在数据分片到达时立即开始,而不必等待完整的 gather;同时利用 RMS norm 的标量因子可与矩阵乘法交换这一特性。
无最大值注意力循环
通过使用分数有界的 QK 归一化注意力(最大绝对值为 43.8),消除了在线 softmax 中的运行最大值,使各数据块能够独立处理,并在微基准测试中实现 3.9× 的注意力加速。
双循环专家处理
按行数对专家排序,并通过两个独立循环处理,避免处理常见的少行数情况时,负载较重的 8 行变体造成寄存器溢出,使解码延迟降低 13–19%。
KV 写入流水线化
专用内核同时发起所有层的分页读取,并利用双 VMEM 缓冲区让读写操作重叠;在 16 行时,写入耗时从 810 µs 降至 155 µs。
完整摘要
这篇博客介绍如何使用 SGLang-TorchTPU,在一台配备 4 个芯片的 TPU v7 主机上运行 Meta 的 816B 参数 Muse Spark Open 混合专家模型并进行优化。核心创新是一个巨核,它将全部 62 个解码器层作为单个 Pallas 程序执行,从而能够持续从 HBM 流式读取权重,并让数据传输与计算重叠。关键技术包括:将集合通信折叠进计算,以流水化处理 all-gather 操作;采用无最大值注意力循环,打破在线 softmax 中的串行依赖;以及通过双循环处理专家,减少寄存器溢出。该系统使单请求解码速度提升 1.94×,并能以每芯片 25,906 tokens/s 处理 1M 上下文轨迹,验证步骤耗时不超过权重流式读取时间的 1.5–1.7×。
目录 · 32 节
我们在一台配备四颗芯片的 TPU v7 主机上,使用运行于 TorchTPU PyTorch 后端的 SGLang,为 Meta 的 Muse Spark Open(一个拥有 816B 参数的混合专家模型)提供服务。核心是一个巨核:解码或验证步骤中的全部 62 层都作为一个 Pallas 程序运行,所有权重加载、KV 读取和跨设备传输都与计算流水重叠。其余工作分为三组:加快解码步骤(集体通信折叠、无需取最大值且能流水处理 KV 块的注意力循环、让寄存器溢出避开常见路径的专家循环,以及 DFlash2 推测解码);增加每颗芯片的 KV 缓存容量(巨核中的序列在线 KV 布局,以及 TPU 上支持按会话感知淘汰的 L2 HiCache);加快预填充(融合 MoE 内核和序列并行)。We serve Meta’s Muse Spark Open, an 816B-parameter mixture-of-experts model, on a single TPU v7 host of four chips, with SGLang running on the TorchTPU PyTorch backend. At the center is a megakernel: all 62 layers of a decode or verify step run as one Pallas program, and every weight load, KV read and cross-device transfer is pipelined behind compute. The rest of the work falls into three groups: faster decode steps (collective folding, a max-free attention loop that pipelines its KV chunks, an expert loop that keeps register spills off its common path, and DFlash2 speculative decoding), more KV cache per chip (sequence-on-lane KV layout in the megakernel, and L2 HiCache on TPU with session-aware eviction), and faster prefill (a fused MoE kernel and sequence parallelism).
- 解码速度。在最能发挥作用的场景下,megakernel 可将一到两个并发请求的每个输出 token 耗时减半;随着并发量增加,收益会逐渐缩小。其验证步骤的耗时仅为单纯从 HBM 流式读取权重所需时间的 1.5–1.7 倍。Decode speed. The megakernel halves the time per output token for one or two concurrent requests, where it helps the most; the gain narrows as concurrency grows. Its verify step runs within 1.5–1.7× of the time it takes just to stream its weights from HBM.
- AgentX。在 SemiAnalysis 的智能体编程基准测试的 100 万上下文版本中,我们的曲线从每个请求 433 输出 tokens/s(每个芯片 6,101 tokens/s),延伸至每个请求 95 tokens/s(每个芯片 25,906 tokens/s)(图 1)。AgentX. On the 1M-context version of SemiAnalysis’s agentic-coding benchmark, our curve runs from 433 output tokens/s per request at 6,101 tokens/s per chip to 25,906 tokens/s per chip at 95 tokens/s per request (Figure 1).
结果Results

图 1. InferenceX AgentX,1M 上下文轨迹集:每美元 token 数与 p90 交互性。TPU v7:单主机、四颗芯片,采用 FP8 计算和 NVFP4 专家权重。GB200(FP4)作为基线,数据来自 InferenceX 截至 2026-11-02 发布的结果。成本为 InferenceX 的外部持有成本:TPU v7 每芯片小时 1.21 美元,GB200 每 GPU 小时 1.86 美元。Figure 1. InferenceX AgentX, 1M-context trace set: tokens per dollar against p90 interactivity. TPU v7: one host, four chips, FP8 compute with NVFP4 expert weights. GB200 (FP4) is shown as a baseline from InferenceX’s published results as of 2026-11-02. Costs are InferenceX’s external owning costs: $1.21 per TPU v7 chip-hour and $1.86 per GB200 GPU-hour.
AgentX 基于 393 个自愿参与的 Claude Code 会话构建。它会重放请求长度、轮次间的前缀共享、工具调用暂停和子代理结构,并用合成 token 替代原始内容。与 GB200 基准测试一样,我们运行其 1M 上下文跟踪集,其中提示词长度可达约 990K 个 token;上下文窗口较短的模型则运行上限为 256K 的版本。吞吐量按输入和输出 token 计。图 1 中的每个 TPU 数据点都能在 p90 下于 47 秒内完成请求。AgentX is built from 393 opt-in Claude Code sessions. It replays their request lengths, prefix sharing between turns, tool pauses and subagent structure, with synthetic tokens in place of the original content. We run its 1M-context trace set, as the GB200 baseline does, where prompts reach about 990K tokens; models with shorter context windows run a version capped at 256K. Throughput counts input and output tokens. Every TPU point in Figure 1 finishes requests within 47 s at p90.
背景Background
该模型The model
Muse Spark Open 是 Meta 的开放权重混合专家(MoE)[1] 模型,总参数量为 8160 亿,每个 token 激活约 420 亿个参数。Muse Spark Open is Meta’s open-weights mixture-of-experts (MoE) [1] model, with 816B parameters in total and about 42B active per token.
- 62 个解码器层,全部都是 MoE。每一层都会将每个 token 路由到 256 个专家中的 8 个。62 decoder layers, all of them MoE. Each layer routes every token to 8 of 256 experts.
- 混合注意力。46 层采用滑动窗口注意力 [2],关注最近的 2,048 个 token;另外 16 层关注完整上下文,最多可达 1M 个 token。注意力机制包含 128 个查询头和 16 个 KV 头,每个头的维度为 64。Hybrid attention. 46 layers use sliding-window attention [2] over the last 2,048 tokens; the other 16 attend over the full context, up to 1M tokens. Attention has 128 query heads and 16 KV heads, each 64 wide.
- NVFP4 专家。专家权重为 4 位,每 16 个值对应一个缩放因子,采用微缩放格式 [3]。NVFP4 experts. Expert weights are 4-bit, with one scale per 16 values, a microscaling format [3].
硬件The hardware
一台 TPU v7(Ironwood)主机包含四颗芯片。每颗芯片集成两个芯粒,每个芯粒各有一个 TensorCore 和独立的 HBM;框架会将每个芯粒作为一个设备暴露出来,因此一台主机有 8 个设备。我们使用张量并行 [4] 将模型切分为 8 份,每个设备对应一份。One TPU v7 (Ironwood) host has four chips. Each chip packs two chiplets, each with one TensorCore and its own HBM, and frameworks expose each chiplet as a device, so a host has 8 devices. We shard the model 8 ways with tensor parallelism [4], one shard per device.

图 2. 单个 TPU v7 芯片,根据 Google Cloud 的 TPU7x 文档中的架构图简化而来。数据为 Google 公布的数值。Figure 2. One TPU v7 chip, simplified from the architecture diagram in Google Cloud’s TPU7x documentation. The numbers are Google’s published figures.
每台设备都是单线程处理器:一次只运行一个程序,因此速度取决于让矩阵单元持续获得数据,并在该程序内将内存传输与计算重叠起来。本文将重点介绍这些单元,相关说明见 Google Cloud 的 TPU7x 文档和 JAX 的 Pallas TPU 指南:Each device is a single-threaded processor: one program runs at a time, so speed comes from keeping the matrix units fed and overlapping memory transfers with compute inside that program. These are the units that matter in this post, as described in Google Cloud’s TPU7x documentation and JAX’s Pallas TPU guide:
- 标量单元。每个设备配备一个,并拥有自己的小型标量存储器(SMEM)。它负责执行控制流:循环、分支和地址计算。Scalar unit. One per device, with its own small scalar memory (SMEM). It runs the control flow: loops, branches and address math.
- MXU,即矩阵单元。每个设备有两个。它们负责执行矩阵乘法;芯片的峰值算力在 bf16 下为 2,307 TFLOPs,在 fp8 下为 4,614 TFLOPs。批量较小时,它们大多在等待权重从 HBM 到达。MXU, the matrix unit. Two per device. They do the matmuls; the chip’s peak is 2,307 TFLOPs in bf16 and 4,614 in fp8. At small batch they mostly wait for weights to arrive from HBM.
- 向量单元(VPU)。用于范数、softmax 指数运算和格式转换等逐元素操作。在较新的 TPU 上,它使用 2D 向量寄存器进行计算,每个寄存器包含 8 × 128 个 32 位值,即 8 个子通道、每个子通道 128 个通道。因此,数据布局若导致通道空闲,就会同时浪费向量计算能力和内存(第 7 节)。与之相邻的跨通道单元(XLU)负责转置和置换。Vector unit (VPU). Elementwise work such as norms, softmax exponentials and format conversions. On recent TPUs it computes on 2D vector registers of 8 × 128 32-bit values, 8 sublanes by 128 lanes, so a data layout that leaves lanes empty wastes both vector work and memory (section 7). A cross-lane unit (XLU) next to it does transposes and permutes.
- VMEM。位于 MXU 和向量单元旁边的片上 SRAM,带宽远高于 HBM。内核会将数据块暂存于此,因此其容量限制了内核可同时处理的数据量。VMEM. On-chip SRAM next to the MXUs and the vector unit, with much higher bandwidth than HBM. Kernels stage their tiles here, so its size bounds how much a kernel can keep in flight.
- DMA 引擎。它们在后台于 HBM、VMEM 和其他设备之间传输数据:内核启动一次复制操作,然后继续计算,稍后再等待复制完成。巨型内核的流水线处理(第 2 节)正是建立在这些引擎之上的。DMA engines. They move data between HBM, VMEM and other devices in the background: a kernel starts a copy and waits for it later, while it computes. The megakernel’s pipelining (section 2) is built on them.
- HBM。每颗芯片容量为 192 GiB,带宽为 7.37 TB/s;每个设备上有其中 96 GiB。HBM. 192 GiB per chip at 7.37 TB/s, 96 GiB of it on each device.
- 裸片间链路。它连接芯片中的两个器件;Google 文档称其速度比 1D ICI 链路快六倍。第 8 节的成对交换依赖它。Die-to-die link. It joins the two devices of a chip; Google documents it as six times faster than a 1D ICI link. Section 8’s pair exchange leans on it.
- ICI。每颗芯片有六条链路,每条链路的带宽为 200 GB/s(双向合计),因此每颗芯片的总带宽为 1,200 GB/s。一个主机中的四颗芯片通过 ICI 彼此通信;由 64 颗或更多芯片组成的切片形成三维环面。ICI. Six links per chip at 200 GB/s each, counting both directions, for 1,200 GB/s per chip. The four chips of a host talk to each other over it; slices of 64 chips or more form 3D tori.
- 主机。每颗芯片都通过 PCIe Gen5 ×16 连接到主机的 CPU。配备 4 颗芯片的主机拥有 960 GB DRAM,L2 HiCache 将其用作第二级缓存(第 7 节)。Host. Each chip connects to the host’s CPUs over PCIe Gen5 ×16. A 4-chip host has 960 GB of DRAM, which L2 HiCache uses as a second cache tier (section 7).
- SparseCore。每个芯片有四个。本工作不使用它们。SparseCores. Four per chip. This work does not use them.
TorchTPU 的帖子有一篇更详尽的入门介绍。The TorchTPU post has a longer primer.
该软件The software
服务器是 SGLang-TorchTPU:使用 PyTorch 实现 SGLang [5] 的调度器、KV 缓存和模型代码,并在关键路径上使用 Pallas 内核。我们采用推测解码 [6, 7]:小型草稿模型猜测接下来的几个 token,然后完整模型在一次前向传播中检查所有猜测,这一步称为验证步骤。验证步骤中的每个(请求,位置)对都是一行,因此两个请求各自验证 8 个 token 时,该步骤就有 16 行。The server is SGLang-TorchTPU: SGLang’s [5] scheduler, KV cache and model code in PyTorch, with Pallas kernels on the hot paths. We decode with speculative decoding [6, 7]: a small draft model guesses the next few tokens, and the full model checks them all in one forward pass, the verify step. Each (request, position) pair in a verify step is a row, so two requests verifying 8 tokens each make a 16-row step.
1. 一个巨型内核1. A megakernel
在小批量场景下,每生成一个 token,每个权重对应的计算量都很少,因此只要数据流不中断,单步速度就取决于 HBM 流送权重的速度。所以,解码或验证步骤应当让权重从 HBM 到 MXU 的传输保持连续、不间断。我们之前的执行路径(下文称为“native”)会将每一层拆成多个内核并执行集合通信,而每个边界都会中断数据流。巨型内核会在每台设备上通过一个 Pallas 程序运行单步中的全部 62 层,因此后续权重始终处于传输过程中。此前已有针对 GPU [8, 9] 的整步巨型内核,以及针对 TPU v7 上 Kimi K3 和 Qwen 3.8 的整步巨型内核 [10]。我们的实现运行在 SGLang 的服务路径中,使用其分页式 KV 缓存,可同时处理许多请求的解码步骤和 DFlash2 验证步骤。At small batch, generating a token does little math per weight, so the step is as fast as HBM can stream the weights, as long as nothing interrupts the stream. A decode or verify step should therefore be one uninterrupted stream of weights from HBM into the MXU. Our previous path (“native” below) ran each layer as several kernels plus collectives, and every boundary stopped the stream. The megakernel runs all 62 layers of a step as one Pallas program per device, so the next weights are always in flight. Whole-step megakernels have been built for GPUs [8, 9] and, on TPU v7, for Kimi K3 and Qwen 3.8 [10]. Ours runs inside SGLang’s serving path, on its paged KV cache, for the decode and DFlash2 verify steps of many requests at once.
原生路径已经由融合的 Pallas 块构建而成,但其验证步骤耗时却是流式传输权重所需时间的 2.9 倍。对我们首个单内核原型进行性能分析后,原因一目了然:在 batch size 为 1 时,矩阵乘法和注意力计算几乎不耗时,而每层的集合通信却耗时约 45 µs。程序边界之间无法实现任何重叠,因此该步骤受限于开销,而非带宽。The native path was already built from fused Pallas blocks, yet its verify step took 2.9× the time needed to stream its weights. Profiling our first one-kernel prototype showed why: at batch 1 the matmuls and attention cost almost nothing, while collectives cost about 45 µs per layer. Nothing overlaps across a program boundary, so the step was bound by overhead, not by bandwidth.

图 3. 一个步骤。在 megakernel 内部,每一层都遵循相同的流程(白色);阴影框表示由该内核自行发起的数据移动。Figure 3. One step. Inside the megakernel every layer runs the same flow (white); the shaded boxes are data movement the kernel issues itself.
每个步骤中,每个设备都会运行一次 pallas_call,覆盖全部 62 层和最终归一化。SGLang 仍会在其周围运行嵌入层、草稿模型、小型 KV 写入内核、LM head 和采样。For each step, every device runs one pallas_call that covers all 62 layers and the final norm. SGLang still runs the embedding, the draft model, a small KV-write kernel, the LM head and sampling around it.

图 4. 采用 DFlash2 推测解码时两条路径的每步验证耗时(使用较早的 Muse Spark 检查点测量)。下限为从 HBM 流式传输该步骤所需的不同专家和稠密权重的耗时。Figure 4. Time per verify step, both paths with DFlash2 speculative decoding (GSM8K, measured on an earlier Muse Spark checkpoint). The floor is the time to stream that step’s distinct experts and dense weights from HBM.
每个输出 token 的耗时方面,对于单个请求,megakernel 比原生路径快 1.94 倍(1.95 毫秒对比 3.78 毫秒);对于两个并发请求,则快 1.85 倍。接下来的章节将介绍让单个程序达到如此高速度的原因。Per output token, the megakernel is 1.94× faster than the native path for a single request (1.95 ms against 3.78 ms) and 1.85× for two concurrent requests. The next sections show what made one program this fast.
2. 将巨型内核中的所有操作进行流水线化2. Pipelining everything inside the megakernel
一个步骤主要是数据搬运:在设备之间传输权重、KV 缓存和部分和。整个步骤成为一个程序后,内核便可以安排每次传输,使数据恰好在需要它的计算开始前到达 [11],甚至跨越层边界进行传输 [10]。图 5 示意了其中一层。A step is mostly data movement: weights, KV cache and partial sums between devices. Once the whole step is one program, the kernel can schedule every transfer so that it lands just before the compute that needs it [11], including across layer boundaries [10]. Figure 5 sketches one layer.

图 5. 一个步骤中的一层示意图。每个 DMA 数据流都先于消费它的计算过程运行,或与之并行运行。Figure 5. One layer of a step, schematic. Each DMA stream runs ahead of, or alongside, the compute that consumes it.
权重会在需要之前到达。Weights arrive before they are needed
- 用于密集权重的环形缓冲区。Attention、o-proj 和路由器权重通过一个跨层预取的瓦片环形队列传输。约十个瓦片同时在途,可使每台设备维持 3.34 TB/s 的吞吐量,而单条 DMA 流的吞吐量仅为 1.13 TB/s。A ring for dense weights. Attention, o-proj and router weights stream through a ring of tiles that prefetches across layer boundaries. About ten tiles in flight sustain 3.34 TB/s per device, while a single DMA stream reaches only 1.13 TB/s.
- 路由一结束便请求专家权重。路由器的选择只有到中间层时才会确定,因此路由一结束,内核就会立即请求每个选定专家的权重,并让三个专家的请求同时在途。Experts as soon as routing finishes. The router’s choice is known only mid-layer, so the kernel requests each chosen expert’s weights the moment routing ends, with three experts in flight.
- 专家循环中的下一层。下一层注意力权重的重新加载会等到专家循环运行时才进行,因此不会与当前层正在等待的专家权重争用。The next layer during the expert loop. Refills for the next layer’s attention weights are held until the expert loop runs, so they never compete with the expert weights the current layer is waiting for.
一旦集体的数据存在,集体就会离开。Collectives leave as soon as their data exists
张量并行会在每层中多次在 8 个设备之间交换部分和。与其在每次矩阵乘法后单独执行一次集体通信,不如由内核直接将部分结果写入其所属设备的内存,远程 DMA 则在内核内部发起;一次小规模通信轮次耗时约 3 微秒。Tensor parallelism exchanges partial sums between the 8 devices several times per layer. Instead of a separate collective after each matmul, the kernel writes partial results straight into the owning device’s memory with remote DMAs issued from inside the kernel; a small round costs about 3 µs.
- 流式 o-proj。每个 o-proj 输出块一经计算完成,就立即发送给其所有者,此时下一个块仍在进行乘法运算。Streamed o-proj. Each o-proj output tile leaves for its owner as soon as it is computed, while the next tile is still being multiplied.
流水线式 KV 写入Pipelined KV writes
每一步都会将新的 K 和 V 行写入缓存。在我们的 fp8 sequence-on-lane 缓存(第 7 节)中,一个 token 对应 256-token 页中的一列 lane,因此写入一个 token 意味着将整个页块读入 VMEM,合并新列,然后将页面写回。Each step writes its new K and V rows into the cache. In our fp8 sequence-on-lane cache (section 7), a token is one lane column of a 256-token page, so writing a token means reading the whole page block into VMEM, merging the new columns, and writing the page back.
它会在 megakernel 之后立即作为一个小型内核运行,因为 XLA 会复制任何发起远程 DMA 的内核的别名操作数。它过去会逐页依次执行:读取、等待、合并、写入、等待;每个请求的 62 层中的每一层都如此。This runs as a small kernel right after the megakernel, because XLA copies the aliased operands of any kernel that issues remote DMA. It used to do every page in turn: read, wait, merge, write, wait, for each request and each of 62 layers.

图 6. 示意图。流水线内核一次性发出某一层的所有页面读取请求,每个页面到达时就进行合并,并启动写入;下一层的读取会立即在第二个 VMEM 存储体上开始。Figure 6. Schematic. The pipelined kernel issues all of a layer’s page reads at once, merges each page as it lands, and starts its write; the next layer’s reads start immediately on a second VMEM bank.
新内核一次性加载所有层的新行,然后保留两个 VMEM 缓冲区:第 l 层从一个缓冲区读取时,第 l−1 层的写入从另一个缓冲区排出;只有在早两层的写入落地后,才会重新使用该缓冲区。每步写入耗时在 16 行时从 810 µs 降至 155 µs,在 64 行时从 2,286 µs 降至 336 µs,且结果逐位一致。The new kernel loads all layers’ new rows once, then keeps two VMEM banks: layer l reads into one while layer l−1’s writes drain from the other, and a bank is reused only after the writes of two layers earlier have landed. The write cost per step fell from 810 to 155 µs at 16 rows and from 2,286 to 336 µs at 64 rows, with bit-identical results.
3. 集体折叠3. Collective folding
由于每一层被拆分到 8 台设备上,设备通常必须先收集其他设备的结果才能继续执行。MoE 和注意力运算结束后,每台设备都会持有该层输出在隐藏维度上的一个切片,并且必须通过 all-gather 收集其他七个切片,才能执行下一次矩阵-向量乘法。集体折叠使这次矩阵-向量乘法能够在切片到达时就开始执行,而不必等待整个 gather 完成;分解式集体矩阵乘法也采用了这种做法 [12]。这里,这种做法跨越了两者之间的 RMS 归一化层。Because each layer is split across 8 devices, a device often has to collect the others’ results before it can continue. After the MoE and after attention, each device holds one slice of the layer’s output along the hidden dimension, and must all-gather the other seven slices before the next matvec can run. Collective folding lets that matvec start on the slices as they arrive instead of waiting for the whole gather, as decomposed collective matmuls do [12], here across the RMS norm that sits between the two.

图 7. 示意图。折叠式矩阵-向量乘法会在每个收集到的切片到达时立即对其进行乘法运算,从设备自身的数据开始,并在最后应用逐行归一化。Figure 7. Schematic. The folded matvec multiplies each gathered slice as soon as it lands, starting with the device’s own, and applies the per-row normalization at the end.
这之所以可行,关键在于 Muse Spark 的归一化位置。下一层的注意力输入,是对残差流 α·x + β·s·f 做 RMS 归一化 [13] 后的结果,其中 x 是该设备已持有的残差,f 是汇集得到的 MoE 输出,s 是 f 自身的范数因子。两个范数因子 s 和最终的 r 都是每行一个标量。每行的标量与矩阵乘法可交换,因此投影可以拆分成设备能够立即计算的部分,以及逐片累加的部分:What makes this possible is where Muse Spark normalizes. The next layer’s attention input is an RMS norm [13] of the residual stream α·x + β·s·f, where x is the residual this device already holds, f is the gathered MoE output and s is f’s own norm factor. The two norm factors, s and the final r, are each one scalar per row. Scalars per row commute with the matmul, so the projection splits into a part the device can compute right away and a part that adds up slice by slice:
这里,g 是范数的增益向量,f_d 是来自设备 d 的切片,W_d 是对应的权重行块。该内核将本地部分和到达的切片堆叠起来,每个块执行一次乘积运算,按固定的对等设备顺序处理这些切片,并重新排列权重环,使 W 的各个块按相同顺序流入。最后一个切片到达后,它计算 s 和 r,并对结果进行缩放。Here g is the norm’s gain vector, f_d is the slice from device d, and W_d is the matching block of weight rows. The kernel stacks the local part and the arriving slice into one product per block, consumes the slices in a fixed peer order, and reorders the weight ring so that W’s blocks stream in the same order. Once the last slice is in, it computes s and r and scales the result.
内核通过以下方式将每层的两次全量聚合折叠起来:将 MoE 输出并入下一层的 qkv 投影,将注意力输出并入池化器和路由器。残差流本身保持不变;变化的只是矩阵乘法输入舍入为 bf16 的时机,因此结果并非逐位完全一致,我们的准确性检查会覆盖这一点。The kernel folds two all-gathers per layer this way: the MoE output into the next layer’s qkv projection, and the attention output into the pooler and router. The residual stream itself is unchanged; only the point where the matmul input is rounded to bf16 moves, so results are not bit-identical, and our accuracy checks cover it.
4. 改进注意力机制中的流水线处理能力4. Enabling better pipelining in attention
在长上下文场景下,注意力计算占据了一个步骤的大部分开销。内核逐块遍历 KV 缓存,而关键瓶颈是在线 softmax 的运行最大值 [14]:它将每个数据块串联到前一个数据块之后,因此无法对数据块进行流水线处理。At long context, attention is the largest part of a step. The kernel walks the KV cache chunk by chunk, and the key bottleneck was the running max of online softmax [14]: it chained every chunk to the one before, so chunks could not be pipelined.
运行中的最大值会将每个数据块串联起来。The running max chains every chunk
FlashAttention [15] 中使用的在线 softmax 会保留迄今为止见到的最大分数。每个新分块都会计算其分数、更新该最大值、以它为基准进行指数运算,并在最大值增大时重新缩放此前累积的所有结果。因此,每个分块都构成一条串行链(等待 DMA、QK、max、exp、sum、P·V、重新缩放),在获知前一个分块的最大值之前,无法开始计算指数。在微基准测试中,无论分块采用 fp8 还是 bf16,这条链每个分块耗时约 0.17 µs。Online softmax, as used by FlashAttention [15], keeps the maximum score seen so far. Each new chunk computes its scores, updates that maximum, exponentiates against it, and rescales everything accumulated so far whenever the maximum grows. So each chunk is a serial chain (wait for its DMA, QK, max, exp, sum, P·V, rescale) that cannot start its exponentials until the previous chunk’s maximum is known. In a microbenchmark this chain costs about 0.17 µs per chunk, whether the chunk is fp8 or bf16.
Muse Spark 让 Max 不再是必需品Muse Spark makes the max unnecessary
Muse Spark 使用没有可学习权重的 RMS 归一化来归一化 q 和 k(QK-norm [16, 17]),并为 q 设置固定增益。注意力分数的绝对值不会超过 43.8,远未达到 f32 中 exp 溢出的范围。维护运行最大值的目的只是防止溢出,因此该内核将其省去,同时也省去了重缩放。构建内核时,它会根据模型常量检查这一上界。FlashDecoding++ [18] 在 GPU 上通过使用统一最大值和针对罕见溢出的重计算路径,打破了同一依赖链;而这里的上界是精确的,因此内核不需要回退路径。Muse Spark normalizes q and k (QK-norm [16, 17]) with an RMS norm that has no learned weight, and gives q a fixed gain. No attention score can exceed 43.8 in magnitude, far from where exp overflows in f32. The running max exists only to prevent that overflow, so the kernel drops it, along with the rescale. It checks the bound from the model’s constants when it is built. FlashDecoding++ [18] breaks the same chain on GPUs with a unified max value and a recomputation path for the rare overflow; here the bound is exact, so the kernel needs no fallback.

图 8. 示意图。使用运行最大值时,每个数据块的处理链都要等待前一个数据块完成。不使用时,各数据块彼此独立,其处理阶段可以重叠。Figure 8. Schematic. With a running max, each chunk’s chain waits on the previous chunk. Without it, chunks are independent and their stages overlap.
独立分块流水线Independent chunks pipeline
没有 max 时,各个分块之间不再相互依赖。内核会在每次循环迭代开始时发出所有 DMA 等待指令,将这些分块分配到多个彼此独立的 softmax 流中,并在末尾合并——这与 Flash-Decoding 对 KV 序列的处理方式类似 [19];同时还会对循环进行软件流水化 [11]:在计算前一批分块的概率与 V 的乘积时,对下一批分块进行打分。Without the max, chunks no longer depend on each other. The kernel issues all DMA waits at the top of each loop iteration, splits the chunks across several independent softmax streams that merge at the end, as Flash-Decoding does across the KV sequence [19], and software-pipelines the loop [11]: it scores the next chunks while it multiplies the previous chunks’ probabilities by V.
另外三项较小的更改进一步缩短了每条链:Three smaller changes shorten each chain further:
- 按层类型确定块大小。全局层以 1,024 到 2,048 个 token 的长块读取缓存,因此 100K 上下文所需的链数要少得多。滑动窗口层使用 512 个 token 的块,因为其窗口只跨越少数几个块。Chunk size by layer type. Global layers read the cache in long chunks of 1,024 to 2,048 tokens, so a 100K context needs far fewer chains. Sliding-window layers use 512-token chunks, since their window spans only a few.
- fp8 键直接送入 MXU。将每个 fp8 数据块在向量单元上扩宽为 bf16,所需的向量运算比其供给的 MXU 运算还多。混合 bf16 × fp8 点积是精确的,因此现在键以 fp8 格式输入。fp8 keys straight into the MXU. Widening each fp8 chunk to bf16 on the vector unit cost more vector work than the MXU work it fed. Mixed bf16 × fp8 dots are exact, so the keys now go in as fp8.
- 查询中的注意力缩放因子。Muse Spark 的注意力缩放因子是 1/8,这是 2 的幂,因此只需对查询乘一次,而不是对每个分数都相乘,结果完全精确。The attention scale in the queries. Muse Spark’s attention scale is 1/8, a power of two, so multiplying the queries once instead of every score is exact.

图 9. 生产环境张量尺寸下的微基准测试。内存下限是读取 KV 数据所需的时间。Figure 9. Microbenchmark at production shapes. The memory floor is the time to read the KV bytes.
在微基准测试中,使用更长的块并行处理独立流,使注意力计算耗时缩短至原来的 1/2.4;去掉运行最大值后,耗时进一步缩短至原来的 1/3.9。在服务器上,对于上下文长度为 500K 的两个请求,流水线循环使每个请求的解码速度提升了 18%。In the microbenchmark, longer chunks with independent streams cut attention time 2.4×, and dropping the running max took it to 3.9×. In the server, the pipelined loop raised per-request decode speed by 18% for two requests at 500K context.
5. 避免常见路径承受寄存器压力5. Keeping register pressure off the common path
处理器对寄存器中保存的值进行运算。寄存器是紧邻算术单元的一小组固定存储槽位。当代码需要同时保留的值多于寄存器容量时,编译器会将其中一些值溢出到内存,并在之后重新加载 [20];每次执行到相关代码时,这些额外的存储和加载操作都会耗费时间。在包含多个分支的循环中,编译器必须将所有分支中的活跃值都安排到同一组寄存器中,因此,即使某个分支从未执行,其中一个负载较重的分支也可能导致每次循环迭代都发生寄存器溢出。A processor computes on values held in its registers, a small, fixed set of storage slots next to the arithmetic units. When code needs more live values than the registers hold, the compiler spills some of them to memory and loads them back later [20], and those extra stores and loads cost time on every pass through the code. In a loop with several branches, the compiler has to fit the live values of all branches into the same registers, so one heavy branch can make every pass through the loop spill, even when that branch never runs.
巨内核的专家循环恰好遇到了这个问题。一个步骤会遍历各行被路由到的专家。对于每个专家,内核都会等待其权重就绪,然后根据该专家处理的行数选择执行路径:行数较少时走轻量路径,其中针对 1 到 8 行还有一些小幅变体;对于处理更多行的专家,则走先反量化再相乘的路径。随着批次增大,一个步骤会访问更多专家,但其中大多数仍然只处理一两行,因此真正重要的是轻量路径。The megakernel’s expert loop had exactly this problem. A step loops over the experts its rows were routed to. For each one, the kernel waits for the expert’s weights and runs a path chosen by how many rows the expert serves: a few-row path, with small variants for one to eight rows, and a dequantize-then-multiply path for busier experts. As the batch grows, a step visits more experts, but most of them still serve only one or two rows, so the light path is the one that matters.
一个繁重分支会拖慢轻量路径One heavy branch slows the light path
8 行变体保留了较大的 f32 累加器,即使单独使用也无法装入向量寄存器。由于它与 1 行和 2 行变体共用同一个循环体,公共路径每处理一个专家都会将寄存器内容溢出到内存,再重新加载:每个专家约耗时 0.37 µs,而流式读取该专家权重约需 1.2 µs。这部分开销与轻量路径本身所做的工作毫无关系。The 8-row variant keeps large f32 accumulators that do not fit in the vector registers even on their own. Because it shared one loop body with the one- and two-row variants, the common path spilled registers to memory and loaded them back on every expert: about 0.37 µs per expert, against roughly 1.2 µs to stream that expert’s weights. That overhead had nothing to do with the work the light path itself did.
用两个循环代替一个循环Two loops instead of one
此修复将重型代码移出轻量路径的循环。内核按行数对某一步中的专家进行排序,并运行两个循环:一个处理行数不超过 4 的专家,另一个处理其余专家。现在每个循环体只包含自身对应的变体,因此,少行循环中的溢出指令减少了 61–64%。每个专家仍走与之前相同的路径,因此输出逐位完全一致。The fix keeps the heavy code out of the light path’s loop. The kernel sorts a step’s experts by row count and runs two loops: one for experts with at most four rows, and one for the rest. Each loop body now holds only its own variants, so the few-row loop carries 61–64% fewer spill instructions. Every expert still takes the same path as before, so the output is bit-identical.

图10. 示意图。在共享的循环体中,每个少行专家之后都会发生一次溢出和回填,导致循环跟不上权重流。而在各自独立的循环中,少行专家能够与权重流保持同步。Figure 10. Schematic. In one shared loop body, every few-row expert is followed by a spill and refill, and the loop falls behind its weight stream. In their own loop, few-row experts keep pace with the weights.
在一次采用随机路由的内核测试中,请求较多的解码步骤提速了 13–19%,专家循环现在也能跟上权重流的速度。In a kernel test with random routing, decode steps with many requests got 13–19% faster, and the expert loop now keeps pace with its weight stream.
6. 使用 DFlash2 进行推测解码6. Speculative decoding with DFlash2
不进行推测解码时,每个输出 token 都需要对当前激活的权重进行一次完整遍历。DFlash [21] 使用小模型的一次前向传播来起草一整块 token;我们使用 Muse Spark 的 DFlash2 草稿模型。Without speculation, every output token costs one full pass over the active weights. DFlash [21] drafts a whole block of tokens in one forward pass of a small model; we use Muse Spark’s DFlash2 draft model.

图 11. 一个推测步骤。草稿模型读取从完整模型中捕获的隐藏状态。令牌条带仅为示意图。Figure 11. One speculative step. The draft model reads hidden states captured from the full model. The token strip is an illustration.
草稿模型在其块内进行双向注意力,并一次性提出该块中的所有令牌。完整模型在一个 megakernel 步骤中检查整个块,保留与自身选择相匹配的最长草稿前缀,并额外保留一个由自身生成的令牌。The draft attends bidirectionally within its block and proposes all of the block’s tokens at once. The full model checks the whole block in one megakernel step and keeps the longest prefix of drafts that matches its own choices, plus one token of its own.
这很适合 TPU:MXU 的耗时随行数和输出 tile 数量增长,而非随乘加运算次数增长;一个 block 的少数几行可以和一个 token 一样放入同一个行 tile,因此验证一个 block 的成本只比验证一个 token 略高。在 GSM8K 上以实际接受率进行测量时,DFlash2 将单个请求的巨型内核每个输出 token 耗时从 3.93 毫秒降至 1.95 毫秒,提升了 2.0 倍。This suits TPU well: MXU time grows with the number of row and output tiles, not with multiply-adds, and a block’s few rows fit in the same row tile as one token, so verifying a block costs little more than verifying one token. Measured on GSM8K with real acceptance, DFlash2 cut the megakernel’s time per output token for a single request from 3.93 to 1.95 ms, 2.0×.
7. 每台设备承载更多上下文:KV 布局与 L2 HiCache7. More context per device: KV layout and L2 HiCache
在智能体流量场景中,KV 容量就意味着吞吐量:每个被逐出缓存的前缀,都会以 100K token 的重新预填充计算量再次出现。扣除权重占用后,每台设备仅剩约 20 GiB 可用于 KV,并分配给两个池:供 16 个全局层使用的全注意力池,以及供其余 46 层使用的滑动窗口池。On agent traffic, KV capacity is throughput: every prefix that falls out of the cache comes back as a 100K-token re-prefill. After the weights, each device has only about 20 GiB left for KV, split between a full-attention pool for the 16 global layers and a sliding-window pool for the other 46.
FP8 KV 的 sequence-on-lane 布局fp8 KV in a sequence-on-lane layout
每个设备持有 16 个 KV 头中的 2 个,每个头宽 64 个值:相当于一个向量寄存器 128 条 lane 的一半。按 token 优先排列的缓存将一个头的 K 和 V 并排打包,以填满这些 lane。这在 bf16 下可行,但 fp8 [22] 会沿子 lane 将每 4 个值打包到一个 32 位字中,因此一对 K 和 V 会补齐到 4 个槽位;仅切换到 fp8 并不会节省任何空间。Each device holds 2 of the 16 KV heads, each 64 values wide: half of a vector register’s 128 lanes. A token-major cache packs a head’s K and V side by side to fill the lanes. That works in bf16, but fp8 [22] packs four values per 32-bit word down the sublanes, so a K-and-V pair is padded to four slots and switching to fp8 alone saves nothing.
| KV bytes per token, per layer, per device | bf16 | fp8 |
|---|---|---|
| Token-major, K and V packed per head | 512 B | 512 B |
| Sequence-on-lane | 512 B | 256 B |
序列沿 lane 排布的布局将页面中的 token 沿 128 个 lane 排列,并将 head 维度沿子 lane 方向排列,因此每个 word 存放同一个 token 的四个 fp8 值,且无需填充。它将 KV 内存占用和每一步读取的 KV 字节数都减半。Google 工程师将这种布局加入了 SGLang-TorchTPU 的 ragged 分页注意力内核(#344);该内核在这里负责 prefill,TorchTPU 的后续文章则介绍了它在 Qwen 3.5 中的应用。我们据此重写了 megakernel 的注意力读取和 KV 写入逻辑。The sequence-on-lane layout puts a page’s tokens along the 128 lanes and the head dimension down the sublanes, so each word holds four fp8 values of one token and nothing is padded. It halves both the KV memory and the KV bytes each step reads. Google engineers added this layout to SGLang-TorchTPU’s ragged paged attention kernel (#344), which serves prefill here, and the TorchTPU post describes it for Qwen 3.5. We rewrote the megakernel’s attention reads and its KV writes for it.
滑动窗口池中的草稿模型 KV#+#+#+#+The draft model’s KV in the sliding-window pool
草稿模型只关注最后 2,048 个 token,但服务器却按完整上下文为它分配了 KV 缓存,几乎占用了三分之一的 KV 内存。改用滑动窗口池为其提供服务后,同一块 HBM 就能容纳多 38% 的 token。The draft model only attends to the last 2,048 tokens, but the server allocated its KV for the full context, almost a third of all KV memory per cached token. Serving it from the sliding-window pool lets the same HBM hold 38% more tokens.
TPU 上的 L2 HiCacheL2 HiCache on TPU
我们在 TPU 上启用了 SGLang 的分层缓存(HiCache)[23],在每个 HBM 池(全注意力、滑动窗口和草稿池)后面都配置了主机 DRAM 作为 L2 缓存。当 HBM 在工具调用暂停期间驱逐某个会话的前缀时,这些页面仍保留在主机内存中,并会在下一轮时复制回 HBM,而无需像 CachedAttention [24] 等多轮 KV 缓存系统那样重新计算。要使其与推测解码和重叠调度器协同工作,我们需要新增一个同步栅栏。在智能体流量场景下,L2 缓存使吞吐量最高提升了 77%。We enabled SGLang’s hierarchical cache (HiCache) [23] on TPU, with host DRAM as an L2 behind every HBM pool: full-attention, sliding-window and draft. When HBM evicts a session’s prefix during a tool pause, its pages stay in host memory and are copied back on the next turn instead of being recomputed, as in multi-turn KV caching systems such as CachedAttention [24]. Making it work alongside speculative decoding and the overlap scheduler needed a new synchronization fence. On agent traffic, the L2 cache raised throughput by up to 77%.
会话感知驱逐Session-aware eviction
智能体流量带来了第二个问题:缓存无法预知哪些旧前缀之后还会再次用到。智能体会话是一棵对话树:主智能体可能闲置一刻钟,让子智能体运行,然后带着完整上下文回来。对于普通的 LRU 淘汰策略来说,这段闲置的对话看起来是缓存中最冷的数据,因此会最先被淘汰;等到它下一轮运行时,就得重新计算一个很长的前缀。混合模型会让损失更严重:要复用一个前缀,需要同时保留其完整注意力 KV,以及最近 2,048 个 token 的滑动窗口 KV,因此,只要丢失较小的窗口 KV,较大的完整注意力 KV 也会变得毫无用处。在这条跟踪记录中,预填充计算的 token 数约为理想缓存所需数量的 1.2 倍。Agent traffic brought a second problem: the cache did not know which old prefixes would be needed again. An agent session is a tree of conversations: a main agent can sit idle for a quarter of an hour while its sub-agents run, then come back with its whole context. To plain LRU eviction, that idle conversation looks like the coldest data in the cache, so it goes first, and its next turn recomputes a long prefix. A hybrid model makes the loss worse: reusing a prefix needs both its full-attention KV and the sliding-window KV of its last 2,048 tokens, so losing only the small window makes the large full-attention KV useless. On this trace, prefill computed about 1.2× the tokens that the best possible cache would.

图 12. 示意图。主代理在其子代理运行时处于空闲状态。普通 LRU 会优先驱逐其 KV;会话感知型驱逐机制则会将其保留在主机内存中,直到其他所有内容都被驱逐。Figure 12. Schematic. A main agent idles while its sub-agents run. Plain LRU evicts its KV first; session-aware eviction keeps it in host memory until everything else has gone.
SGLang 的会话感知基数缓存 [5](sgl-project/sglang#29173)让缓存具备了这种认知。来自同一对话的请求共享一个会话 ID,而活动会话将重用的 KV 只有在其他所有内容都被逐出后才会被逐出。我们针对智能体流量对其进行了调整:会话 ID 取自客户端已经发送的每对话 ID;保护机制仅适用于主机内存,因此对于正在运行的请求,HBM 仍采用普通 LRU,而主机内存则保存空闲对话。在图 1 的最高吞吐量测试中,prefill 的计算性能如今已达到理想缓存最佳表现的 1–5% 以内。SGLang’s session-aware radix cache [5] (sgl-project/sglang#29173) gives the cache that knowledge. Requests from the same conversation share a session id, and KV that a live session will reuse is evicted only after everything else. We adapted it to agent traffic: the session id comes from the per-conversation id the client already sends, and the protection applies only in host memory, so HBM stays plain LRU for the requests that are running while host memory holds the idle conversations. In the highest-throughput run of Figure 1, prefill now computes within 1–5% of what the best possible cache would.
8. 预填充:融合 MoE 内核与公平批处理8. Prefill: a fused MoE kernel and fair batching
在请求开始解码之前,服务器会将新提示词的 token 分成每块 4,096 个,依次输入模型处理 [25, 26],这一阶段称为预填充。每个数据块包含足够多的行,能让矩阵单元保持繁忙;因此,与解码不同,预填充耗时主要取决于计算以及在设备之间传输结果。在智能体流量中,单个轮次可能带来数十万个新 token,因此预填充速度决定了请求在收到首个 token 前需要等待多久。Before a request can start decoding, the server runs its new prompt tokens through the model in chunks of 4,096 tokens [25, 26]: the prefill. A chunk has enough rows to keep the matrix unit busy, so unlike decode, prefill time goes to compute and to moving results between devices. On agent traffic a single turn can bring hundreds of thousands of new tokens, so prefill speed decides how long requests wait before their first token.
在预填充阶段的 MoE 层中,每个设备都会为每个(token,expert)对计算一个部分结果,而每个 token 的所有者必须将其中 8 个部分结果相加。一次只传输一小块部分结果,所花的成本比矩阵运算本身还高。In the MoE layers of prefill, every device computes a partial result for every (token, expert) pair, and each token’s owner must add up 8 of them. Moving those partials, one small write at a time, cost more than the matrix math.
融合 MoE 内核与成对交换The fused MoE kernel and the pair exchange
专家采用张量并行进行分片:每个设备持有每个专家的 1/8。因而,每个设备都会针对自己的分片,处理预填充块中的每个(token,专家)行,为每行生成一个全宽的部分结果;Muse Spark 会在加权求和前对每个专家的输出进行归一化,因此必须先将一行对应的 8 个部分结果全部相加,所有者才能进行归一化并合并各专家的输出。内核在预取下一个专家权重的同时流式读取当前专家的权重,执行 gate/up、SwiGLU [27] 和 down 操作,并将每个完成的行直接写入其所有者的 HBM,同时与后续块的处理重叠。Experts are sharded with tensor parallelism: each device holds 1/8 of every expert. Each device therefore runs every (token, expert) row of a prefill chunk against its slice, producing a full-width partial per row; Muse Spark normalizes each expert’s output before the weighted sum, so a row’s 8 partials must all be added up before its owner can apply the norm and combine experts. The kernel streams one expert’s weights while the next prefetches, runs gate/up, SwiGLU [27] and down, and writes each finished row straight into its owner’s HBM, overlapping later tiles.

图 13. 芯片上的两个器件共用一条芯片间链路,Google 文档称其速度是连接到另一块芯片的 1D ICI 链路的六倍。Figure 13. The two devices on a chip share a die-to-die link, which Google documents as six times faster than a 1D ICI link to another chip.
每一行的写入大约需要 50 ns 的标量运算,而且由负责发起矩阵乘法的同一单元执行,因此写入会与计算串行进行。配对交换则利用了芯片的拓扑结构:每个设备通过高速片上链路,将整个数据块发送给同一芯片上的配对设备;随后,这一对设备的求和结果会发送给每个远端所有者,每个连续行段只需一次 DMA。跨芯片传输的字节数减半,每个所有者要累加的块数从 8 个降至 5 个,MoE 内核的每层耗时也从 3,247 µs 降至 2,368 µs。Each row’s write took about 50 ns of scalar work on the same unit that issues the matmuls, so writes serialized with compute. The pair exchange uses the chip’s topology instead. Each device sends its whole tile to its sibling on the same chip over the fast on-chip link, and the pair’s sum then goes to each remote owner once, as one DMA per contiguous run of rows. Cross-chip bytes halve, each owner adds 5 blocks instead of 8, and the MoE kernel went from 3,247 to 2,368 µs per layer.
一些较小的改动则精简了路径的其余部分:Smaller changes trimmed the rest of the path:
- 权重乒乓。交替使用两个权重缓冲区,使每个专家的权重加载可以在前一个专家进行计算时启动。Weight ping-pong. Alternating two weight buffers lets each expert’s fetch start while the previous expert computes.
- 一次遍历完成合并。归属方的部分结果求和、逐专家范数计算和加权求和原本分为三个 XLA pass;一个融合的 Pallas pass 只需读取一次部分结果。A one-pass combine. The owner’s sum of partials, per-expert norm and weighted sum ran as three XLA passes; one fused Pallas pass reads the partials once.
- 不进行清零,写入操作已展开。每个输出行都恰好写入一次,因此移除了输出缓冲区的清零操作,并将逐行 DMA 循环改为每次迭代处理 8 行。No zero fill, unrolled writes. Every output row is written exactly once, so the zero fill of the output buffer was dropped, and the per-row DMA loop issues 8 rows per iteration.
配合这些小幅改动,成对交换将冷启动的 100K token 提示词中一个 4,096-token 预填充块的耗时从 440 毫秒缩短至 384 毫秒。Together with these smaller changes, the pair exchange cut a 4,096-token prefill chunk from 440 to 384 ms on a cold 100K-token prompt.
序列并行预填充Sequence-parallel prefill
张量并行会将每次矩阵乘法拆分到 8 个设备上执行,但每个设备仍持有整个分块的激活值,因此矩阵乘法之间按 token 执行的工作(如归一化、残差更新和路由)会在每个设备上重复进行。序列并行 [28] 则拆分 token:在层与层之间,每个设备只保留该分块 4,096 个 token 中属于自己的 512 个。这样,归一化和残差更新只需处理八分之一的 token;注意力中的全归约则变为归约散射,每个设备只会收到属于自己的 token 的求和结果。路由会将每个 token 的专家 ID 和权重打包到一次小规模的全收集中。MoE 的输出通过一次全互换到达对应 token 所在的设备:每个设备只从其他七个设备接收属于自己的 token 的列,数据量仅为被替代的全收集的八分之一;后者会将全部 4,096 个 token 的列发送给每个设备。在 131K 上下文下,这使一次包含 4,096 个 token 的前向计算缩短了 51 毫秒,约 11%。这会改变某些归约的顺序,因此结果并非逐位完全相同;我们的准确性检查也覆盖了这一点。Tensor parallelism splits every matmul across the 8 devices, but each device still holds the activations of the whole chunk, so the per-token work between the matmuls, such as norms, residual updates and routing, is repeated on every device. Sequence parallelism [28] splits the tokens instead: between layers, each device keeps only its own 512 of the chunk’s 4,096 tokens. The norms and residual updates then run on an eighth of the tokens, and attention’s all-reduce becomes a reduce-scatter, which delivers each device only its own tokens’ sums. Routing packs each token’s expert ids and weights into one small all-gather. The MoE output reaches its tokens’ devices through an all-to-all: each device receives only its own tokens’ columns from the other seven, an eighth of the bytes of the all-gather it replaces, which sent every device the columns of all 4,096 tokens. This cut a 4,096-token forward at 131K context by 51 ms, about 11%. It changes the order of some reductions, so results are not bit-identical, and our accuracy checks cover it.
分块共享Chunk sharing
一条包含数十万 token 的冷启动提示词,会以每块 4,096 个 token、每块约半秒的速度预填充。过去,调度器会一直把每个数据块都分配给这条提示词,直到处理完毕,因此其他轮次新增的几千个 token 不得不在它后面等待 15 到 95 秒。A cold prompt of hundreds of thousands of tokens is prefilled in 4,096-token chunks of about half a second each. The scheduler used to give every chunk to that prompt until it finished, so other turns’ few thousand new tokens waited 15 to 95 s behind it.

图 14. 示意图。长提示会保留每个批次至少 1,024 个 token,等待中的轮次填满其余部分,长提示稍后完成。Figure 14. Schematic. The long prompt keeps at least 1,024 tokens of each batch, waiting turns fill the rest, and the long prompt finishes a little later.
现在,在分块预填充过程中插入提示词,可确保每个批次至少包含 1,024 个 token,其余部分由等待中的请求轮次填充。在一项 AgentX 测试中,这使端到端延迟中位数降低了 58%,p90 降低了 33%,同时吞吐量变化在 5% 以内。Now a prompt in the middle of a chunked prefill keeps at least 1,024 tokens of each batch, and waiting turns fill the rest. In an AgentX test, this cut median end-to-end latency by 58% and p90 by 33%, with throughput within 5%.
未来工作Future work
- 通过将宽度为 64 的注意力头打包以充分利用 MXU,并进一步缩短每个分块的计算链,使注意力计算性能更接近内存受限下限。Attention closer to the memory floor, by packing the 64-wide heads to fill the MXU and shortening the per-chunk chain further.
- 一种感知拓扑的 MoE 布局:在芯片之间采用专家并行,在单个芯片内部采用张量并行,使大部分 MoE 通信都在本地完成。A topology-aware MoE layout, with expert parallelism across chips and tensor parallelism inside each chip, to make most of the MoE exchange local.
- 通过增大预填充计算图、让集合通信与计算重叠,以及重新设计 MoE 预填充内核来加快预填充速度——它如今已成为高并发下的瓶颈。Faster prefill, now the limit at high concurrency, through larger prefill graphs, collectives overlapped with compute and a reworked MoE prefill kernel.
- 预填充/解码(P/D)解耦:将预填充和解码部署在不同主机上,以优化 AgentX 性能。Prefill/decode (P/D) disaggregation, optimizing AgentX performance with prefill and decode on separate hosts.
- 将这项工作合并到 SGLang-TorchTPU 的主分支。Upstreaming this work into SGLang-TorchTPU’s main branch.
代码Code
这里的所有内容都在 SGLang-TorchTPU 的 haolin/ms-v11 分支中开源。Megakernel 位于 sglang_tpu/muse_megakernel/,融合 MoE 预填充内核位于 sglang_tpu/moe/pallas/fused_rs/。Everything here is open source in SGLang-TorchTPU, branch haolin/ms-v11. The megakernel lives in sglang_tpu/muse_megakernel/, the fused MoE prefill kernel in sglang_tpu/moe/pallas/fused_rs/.
致谢Acknowledgments
我们感谢 Google 和 Meta 为 SGLang-TorchTPU 作出的内核贡献,本工作正是基于这些贡献开展的;特别感谢 Qi Zhou、Yunlong Liu、Charles Chen、Yin Lin、Jiaxin Cao 和 Anne Stern 为本文所述内核及 AgentX 优化所作的工作。我们还感谢 SemiAnalysis、Google、Meta 和 SGLang 社区提供 InferenceX、TPU v7 和 TorchTPU、Muse Spark Open 以及 SGLang。We thank Google and Meta for their kernel contributions to SGLang-TorchTPU, which this work builds on, and give special thanks to Qi Zhou, Yunlong Liu, Charles Chen, Yin Lin, Jiaxin Cao and Anne Stern for their work on the kernels and AgentX optimization described here. We also thank SemiAnalysis, Google, Meta and the SGLang community for InferenceX, TPU v7 and TorchTPU, Muse Spark Open, and SGLang.
参考文献References
- N. Shazeer、A. Mirhoseini、K. Maziarz 等。《令人惊叹的大型神经网络:稀疏门控混合专家层》。ICLR 2017。arXiv:1701.06538N. Shazeer, A. Mirhoseini, K. Maziarz, et al. Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer. ICLR 2017. arXiv:1701.06538
- I. Beltagy、M. E. Peters、A. Cohan。《Longformer:长文档 Transformer》。2020。arXiv:2004.05150I. Beltagy, M. E. Peters, A. Cohan. Longformer: The Long-Document Transformer. 2020. arXiv:2004.05150
- B. D. Rouhani、R. Zhao、A. More 等。《深度学习的微缩放数据格式》。2023。arXiv:2310.10537B. D. Rouhani, R. Zhao, A. More, et al. Microscaling Data Formats for Deep Learning. 2023. arXiv:2310.10537
- M. Shoeybi、M. Patwary、R. Puri 等。《Megatron-LM:使用模型并行训练数十亿参数语言模型》。2019 年。arXiv:1909.08053M. Shoeybi, M. Patwary, R. Puri, et al. Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism. 2019. arXiv:1909.08053
- L. Zheng、L. Yin、Z. Xie 等。《SGLang:结构化语言模型程序的高效执行》。NeurIPS 2024。arXiv:2312.07104L. Zheng, L. Yin, Z. Xie, et al. SGLang: Efficient Execution of Structured Language Model Programs. NeurIPS 2024. arXiv:2312.07104
- Y. Leviathan、M. Kalman、Y. Matias。《通过推测解码实现 Transformer 的快速推理》。ICML 2023。arXiv:2211.17192Y. Leviathan, M. Kalman, Y. Matias. Fast Inference from Transformers via Speculative Decoding. ICML 2023. arXiv:2211.17192
- C. Chen、S. Borgeaud、G. Irving 等。《使用推测采样加速大型语言模型解码》。2023。arXiv:2302.01318C. Chen, S. Borgeaud, G. Irving, et al. Accelerating Large Language Model Decoding with Speculative Sampling. 2023. arXiv:2302.01318
- B. Spector、J. Juravsky 等。《瞧,妈妈,没有气泡!为 Llama-1B 设计低延迟巨型内核》。Hazy Research,2025。博客文章B. Spector, J. Juravsky, et al. Look Ma, No Bubbles! Designing a Low-Latency Megakernel for Llama-1B. Hazy Research, 2025. Blog post
- X. Cheng、Z. Zhang、Y. Zhou 等。《MPK:用于超级内核化张量程序的编译器和运行时》。OSDI 2026。论文X. Cheng, Z. Zhang, Y. Zhou, et al. MPK: A Compiler and Runtime for Mega-Kernelizing Tensor Programs. OSDI 2026. Paper
- G. Novack、X. Liu、J. Ma、W. Kwon。《面向 Kimi K3 和 Qwen3.8-27B 的 TPU 巨型内核》。2026。代码G. Novack, X. Liu, J. Ma, W. Kwon. TPU megakernels for Kimi K3 and Qwen3.8-27B. 2026. Code
- M. Lam。《软件流水线:一种适用于 VLIW 机器的有效调度技术》。PLDI 1988。doi:10.1145/53990.54022M. Lam. Software Pipelining: An Effective Scheduling Technique for VLIW Machines. PLDI 1988. doi:10.1145/53990.54022
- S. Wang、J. Wei、A. Sabne 等.《通过分解在大型深度学习模型中实现通信与依赖计算的重叠》. ASPLOS 2023. doi:10.1145/3567955.3567959S. Wang, J. Wei, A. Sabne, et al. Overlap Communication with Dependent Computation via Decomposition in Large Deep Learning Models. ASPLOS 2023. doi:10.1145/3567955.3567959
- B. Zhang, R. Sennrich. 均方根层归一化。NeurIPS 2019。arXiv:1910.07467B. Zhang, R. Sennrich. Root Mean Square Layer Normalization. NeurIPS 2019. arXiv:1910.07467
- M. Milakov、N. Gimelshein。《Softmax 的在线归一化计算》。2018 年。arXiv:1805.02867M. Milakov, N. Gimelshein. Online Normalizer Calculation for Softmax. 2018. arXiv:1805.02867
- T. Dao、D. Y. Fu、S. Ermon 等。《FlashAttention:具备 IO 感知能力的快速且内存高效的精确注意力》。NeurIPS 2022。arXiv:2205.14135T. Dao, D. Y. Fu, S. Ermon, et al. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. NeurIPS 2022. arXiv:2205.14135
- A. Henry、P. R. Dachapally、S. Pawar 等。《Transformer 的查询-键归一化》。EMNLP 2020 研究成果。arXiv:2010.04245A. Henry, P. R. Dachapally, S. Pawar, et al. Query-Key Normalization for Transformers. Findings of EMNLP 2020. arXiv:2010.04245
- M. Dehghani、J. Djolonga、B. Mustafa 等。《将视觉 Transformer 扩展至 220 亿参数》。ICML 2023。arXiv:2302.05442M. Dehghani, J. Djolonga, B. Mustafa, et al. Scaling Vision Transformers to 22 Billion Parameters. ICML 2023. arXiv:2302.05442
- K. Hong、G. Dai、J. Xu 等。《FlashDecoding++:在 GPU 上实现更快的大型语言模型推理》。MLSys 2024。arXiv:2311.01282K. Hong, G. Dai, J. Xu, et al. FlashDecoding++: Faster Large Language Model Inference on GPUs. MLSys 2024. arXiv:2311.01282
- T. Dao、D. Haziza、F. Massa、G. Sizov。《用于长上下文推理的 Flash-Decoding》。斯坦福 CRFM,2023。博客文章T. Dao, D. Haziza, F. Massa, G. Sizov. Flash-Decoding for Long-Context Inference. Stanford CRFM, 2023. Blog post
- G. J. Chaitin。通过图着色进行寄存器分配与溢出。SIGPLAN 编译器构造研讨会,1982 年。doi:10.1145/800230.806984G. J. Chaitin. Register Allocation & Spilling via Graph Coloring. SIGPLAN Symposium on Compiler Construction, 1982. doi:10.1145/800230.806984
- J. Chen、Y. Liang、Z. Liu 等。《DFlash:用于 Flash 推测解码的块扩散》。2026。arXiv:2602.06036J. Chen, Y. Liang, Z. Liu, et al. DFlash: Block Diffusion for Flash Speculative Decoding. 2026. arXiv:2602.06036
- P. Micikevicius、D. Stosic、N. Burgess 等。《深度学习的 FP8 格式》。2022 年。arXiv:2209.05433P. Micikevicius, D. Stosic, N. Burgess, et al. FP8 Formats for Deep Learning. 2022. arXiv:2209.05433
- SGLang 团队。《SGLang HiCache:借助你喜爱的存储后端实现快速分层 KV 缓存》。LMSYS Org,2025。博客文章.SGLang Team. SGLang HiCache: Fast Hierarchical KV Caching with Your Favorite Storage Backends. LMSYS Org, 2025. Blog post
- B. Gao、Z. He、P. Sharma 等:《面向多轮对话的 CachedAttention 高性价比大语言模型服务》。USENIX ATC 2024。arXiv:2403.19708B. Gao, Z. He, P. Sharma, et al. Cost-Efficient Large Language Model Serving for Multi-turn Conversations with CachedAttention. USENIX ATC 2024. arXiv:2403.19708
- A. Agrawal、A. Panwar、J. Mohan 等。《SARATHI:通过将解码搭载到分块预填充上实现高效 LLM 推理》。2023 年。arXiv:2308.16369A. Agrawal, A. Panwar, J. Mohan, et al. SARATHI: Efficient LLM Inference by Piggybacking Decodes with Chunked Prefills. 2023. arXiv:2308.16369
- A. Agrawal、N. Kedia、A. Panwar 等:《借助 Sarathi-Serve 驯服大语言模型推理中的吞吐量—延迟权衡》。OSDI 2024。arXiv:2403.02310A. Agrawal, N. Kedia, A. Panwar, et al. Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve. OSDI 2024. arXiv:2403.02310
- N. Shazeer。《GLU 变体改进 Transformer》。2020。arXiv:2002.05202N. Shazeer. GLU Variants Improve Transformer. 2020. arXiv:2002.05202
- V. Korthikanti、J. Casper、S. Lym 等。《减少大型 Transformer 模型中的激活重计算》。MLSys 2023。arXiv:2205.05198V. Korthikanti, J. Casper, S. Lym, et al. Reducing Activation Recomputation in Large Transformer Models. MLSys 2023. arXiv:2205.05198