借助位级零训练—推理偏差,在 TPU 上实现稳定的 On-Policy RL
原题Unlocking Stable On-Policy RL on TPU with Bitwise-Zero Train–Inference Mismatch
推荐理由Google 的 Zero-TIM 指出相同权重在训练与推理路径仍会产生 logprob 偏差,并给出 TPU 位级一致的实现步骤。训练团队可据此定位 On-Policy RL 不稳定的数值根因,而非只继续调参。
读前速览
Google 推出 Zero-TIM,这是一种位级一致的训练—推理对齐技术,通过自定义 Pallas 内核和受控的规约顺序,消除采样器与训练器之间的数值差异,从而在 TPU 上实现稳定的 On-Policy RL。
Zero-TIM 可确保采样器、预填充和训练器路径上的 logprob 计算达到位级一致
该技术通过严格的对齐约定,确保三条执行路径对采样动作生成完全相同的浮点字节,从而消除隐蔽的 Off-Policy 偏差,避免其在强化学习训练的多轮轨迹中不断累积。
四部分流程打通了 TPU 上相互独立的服务与训练流水线
该方案通过锁定分片内核的累加顺序、明确跨分片规约顺序、统一 logprob 评分流程,以及采用自定义求导规则,在不合并不同引擎的情况下保持数值一致性。
自定义 Pallas 内核控制累加顺序和中间精度
投影内核按固定顺序遍历收缩块,以 float32 累加部分乘积,再转换为 bfloat16;涵盖注意力、MLP 投影、LM 头、RMSNorm 和 SwiGLU 运算。
评估显示,logprob 差异为零,求解率更高
在由 64 个 TPU v5p 组成的网格上进行 FrozenLake 基准测试时,Zero-TIM 实现了采样器与训练器之间平均绝对 logprob 差异为零;与标准训练和 TIS 方法相比,其求解率也更高。
完整摘要
本文介绍 Zero-TIM(零训练—推理偏差),这项技术可在 TPU 上的 On-Policy 强化学习中,确保采样器解码、服务预填充和训练器前向计算路径上的 logprob 计算达到位级一致。该方法针对 bfloat16 中浮点规约不满足结合律所导致的数值不稳定问题;在权重相同的情况下,这一问题会使同一 token 得到不同的 logprob。解决方案采用四部分流程:锁定分片内核的累加顺序、明确跨分片规约顺序、统一 logprob 评分流程的末端计算,并为服务内核封装自定义求导规则。在 64 个 TPU v5p(DP8×TP8)组成的网格上验证后,Zero-TIM 实现了采样器与训练器之间平均绝对 logprob 差异为零;在 FrozenLake 基准测试中,其求解率也高于标准训练和 token 级截断重要性采样。
目录 · 11 节
问题The problem
用于大语言模型的强化学习(RL)以对数值不稳定极其敏感而闻名:即使生成 rollout 与梯度更新之间只有细微差异,也可能导致训练不稳定或收敛停滞。在大语言模型的 RL 中,模型充当策略 π(action | previous tokens),而真正的在线策略学习要求更新中的每个动作都由完全相同的策略生成并评估。虽然同步循环能够确保每个 rollout 批次都使用生成它的同一组权重进行评分,但仍有一项关键的数值要求:采样器和训练器必须以完全相同的方式评估该策略。Reinforcement learning (RL) for large language models is notoriously sensitive to numerical instability: even tiny discrepancies between rollout generation and gradient updates can destabilize training or stall convergence. In LLM RL, the model serves as the policy, π(action | previous tokens), and true on-policy learning requires every action in an update to be generated and evaluated by that exact same policy. While a synchronous loop ensures each rollout batch is scored using the same weights that generated it, a critical numerical requirement remains: the sampler and trainer must evaluate that policy identically.
在实践中,生产级 RL 技术栈会通过相互独立、各有专长的执行路径来进行采样和训练。采样器在增量解码过程中选择每个动作 token,并记录其行为 logprob。训练器则通过批量前向和反向传播来评估同一个 token,计算其当前 logprob 和梯度。即使使用相同的权重,这些不同的执行路径仍可能为同一 token 和上下文赋予不同的 logprob。训练计划是 on-policy 的,但数值执行过程却引入了一个隐蔽的 off-policy 差距,并且会在多轮轨迹中不断累积。In practice, production RL stacks run sampling and training through separate, specialized execution paths. The sampler chooses each action token during incremental decoding and records its behavior logprob. The trainer evaluates the same token in batched forward-backward passes to compute its current logprob and gradients. Under the same weights, these differing execution paths can still assign different logprobs to the same token and context. The training schedule is on-policy, but the numerical execution has introduced a hidden off-policy gap that compounds over multi-turn trajectories.
我们在 Tunix 中开发的零训练–推理不匹配(Zero-TIM)实现,已在 64 个 TPU v5p 芯片(DP8×TP8)的多主机规模下完成验证,弥合了这一数值差距。在相同权重下,采样器和训练器对相同的动作与 token 历史赋予逐位完全一致的 logprobs,从而为 TPU 强化学习训练带来最先进的真正在线策略稳定性。Our zero train–inference mismatch (Zero-TIM) implementation, developed in Tunix and verified at multi-host scale across 64 TPU v5p chips (DP8×TP8), closes this numerical gap. At the same weights, the sampler and trainer assign bitwise-identical logprobs to the same action and token history—bringing state-of-the-art, true on-policy stability to TPU RL training.
为什么会发生Why it happens
归约是一棵由浮点加法构成的树。浮点加法不满足结合律,因此改变这棵树会改变舍入发生的位置。在 bfloat16 中,这种影响更容易显现,因为它的精度低于 float32。A reduction is a tree of floating-point additions. Floating-point addition is not associative, so changing the tree changes where rounding occurs. The effect is easier to expose in bfloat16, which retains less precision than float32.
下面的 bfloat16 示例单独展示了归约顺序的影响:The following bfloat16 example isolates the effect of reduction order:
模型缩减中也会出现同样的问题:矩阵乘法会累积部分和,归一化会计算统计量,张量并行的分片会合并部分输出。在我们原有的技术栈中,采样器解码和训练器前向传播使用了不同的 token 数组形状和前向实现。JAX 会针对输入形状专门优化计算,而训练前向传播还会在一个经过微分的程序中运行。The same issue appears in model reductions: matrix products accumulate partial sums, normalization computes statistics, and tensor-parallel shards combine partial outputs. In our original stack, sampler decode and trainer forward used different token-array shapes and forward implementations. JAX specializes computations to their input shapes, and the training forward also runs inside a differentiated program.
在这些路径中,归约顺序和中间精度并未始终保持一致。浮点舍入使这些算术差异转化为不同的 logprob 位值。权重和模型方程完全相同,但算术过程并不相同。Across these paths, reduction order and intermediate precision were not consistently aligned. Floating-point rounding turned those arithmetic differences into different logprob bits. The weights and model equations were identical; the arithmetic was not.
对齐契约The alignment contract
约定很简单:在采样器解码、服务端预填充和训练器前向传播这三条路径中,对于每个采样动作,在 rollout 权重、token 历史和采样设置相同的条件下,都必须生成逐位完全相同的对数概率——比较原始浮点数的字节,不做任何舍入,也不允许任何容差。The contract is simple: across sampler decode, serving prefill, and trainer forward, all three paths must produce bitwise-identical logprobs for every sampled action—comparing raw floating-point bytes under the same rollout weights, token history, and sampling settings, with zero rounding or tolerance.
为什么是三条路径,而不是两条?在解耦的 RL 技术栈中,采样器与训练器之间的直接差异表明存在数值差距,但无法说明差距从何处产生。将服务端预填充作为中间检查点,就能把对齐检查转变为系统性的两步诊断,任何 RL 技术栈都可以采用:Why three paths instead of two? In a decoupled RL stack, a direct sampler–trainer disagreement shows that a numerical gap exists, but not where it enters. Introducing serving prefill as a middle checkpoint turns alignment into a systematic two-step diagnostic that any RL stack can adopt:
Sampler 解码与 prefill 的比较,用于验证服务引擎在增量生成 token 和对完整序列重新评分时是否一致;而 prefill 与 trainer 的比较,则用于验证服务引擎和训练引擎跨越编译与微分边界时是否一致。Sampler decode vs. prefill verifies that the serving engine agrees with itself between incremental token generation and full-sequence re-scoring, while prefill vs. trainer verifies that the serving and training engines agree across compilation and differentiation boundaries.
我们如何在 TPU 上构建 zero-TIMHow we built zero-TIM on TPU
实现 Zero-TIM 并不需要将采样器和训练器合并为一个单体引擎。相反,我们采用一套具有通用性的四步方案,在多主机 TPU 网格上衔接彼此独立的服务与训练流水线:锁定分片内的内核累加方式,规定跨分片归约的顺序,统一 logprob 评分的尾部计算,并为服务内核封装自定义求导规则。Achieving Zero-TIM does not require merging the sampler and trainer into a single monolithic engine. Instead, we use a generalizable four-part recipe that bridges separate serving and training pipelines across multi-host TPU meshes: locking within-shard kernel accumulation, ordering cross-shard reductions, standardizing the logprob scoring tail, and wrapping serving kernels with custom differentiation rules.
修复分片内算术运算Fix within-shard arithmetic
在每个张量并行 rank 内,批次不变的 Pallas 内核控制累加顺序和中间精度。投影内核按顺序遍历固定的收缩块,使归约分块方式不受 token 行数影响。部分乘积以 float32 累加,并显式转换输出类型。Inside each tensor-parallel rank, batch-invariant Pallas kernels control accumulation order and intermediate precision. Projection kernels traverse fixed contraction blocks in order, keeping the reduction blocking independent of token-row count. Partial products accumulate in float32, with explicit output casts.
生产内核会在遍历分块之前初始化其临时累加器,然后对每个分块应用此核心:The production kernel initializes its scratch accumulator before the tile traversal, then applies this core to each tile:
input_tile = x_ref[...]
weight_tile = y_ref[...]
partial = jnp.dot(
input_tile,
weight_tile,
preferred_element_type=jnp.float32,
)
acc_ref[...] = acc_ref[...] + partial
out_ref[...] = acc_ref[...].astype(out_ref.dtype)
下一个分块会从 float32 累加器继续计算,而不是使用类型转换后的输出。此构造涵盖 attention 和 MLP 投影以及 LM head。专用内核修正了 RMSNorm 归约和 SwiGLU 的中间类型转换。现有的 Pallas 分页注意力前向实现予以保留。The next tile continues from the float32 accumulator, not the cast output. This construction covers the attention and MLP projections and the LM head. Dedicated kernels fix RMSNorm reductions and SwiGLU’s intermediate casts. The existing Pallas paged-attention forward is retained.
对跨分片归约操作进行排序Order cross-shard reductions
对于行并行投影,每个张量并行 rank 都会生成部分输出。我们将通信与加法分开:ppermute 传输这些部分输出,然后每个 rank 按相同的源 rank 顺序将它们相加。For row-parallel projections, each tensor-parallel rank produces a partial output. We separate communication from addition: ppermute transports the partials, then every rank adds them in the same source-rank order.
归约顺序由程序显式指定,而非由 collective 的实现来选择。The reduction order is explicit in the program rather than selected by a collective implementation.
共享 action-logprob 路径Share the action-logprob path
对齐必须超越模型 logits,延伸到采样动作的概率。解码、预填充和训练器应用匹配的采样变换,使用相同的固定 Pallas log-softmax 构造,并选取记录的动作 token。Alignment must extend beyond model logits to the probability of the sampled action. Decode, prefill, and trainer apply matching sampling transforms, use the same fixed Pallas log-softmax construction, and select the recorded action token.
Prefill 和 trainer 对 rollout 期间生成的动作进行评分,而不是选择其他动作。我们还会在环境轮次之间保留采样得到的 token ID,以便每条路径都评估相同的 token 历史。Prefill and trainer score the action generated during rollout rather than choosing another action. We also preserve sampled token IDs across environment turns so that every path evaluates the same token history.
对服务端前向过程求导Differentiate the serving forward
训练器复用了服务端的预填充计算。自定义向量-雅可比积(VJP)保留服务端内核用于前向计算,并提供相应的反向传播规则。矩阵乘法示例展示了这种分离:The trainer reuses the serving prefill computation. Custom vector–Jacobian products retain the serving kernels for forward evaluation and provide their backward rules. The matmul example shows this separation:
@jax.custom_vjp
def serving_matmul(inputs, weights):
return pallas_matmul(inputs, weights)
def matmul_forward(inputs, weights):
output = pallas_matmul(inputs, weights)
return output, (inputs, weights)
def matmul_backward(saved, output_gradient):
inputs, weights = saved
_, pullback = jax.vjp(
differentiable_matmul,
inputs,
weights,
)
return pullback(output_gradient)
serving_matmul.defvjp(matmul_forward, matmul_backward)
可微分副本会复现内核的累积与类型转换,但仅用于构造拉回函数。前向值仍由服务端 Pallas 内核提供。The differentiable replica mirrors the kernel’s accumulation and casts, but is used only to construct the pullback. Forward values still come from the serving Pallas kernel.
在可微分的 JAX 程序中执行前向传播的训练位置。我们通过 XLA_FLAGS 将 --xla_allow_excess_precision=false 传递给编译器进程,以限制 Pallas 内核周边操作中超出需要的中间精度。Training places that forward inside a differentiated JAX program. We pass --xla_allow_excess_precision=false through XLA_FLAGS to the compiler process, constraining excess intermediate precision in the operations surrounding the Pallas kernels.
长轨迹按固定大小的分块进行评估,并沿用分页 KV 缓存。所有动作的对数概率都会纳入完整训练批次的 RL 损失。反向传播会通过这些缓存连接传递梯度,并在优化器更新前合并各项参数梯度贡献。Long trajectories are evaluated in fixed-size chunks, carrying the paged KV cache forward. All action logprobs feed the complete train-batch RL loss. The reverse pass propagates gradients through those cache connections and combines parameter-gradient contributions before the optimizer update.
将前沿强化学习的数值对齐带到 TPUBringing frontier RL numerical alignment to TPU
在 AI 系统社区中,消除训练与推理不匹配已迅速成为稳定大规模 RL 收敛的前沿要求。近期的开源项目——包括 vLLM 与 TorchTitan,以及 RadixArk/LMSys Miles——展示了批次不变内核和按位数值对齐如何防止策略优化过程中的离策略漂移。Across the AI systems community, eliminating train–inference mismatch has rapidly become a state-of-the-art requirement for stabilizing large-scale RL convergence. Recent open-source efforts—including vLLM with TorchTitan and RadixArk/LMSys Miles—have demonstrated how batch-invariant kernels and bitwise numerical alignment prevent off-policy drift during policy optimization.
我们的工作在 Tunix 中提供了这一契约的开源、模块化 JAX/XLA 和 Pallas TPU 实现。在由多主机 64 个 TPU v5p 组成的网格(DP8×TP8)上完成验证后,这些内核与集体通信模式为团队提供了一套可复用的蓝图,可用于在分布式 JAX/TPU 技术栈中实现逐位精确的 on-policy 强化学习。Our work delivers an open-source, modular JAX/XLA and Pallas implementation of this contract for TPU in Tunix. Verified across a multi-host 64 TPU v5p (DP8×TP8) mesh, these kernel and collective patterns provide a reusable blueprint that teams can adopt to achieve bit-exact on-policy RL across distributed JAX/TPU stacks.
评估与结果Evaluation and results
为了对我们的 TPU 内核进行基准测试,我们在合成 FrozenLake 环境中运行 200 步数值验证测试,并使用公开的 Qwen3-8B 检查点作为基线测试用例。测试使用 64 个 TPU v5p 芯片和 DP8×TP8 网格。训练方案采用 GSPO-token 损失和留一法优势值。我们比较了标准训练(使用 trainer-old 的 logprobs,且不进行额外的采样器校正)、令牌级截断重要性采样(TIS)和 Zero-TIM。To benchmark our TPU kernels, we run a 200-step numerical verification test on the synthetic FrozenLake environment using a public Qwen3-8B checkpoint as a baseline test case using 64 TPU v5p chips with a DP8×TP8 mesh. The recipe uses a GSPO-token loss with leave-one-out advantages. We compare Standard training with trainer-old logprobs and no additional sampler correction, token-level truncated importance sampling (TIS), and Zero-TIM.
Zero-TIM 配置也采用 token-in/token-out (TiTO) 处理,以便在不同环境轮次之间保留采样得到的 token ID。对比运行则保留现有的分词路径。The Zero-TIM configuration also uses token-in/token-out (TiTO) handling to preserve sampled token IDs across environment turns. The comparison runs retain their existing tokenization paths.
在此窗口内的每个记录步,Zero-TIM 的采样器与训练器对数概率差的平均绝对值均为零,同时其训练求解率不断提升。Standard 和 TIS 仍存在非零差值:TIS 会调整这些差值对更新的贡献,但不会消除底层的不匹配。在这些运行中,Zero-TIM 达到了更高的观测求解率。Zero-TIM records zero mean absolute sampler–trainer logprob difference at every logged step in this window, while its training solve rate increases. Standard and TIS retain nonzero differences: TIS adjusts their contribution to the update without removing the underlying mismatch. Zero-TIM reaches higher observed solve rates in these runs.
代码和更新Code and updates
我们将 Zero-TIM 原型作为 Tunix 的一部分开发。Tunix 是 Google 开源、原生支持 JAX 的库,用于在 Cloud TPU 上进行 LLM 强化学习和后训练。其内核模式和三方验证契约在设计上采用模块化,因此可以轻松应用于现有的多主机 JAX/TPU 服务与训练流水线;我们也在积极扩展对线性注意力和混合专家(MoE)架构的支持。We developed Zero-TIM prototype as part of Tunix, Google's open-source, JAX-native library for LLM RL and post-training on Cloud TPU. The kernel patterns and three-way verification contract are modular by design—making them straightforward to adopt across existing multi-host JAX/TPU serving and training pipelines—and we are actively extending support to linear-attention and Mixture-of-Experts (MoE) architectures.
预览当前实现的效果Preview the current implementation