LLM 对齐的焦点已迅速从静态聊天机器人对齐转向动态的智能体工作流。如今的模型不再只是对话——它们会执行多步推理、调用外部 API,并与复杂环境交互。
训练推理智能体会遇到特殊的挑战和瓶颈。近期智能体 RL 训练的演进,将这一过程从单轮对齐转变为多轮决策,涉及复杂的环境交互和工具使用。这一转变在基础设施层面带来了关于 rollout 性能和效率的新挑战;当智能体暂停以执行代码、查询数据库或等待网络搜索时,昂贵的 AI 加速器利用率会骤降,因为 TPU 会闲置等待环境步骤完成。
Tunix——Google 的后训练库——在其最新版本中原生解决了这一瓶颈,引入了一个高效、可组合的框架,用于大规模训练 LLM 智能体。Tunix 从两个方面让加速器保持充分利用:
- 异步 Rollout:一个高并发 rollout 引擎将 TPU 执行与主机侧环境延迟(如网络 I/O 或工具执行)完全解耦。
- 无屏障流水线:一种动态生产者-消费者架构持续将变长轨迹分批并流式传输给训练器,防止流水线停滞。
除了编排之外,智能体强化学习还需要专门的可观测性。虽然像 XProf 这样的标准性能分析器能提供深度的算子级追踪,但其高昂的开销使其只能用于短时、零星的采集。Tunix 引入了围绕领域特定强化学习指标直接构建的持续、轻量级插桩。通过将这些高层循环指标与 TPU 时间线相关联,开发者可以获得执行效率的全局视图,从而快速发现并解决系统瓶颈。
最终,Tunix 的构建目标是最大化 TPU 吞吐量、保持环境的模块化,并让多轮训练效率完全透明。以下是其底层工作原理。
1. 异步与解耦式 rollout:近乎零空闲时间,最大化吞吐量
要实现硬件吞吐量的峰值,就意味着让 TPU 始终保持忙碌。Tunix 通过将异步 rollout 与解耦式流水线相结合来实现这一点——前者消除执行气泡和掉队者,后者持续向训练器流式传输数据。
异步 rollout
在智能体强化学习中,轨迹生成(rollout)是最耗时的阶段。然而,传统的同步 rollout 架构会产生两个主要问题,如下图所示。
- 执行气泡:当 rollout 同步等待环境初始化,或等待返回状态和奖励时,会在加速器上产生执行气泡,降低效率。
- 长尾效应:批量生成同样容易受到长尾问题的影响,即整体延迟取决于一组中最慢的那条轨迹。
Tunix 通过一个异步轨迹收集引擎解决了这一问题。
- 高并发执行:利用 Python 的asyncio在我们的
RolloutOrchestrator中,该框架管理着大量并发的智能体与环境交互池。当一个智能体因等待宿主机侧的工具执行而暂停时,推理引擎会立即转向为其他活跃轨迹生成 token。 - 异步 vLLM 与 SGLang 集成: Tunix 原生集成了 vLLM-TPU 和 SGLang-Jax 等高性能推理引擎。通过启用异步请求处理,该引擎确保在 TPU 上实现非阻塞采样和最大并发。
该架构将模型推理、工具执行和奖励计算完全重叠,从而保持高硬件利用率。
解耦的 Rollout 与训练流水线
虽然异步 rollout 解决了轨迹生成的瓶颈,但在端到端 RL 工作流中,硬件效率面临的另一个关键挑战是如何将动态的、变长的、可能呈长尾分布的 rollout 与严格同步的训练循环衔接起来。一种朴素的做法依赖同步点,强制加速器等待整批轨迹全部完成后才能启动训练步骤,从而使训练器 TPU 处于饥饿状态。
Tunix 通过将 rollout 与训练解耦为持续的生产者-消费者流水线(如下图所示)消除了这一瓶颈:
- 生产者:异步 rollout 编排器持续将已完成的轨迹产出到高吞吐队列中。
- 消费者:
AgenticRLLearner从该队列中消费。对于 GRPO 这类需要针对每个提示词生成多条推理路径以计算组优势的算法,Tunix 会即时对这些异步轨迹进行动态分组。
一旦某个轨迹组完成,它就会被后处理、评分,并直接流式送入训练器。该流水线确保同步训练器持续获得数据供给,从而最大化端到端吞吐量。
2. 可组合的智能体与环境抽象——即插即用的 OSS 环境
RL 框架的一个主要痛点是算法与环境循环之间的刚性耦合。要修改代码库以支持新的开源软件(OSS)基准测试,如 SWE-bench、WebArena,或自定义游戏引擎,往往需要大规模重写。
Tunix 通过解耦、可组合的架构解决了这一问题。通过暴露清晰的 API 边界,Tunix 自动化了步骤调用和生命周期管理,让你能够完全专注于核心交互逻辑。
- 智能体层:管理提示词格式化、动作生成和对话历史。它会自动应用策略模型的聊天解析器,并在多轮边界处保留特殊 token——这对于确保严格的 Token-In, Token-Out(TITO)行为至关重要。你可以通过继承
ConversationAgentBase轻松自定义生成逻辑。 - 环境层:开箱即用,Tunix 提供了预构建的
TaskEnvironment和ToolEnvironment类。你也可以继承BaseTaskEnv来对接任何外部系统。Tunix 会自动处理多轮 episode 生命周期、观测路由和奖励处理。
为什么这很重要: 你可以在几分钟内接入任何开源 RL 环境。由于智能体和环境逻辑与训练工作流完全解耦,将单轮数学验证器替换为交互式 bash 终端无需对训练代码做任何修改。为了展示这种可组合设计的强大之处,我们接下来展示几个示例,说明新的智能体、模型或环境可以多么轻松地被使用。你可以在我们的 recipes 中找到更详细的定制 Agent/Env 示例。
示例 1:预置智能体 vs. 自定义智能体
Tunix 提供了诸如 ModelAgent 和 ToolAgent 这样的内置类,通过配置即可立即使用。
from tunix.rl.agentic.agentic_grpo_learner import GRPOLearner
from tunix.rl.agentic.agents.model_agent import ModelAgent, ToolAgent
# Non tool calling single turn agent
learner = GRPOLearner(
agent_class=ModelAgent,
agent_kwargs={"system_prompt": "my system prompt"},
...
)
# Customized tool call agent
tool_map = {"calculator": CustomizedCalculatorClass, ...}
learner = GRPOLearner(
agent_class=ToolAgent,
agent_kwargs={
"system_prompt": "my system prompt",
"tool_parser_name": "gemma",
"tool_map": tool_map,
},
...
) 或者,你可以构建自己的自定义 Agent,并添加处理模型响应的特定逻辑。Tunix 会自动将此智能体接入端到端训练工作流。例如 SWEAgent、FrozenLakeAgent
from tunix.rl.agentic.agents.base_agent import ConversationAgentBase
from tunix.rl.agentic.agents import agent_types
# Bring your own agent!
# Notice how the agent doesn't need to know anything about the model (if it is Qwen, Llama, or Gemma)
class MyAgent(ConversationAgentBase):
def __init__(self, args):
...
def update_from_model(self, response: str, **kwargs) -> agent_types.Action:
# Custom logic to process the raw response (e.g., extracting <answer> tags)
...
# Tunix automatically wires up the e2e workflow
learner = GRPOLearner(agent_class=MyAgent, agent_kwargs={...}, ...) 示例 2:引入自定义环境
与 Agent 类似,Tunix 提供了多种预置环境,包括 TaskEnvironment、ToolEnvironment。或者,你也可以通过仅实现几个主要 API 来引入自己的自定义环境,包括任何开源环境,例如下面的 Gymnasium 示例。
import gymnasium as gym
from tunix.rl.agentic.agentic_grpo_learner import GRPOLearner
from tunix.rl.agentic.environments.base_environment import BaseTaskEnv, EnvStepResult
# You only need to focus on the core logic of environment interactions, and Tunix will automatically handle the rest of the lifecycle management and function invocation.
class MyEnv(BaseTaskEnv):
def _initial_observation(self):
# handle env creation and initial observation
self.env = gym.make("your_chosen_env")
observation, info = self.env.reset(seed=42)
return observation
def _step_impl(self, action):
# compute observation, reward, done, info
action = self.env.action_space.sample()
obs, reward, done, info = self.env.step(action)
return EnvStepResult(obs, reward, done, info)
def close(self):
self.env.close() # clean up env after trajectory is done
learner = GRPOLearner(env_class=MyEnv, ...) 3. 消除黑盒:RL 专属轻量级性能分析
在大规模运行异步智能体训练时,传统日志记录已力不从心。你需要细粒度且面向特定领域的可观测性来定位效率问题:瓶颈是在生成阶段吗?是工具调用耗时过长吗?还是数据加载器太慢?
像 XProf 这样的标准性能分析工具能提供详细的操作级追踪,帮助理解内核与模型执行等微观层面的性能。然而,用这些工具捕获长时间跨度的追踪通常成本高得难以承受,而且在底层数据的噪声中识别宏观层面的瓶颈依然困难。对于智能体 RL 的复杂工作流,开发者需要一种轻量级、宏观层面的视图,它建立在直接映射到 RL 各阶段的领域特定指标之上。
Tunix 通过精心追踪一组最小化的关键 RL 专属指标来呈现这一全局图景,这些指标既代表全局流水线(rollout、训练和权重同步各阶段如何交互),也代表重要的子步骤(每次模型调用、环境交互等)。由于这些指标轻量,它们会在整个训练任务期间持续运行。用户可以快速定位工作流在全局层面卡在哪里,然后再部署像 XProf 这样的工具进行有针对性的进一步调试。
上图展示了一个从多轮智能体训练任务中捕获的 Perfetto 追踪,详细呈现了跨 CPU 线程和 TPU 设备的分阶段执行时间线。如该追踪所示,TPU 设备的利用率远高于 CPU 线程,后者的空闲时间主要来自环境执行延迟。
这种对分阶段 RL 流水线的宏观层面追踪让你能够:
- 精准定位 TPU 饥饿:可视化 Python 工具调用或环境执行阻塞异步流水线的确切时间点。反过来,它也能让你确认并行 rollout 是否成功重叠,从而让加速器保持饱和运转。
- 验证流水线对齐:追踪各宏观阶段的精确时序,确保它们对齐且不引入隐藏的延迟气泡。你可以轻松验证训练器没有在等待 rollout 生成,或者权重同步没有造成严重的执行延迟。
- 优化训练配置:利用指标数据动态调优性能。例如,你可以通过将线程池直接与 TPU 空闲时间相关联来调整最大 rollout 并发数,或者根据数据生成速率和 HBM 约束来优化训练 micro-batch 大小。
Tunix 将分布式多轮 RL 的“黑箱”转变为训练任务透明、可优化的时间线。
Tunix 与生态系统的对比
如果你正在为智能体 RL 评估框架,以下是 Tunix 的突出之处:
- 对比 OpenRLHF / veRL: OpenRLHF 和 veRL 借助 Ray + vLLM 取得了显著进展。然而,它们主要面向 PyTorch 生态构建。Tunix 将这一能力原生带入 JAX/TPU 生态。Tunix 无缝构建于 JAX、Flax 和 Optax 之上,提供原生的 Pathways 多主机分布式训练,充分利用 XLA 的编译器优化。
- 对比 Hugging Face TRL: TRL 非常适合标准的单轮 SFT(监督微调)和 RLHF(基于人类反馈的强化学习)。然而,编排复杂的多轮异步循环往往需要大量自定义胶水代码。Tunix 将多轮、工具使用环境作为一等公民开箱即用。
- 对比 Ray RLlib: RLlib 是一个全面的、通用型强化学习利器。然而,将现代 LLM 原生映射到加速器上共享权重而不带来沉重开销,是件复杂的事。Tunix 颠覆了这一局面:它是一个 LLM 优先的库,将高性能强化学习直接带入原生 LLM 服务基础设施。
今天就开始构建你的智能体
无论你是在复现 SOTA 推理模型、微调 Gemma 或 Qwen 系列使其学会“思考”,还是部署复杂的多智能体系统,Tunix 都为下一代推理智能体提供了所需的高性能基础。今天就开始构建吧!
- 🌟 给仓库点星并探索代码: github.com/google/tunix
- 📖 示例配方: SWE 编程智能体、数学、游戏智能体。
- 📖 阅读文档: 在 tunix.readthedocs.io 深入了解我们的智能体 RL 架构
- 🚀 试试快速上手: 进入我们的
/examples文件夹,探索各种示例配方,今天就运行你的第一个训练任务!
Tunix 正由 Google 及更广泛的社区积极进行开源开发。如果你正在构建下一代推理智能体,欢迎来我们的 GitHub Issues 留言,告诉我们你正在接入哪些环境。
The focus of LLM alignment has rapidly shifted from static chatbot alignment to dynamic agentic workflows. Today’s models don't just talk—they execute multi-step reasoning, call external APIs, and interact with complex environments.
Training reasoning agents encounters special challenges and bottlenecks. The recent evolution of agentic RL training shifts the process from single-turn alignment to multi-turn decision-making with complex environment interactions and tool usage. This shift raises new challenges on the infrastructure side for rollout performance and efficiency; when an agent pauses to execute code, query a database, or wait on a web search, the expensive AI accelerator utilization plummets as TPUs sit idle waiting for environment steps.
Tunix—Google’s post-training library—natively solves this bottleneck in its latest release, introducing an efficient, composable framework for training LLM agents at scale. Tunix keeps accelerators fully utilized on two fronts:
- Asynchronous Rollouts: A high-concurrency rollout engine completely decouples TPU execution from host-side environment latency (like network I/O or tool execution).
- Barrier-Free Pipelining: A dynamic producer-consumer architecture constantly batches and streams variable-length trajectories to the trainer, preventing pipeline stalls.
Beyond orchestration, agentic RL requires specialized observability. While standard profilers like XProf offer deep operator-level traces, their high overhead limits them to short, sporadic captures. Tunix introduces continuous, lightweight instrumentation built directly around domain-specific RL metrics. By correlating these high-level loop metrics with TPU timelines, developers get a global view of execution efficiency to quickly spot and resolve system bottlenecks.
Ultimately, Tunix is built to maximize TPU throughput, keep environments modular, and make multi-turn training efficiency fully transparent. Here is how it works under the hood.
1. Asynchronous & Decoupled Rollouts: Near-Zero Idle Time, Maximum Throughput
Achieving peak hardware throughput means keeping TPUs constantly busy. Tunix accomplishes this by combining asynchronous rollouts to eliminate execution bubbles and stragglers with a decoupled pipeline that continuously streams data to the trainer.
Asynchronous Rollouts
In Agentic RL, trajectory generation (rollout) is the most time-consuming phase. However, the traditional synchronous rollout architecture creates two major problems, as depicted in the figure below.
- Execution bubbles: when the rollout synchronously waits for an environment to initialize, or return a state and reward, it will create execution bubbles in the accelerator and degrade efficiency.
- Straggler effect: Batched generation is also vulnerable to long-tail problems, where overall latency is dictated by the slowest trajectory in the group.
Tunix solves this with an Asynchronous Trajectory Collector Engine.
- High-Concurrency Execution: Leveraging Python’s asyncio within our
RolloutOrchestrator, the framework manages massive pools of concurrent agent-environment interactions. While one agent pauses for a host-side tool execution, the inference engine immediately pivots to generate tokens for other active trajectories. - Async vLLM & SGLang Integration: Tunix natively integrates with performant inference engines like vLLM-TPU and SGLang-Jax. By enabling async request handling, the engine ensures non-blocking sampling and maximum concurrency on the TPU.
This architecture completely overlaps model inference, tool execution, and reward computation, preserving high hardware utilization.
Decoupled Rollout & Training Pipelining
While async rollouts solve trajectory generation bottlenecks, another critical challenge for hardware efficiency in the end-to-end RL workflow is bridging dynamic, variable-length, and potentially long-tail rollouts with a strictly synchronous training loop. A naive approach relies on a synchronization point that forces the accelerator to wait until an entire batch of trajectories is complete before initiating the training step, starving the trainer TPU.
Tunix eliminates this bottleneck by decoupling rollout and training into a continuous producer-consumer pipeline (illustrated in the diagram below):
- The Producer: The async rollout orchestrator continuously yields completed trajectories into a high-throughput queue.
- The Consumer: The
AgenticRLLearnerconsumes from this queue. For algorithms like GRPO—which require multiple reasoning paths per prompt to compute group advantages—Tunix dynamically groups these asynchronous trajectories on the fly.
The moment a trajectory group is complete, it is post-processed, scored, and streamed directly into the trainer. This pipeline ensures the synchronous trainer is constantly fed, maximizing end-to-end throughput.
2. Composable Agent and Environment Abstractions – Plug-and-Play OSS Environments
A major friction point in RL frameworks is the rigid coupling of the algorithm to the environment loop. Modifying a codebase to support a new open-source software (OSS) benchmark like SWE-bench, WebArena, or a custom game engine often requires a massive rewrite.
Tunix resolves this with a decoupled, composable architecture. By exposing a clean API boundary, Tunix automates step invocation and lifecycle management so you can focus entirely on core interaction logic.
- The Agent Layer: Manages prompt formatting, action generation, and conversation histories. It automatically applies the policy model's chat parser and preserves special tokens at multi-turn boundaries—critical for ensuring strict Token-In, Token-Out (TITO) behavior. You can easily customize generation logic by subclassing
ConversationAgentBase. - The Environment Layer: Out of the box, Tunix provides prebuilt
TaskEnvironmentandToolEnvironmentclasses. You can also inherit fromBaseTaskEnvto interface with any external system. Tunix handles multi-turn episode lifecycles, observation routing, and reward processing automatically.
Why it matters: You can onboard any open-source RL environment in minutes. Because the agent and environment logic are completely decoupled from the training workflow, swapping a single-turn math verifier for an interactive bash terminal requires zero modifications to your training code. To demonstrate the power of this composable design, we next showcase a few examples of how easily new agents, models, or environments can be used. You can find more detailed examples of customized Agent/Env in our recipes.
Example 1: Prebuilt vs. Custom Agents
Tunix offers built-in classes like ModelAgent and ToolAgent that work immediately via configuration.
from tunix.rl.agentic.agentic_grpo_learner import GRPOLearner
from tunix.rl.agentic.agents.model_agent import ModelAgent, ToolAgent
# Non tool calling single turn agent
learner = GRPOLearner(
agent_class=ModelAgent,
agent_kwargs={"system_prompt": "my system prompt"},
...
)
# Customized tool call agent
tool_map = {"calculator": CustomizedCalculatorClass, ...}
learner = GRPOLearner(
agent_class=ToolAgent,
agent_kwargs={
"system_prompt": "my system prompt",
"tool_parser_name": "gemma",
"tool_map": tool_map,
},
...
) Alternatively, you can build your own custom Agent and add specific logic on how to process the model responses. Tunix will automatically wire this agent in the end to end training workflow. E.g. SWEAgent, FrozenLakeAgent
from tunix.rl.agentic.agents.base_agent import ConversationAgentBase
from tunix.rl.agentic.agents import agent_types
# Bring your own agent!
# Notice how the agent doesn't need to know anything about the model (if it is Qwen, Llama, or Gemma)
class MyAgent(ConversationAgentBase):
def __init__(self, args):
...
def update_from_model(self, response: str, **kwargs) -> agent_types.Action:
# Custom logic to process the raw response (e.g., extracting <answer> tags)
...
# Tunix automatically wires up the e2e workflow
learner = GRPOLearner(agent_class=MyAgent, agent_kwargs={...}, ...) Example 2: Bringing in Custom Environments
Similar to Agents, Tunix offers a number of pre-built environments including TaskEnvironment, ToolEnvironment. Alternatively, you can also bring your own custom environment by simply implementing a few main APIs, including any open source environment such as the Gymnasium example below.
import gymnasium as gym
from tunix.rl.agentic.agentic_grpo_learner import GRPOLearner
from tunix.rl.agentic.environments.base_environment import BaseTaskEnv, EnvStepResult
# You only need to focus on the core logic of environment interactions, and Tunix will automatically handle the rest of the lifecycle management and function invocation.
class MyEnv(BaseTaskEnv):
def _initial_observation(self):
# handle env creation and initial observation
self.env = gym.make("your_chosen_env")
observation, info = self.env.reset(seed=42)
return observation
def _step_impl(self, action):
# compute observation, reward, done, info
action = self.env.action_space.sample()
obs, reward, done, info = self.env.step(action)
return EnvStepResult(obs, reward, done, info)
def close(self):
self.env.close() # clean up env after trajectory is done
learner = GRPOLearner(env_class=MyEnv, ...) 3. Eliminating the Black Box: RL-Specific Lightweight Profiling
When running asynchronous agentic training at scale, traditional logging falls short. You need granular yet domain-specific visibility to identify efficiency problems: Is the bottleneck in the generation phase? Is the tool call taking too much time? Or is the data-loader too slow?
Standard profilers like XProf provide detailed, op-level traces to understand micro-level performance like kernel and model execution. However, capturing long-spanning traces with these tools is typically cost-prohibitive, and identifying macro-level bottlenecks within the noise of low-level data remains difficult. For the complex workflows of agentic RL, developers need a lightweight, macro-level view built on domain-specific metrics that map directly to RL stages.
Tunix delivers this big picture by carefully tracking a minimal set of critical RL-specific metrics that represent both the global pipeline (how rollout, training, and weight sync phases interact) and important sub-steps (each model call, environment interaction, etc.). Because they are lightweight, these metrics run continuously throughout the entire training job. Users can quickly identify where the workflow is stalling globally, and then deploy a tool like XProf for targeted, further debugging.
The figure above illustrates a Perfetto trace captured from a multi-turn agentic training job, detailing the staged execution timelines across CPU threads and TPU devices. As demonstrated by the trace, TPU device utilization is much higher than that of the CPU threads, whose idle time is primarily due to environment execution latency.
This macro-level tracing of staged RL pipelines enables you to:
- Pinpoint TPU Starvation: Visualize the exact time a Python tool call or environment execution blocks the asynchronous pipeline. Conversely, it lets you confirm that parallel rollouts successfully overlap to keep accelerators saturated.
- Verify Pipeline Alignment: Track the precise timing of macro-stages to ensure they align without introducing hidden latency bubbles. You can easily verify that the trainer isn't waiting on rollout generation, or that weight synchronization isn't causing severe execution delays.
- Optimize Training Configuration: Tune performance dynamically using metric data. For example, you can adjust max rollout concurrency by correlating thread pools directly against TPU idle time, or optimize training micro-batch sizes based on data generation rates and HBM constraints.
Tunix turns the "black box" of distributed multi-turn RL into a transparent, optimizable timeline for the training job.
How Tunix Compares to the Ecosystem
If you are evaluating frameworks for Agentic RL, here is how Tunix stands out:
- vs. OpenRLHF / veRL: OpenRLHF and veRL have made significant strides using Ray + vLLM. However, they are built primarily for the PyTorch ecosystem. Tunix brings this capability natively to the JAX/TPU ecosystem. Sitting seamlessly on top of JAX, Flax, and Optax, Tunix delivers native Pathways multi-host distributed training, leveraging XLA's compiler optimizations.
- vs. Hugging Face TRL: TRL is well-suited for standard single-turn SFT (Supervised Fine-Tuning) and RLHF (Reinforcement Learning from Human Feedback). However, orchestrating complex, multi-turn async loops often requires significant custom glue code. Tunix makes multi-turn, tool-use environments a first-class citizen out-of-the-box.
- vs. Ray RLlib: RLlib is a comprehensive, general-purpose RL powerhouse. Yet, mapping modern LLMs natively to share weights on accelerators without heavy overhead is complex. Tunix flips the script: it is an LLM-first library that brings high-performance RL directly to the native LLM serving infrastructure.
Start Building Your Agents Today
Whether you are reproducing SOTA reasoning models, fine-tuning the Gemma or Qwen families to "think," or deploying complex multi-agent systems, Tunix provides the high-performance foundation needed for the next generation of reasoning agents. Start building today!
- 🌟 Star the Repo & Explore the Code: github.com/google/tunix
- 📖 Recipes: SWE coding agent, math, gaming agent.
- 📖 Read the Docs: Deep-dive into our Agentic RL architecture at tunix.readthedocs.io
- 🚀 Try the Quick Start: Jump into our
/examplesfolder to explore a variety of recipes and run your first training job today!
Tunix is under active open-source development by Google and the wider community. If you are building the next generation of reasoning agents, drop by our GitHub Issues and let us know what environments you are plugging in.