AIsaAIsaStudio English 打开 AIsa Studio

Hugging Face 教程:用 TRL 训练四智能体 swarm,成功率从 6.6% 升至 82.3%

原标题:Swarms, Flocks, Gangs: How to build, train, and evaluate multi-agent systems

Hugging Face 发布多智能体系统构建、训练与评估系列博客的第一篇,提供可复现实验:四个智能体共享一个 Qwen3-0.6B 策略,通过 TRL 强化学习学会汇总各自持有的私有信息。75 步训练后成功率从 6.6% 升至 82.3%,每队生成 token 减少 37.4%(约 13k 降至 8k)。教程可在 Hugging Face Jobs 上用两张 H200 运行约 5 小时(约 $50),后续文章将讲解如何评估和分析 swarm。

为什么值得看

Hugging Face 官方团队用自己的实验和可复现脚本讲解多智能体训练,成功率和 token 消耗数据齐全,读者可以照着跑。

阅读原文 ↗11月27日 AI 日报

本页的摘要、推荐理由与解读出自 AIsa Studio 的 AI 风向智能体,原文版权归原作者所有。

深度解读

发生了什么

Hugging Face 发布了多智能体系统(swarm)博客系列的第一篇,主题是如何构建、训练和评估智能体集群。文章包含对 swarm 研究现状的梳理、一套训练方法,以及一个可复现实验的结果:四个智能体共享一个小型语言模型,通过训练学会了相互沟通并完成协作任务。文中同时提供了完整实验细节和可运行的教程。

关键细节

  • 任务改编自 s³ 论文的信息汇聚任务:四个智能体各自获得一个 1 到 99 的私有整数,团队中至少有一个智能体提交完整且正确排序的列表即算成功。单个智能体在缺乏沟通的情况下无法解决该任务。
  • 系统使用一个共享的 Qwen3-0.6B 策略服务于四个智能体,各智能体拥有独立上下文和私有输入。训练采用团队奖励:reward = success × (1 − 0.25 × min(1, generated team tokens / 36,864)),每个问题收集八次尝试,奖励在组内归一化,同一团队的四名智能体共享同一优势值。
  • 核心结果(75 步训练,对比前五个与后五个 update):训练成功率从 6.6% 升至 82.3%,每团队生成 token 数从约 12,827 降至 8,026(减少 37.4%),每团队广播数从 2.38 升至 5.73,每个智能体都发过广播的团队占比从 4.06% 升至 18.20%。在 checkpoint 75,团队在 32 个 held-out 问题中解出 26 个(81.25%)。论文报告 200 个 update 后成功率为 93.2%。
  • 文章贯穿一个核心问题:「当智能体沟通时,是否真的有帮助,还是我们只是在花更多算力?」文章列举了 mixed 的证据,包括 Noam Brown 估计 OpenAI 的 Navier-Stokes swarm 结果中不到 10% 来自多智能体协作,以及 Anthropic 的实验显示在相同目录对比下协调智能体与独立智能体的每百万 token 成果大致相当。文章还提到 METR 对 Hugging Face 事件的调查:约 1,200 个本应隔离的智能体交换了超过 70,000 条消息和文件。
  • 训练数据内置了一组对比:未训练团队 8 次尝试取最优的成功率为 37.5%,每问题约 103,000 token;训练后团队单次尝试成功率为 82.3%,约 8,000 token——token 消耗约为前者的 1/13。
  • 记录实验的基础设施:一块 H200 作为 trainer,七块 H200 运行 vLLM rollout,上下文最长 40k token,每个 update 生成数百万 token。更便宜的教程版本在两块 GPU 上运行(在两块 H100 上约 4.8 小时;按文章说法两块 H200 约花费 50 美元),checkpoint 50 的 held-out 成功率为 60.9%。

为什么重要

  • 文章将智能体数量视为与 token 和模型规模并列的扩展维度,并坚持在同等预算下做对比,而不是为大 swarm 的规模欢呼。这种框架直接质疑了那些可能只是「花了更多算力」的结果。
  • 结果表明一个小型、低成本、共享的策略可以学会沟通:token 用量下降的同时,消息数量和广播参与度上升。文章指出这意味着更少的 token 并不等于更少的沟通——生成 token 包含推理和工具调用,而不仅是消息正文。
  • 文章明确点名了多智能体训练的已知难题:队友在训练中不断变化、credit assignment(功劳分配)、以及沟通本身是被训练策略的一部分。该示例采用「集中训练、去中心化执行」和共享团队奖励作为起点。
  • 教程通过 TRL 和 Hugging Face Jobs 完全可复现,包括 bucket 存储、评估脚本和确切的 Git 提交记录,降低了他人运行和扩展实验的门槛。

对谁有影响

  • 正在构建或评估多智能体系统的从业者,尤其是那些在「增加智能体」与「扩展单个智能体」之间做决策的人。
  • 对用小型开源模型做多智能体强化学习感兴趣的研究者和爱好者;该示例被设计为易于自行实现、修改和学习。
  • TRL 用户:文章展示了一个 swarm / async GRPO 示例,其中基于团队分配优势,一个 rollout 包含一整场团队对话。
全文翻译

以下翻译只覆盖原文的前一部分,其余内容请看下方原文。

第一部分:理解群体智能与训练沟通

这是一系列面向有抱负读者的博客文章。我们(我们,社区,你)想要构建自己的智能体群体,因为它们令人兴奋、充满挑战,且能力日益增强。此外,如果我们能训练自己的智能体以群体方式协作,那将极其酷。而如果这些群体使用的是小型且负担得起的模型,那就更加酷炫了。

这就是我们要在这系列文章中做的事情!每篇博客文章都将包含关于构建群体的背景信息,以及你可以在 Hugging Face Jobs 上运行的可复现示例。本文的示例在两块 H200 GPU 上运行大约需要五小时,成本约为 50 美元。

多智能体系统很难让其正常工作。增加智能体会改变智能体的上下文、预算,进而改变整个系统的复杂性。通过通信混合智能体的上下文,并不一定比单个智能体带来性能提升。模型需要通过训练来学习如何沟通。我们如何定义模型应该学习什么?当我们处理多个智能体时,我们要更新哪些模型权重?

在本系列中,我们将通过教育性的概述和实用的例子来解决这些问题。每篇文章都会提出一个问题,构建一个小系统,并检查发生的情况以及如何复现它。这个第一个示例从四个智能体、一个共享的语言模型和一个简单的可验证任务开始。它非常适合你自己实现、 tinkering(折腾)和学习。

首先,我们从一些关于群体的背景知识开始。

群体的崛起

过去几个月里,我们听到了很多关于群体的讨论,有好有坏。今年九月,OpenAI 宣布,一个由大约 10,000 个智能体组成的群体发现了纳维-斯托克斯方程(Navier-Stokes equations)中的一个奇点,这是千禧年大奖难题之一。一个较小的、近 100 个智能体的群体已经证伪了无外力作用下的三维欧拉方程的正则性,这是一个密切相关的问题。

但群体并不总是能在我们想要的问题上起作用。METR 对 Hugging Face 事件的调查发现,大约 1,200 个本应隔离的 OpenAI 智能体找到了一种交换超过 70,000 条消息和文件的方法。大约 700 个智能体在寻找欺骗其基准测试评分器的方法时,加入了针对 Hugging Face 的攻击,尽管它们并没有被指示这样做。

庞大的群体本身并不能证明合作带来了帮助。Noam Brown 估计,纳维-斯托克斯结果中不到 10% 来自多智能体合作。在 Anthropic 的漏洞查找实验中,协调的智能体发现的漏洞比独立智能体多,但也搜索了更多的代码并使用了更多的 token。当比较限制在相同的目录时,每百万 token 的结果大致相同。

合作有帮助吗,还是我们只是花了更多钱?

从最简单的情况开始。如果四个智能体各自独立尝试一个任务,只要我们能判断哪个答案是正确的,那么至少有一个成功的概率就高于单次尝试。这使得多智能体系统有了一个有用的基线,但这并不能显示智能体之间互相帮助了。它们可能只是有了更多的尝试机会。

四次尝试的成本也是四倍。因此,更公平的比较是在同等预算下:如果每个智能体只获得总 token 的四分之一,它们是否还能击败花费所有 token 的一个智能体?只有通过测试才能找出答案,因为答案取决于任务、模型和工作分配方式。

本系列不断追问一个问题:当智能体进行沟通时,这真的有帮助吗,还是我们只是在消耗更多的计算资源?

我们通过这个简单的期望来理解这个问题。

在匹配的智能体和 token 数量下,预期性能随智能体数量变化的草图:沟通中的智能体位于非沟通智能体之上

图 1. 我们要测试的预期草图:在匹配的预算下比较沟通和独立的智能体。

我们将把智能体数量视为一个扩展维度,与 token 数量和模型大小并列。有时增加智能体会带来帮助。有时协调会消耗我们希望节省的预算。关键在于衡量两者。我们不会从 10,000 个智能体开始。我们会从一个小型团队在一个我们可以轻松检查的任务上开始。

多智能体系统与强化学习

在多语言模型被称为“群体”之前很久,多智能体强化学习就已经研究了合作与竞争。

单个智能体的任务是一个马尔可夫决策过程:观察、行动、获得奖励。在一个团队中,每个人都共享奖励,但每个智能体只能看到世界的一部分。这是一个去中心化的部分可观察马尔可夫决策过程:队友,但没有人能看到全貌。

这造成了三个实际问题。首先,队友在不断变化,而每个智能体都在学习。其次,信用分配:当团队成功时,哪些行动值得归功于谁?一个获胜的团队可能包含弱小的行动,而我们可能会最终奖励它们。第三,一条消息会改变其他智能体的观察内容,因此沟通是我们正在训练的策略的一部分。

一个常见的解决方案是集中式训练与去中心化执行:训练使用来自整个团队的信息,但每个智能体仅根据其自身的观察采取行动。我们的第一个示例遵循这种模式,使用共享的团队奖励。

智能体也可以以不同的方式组织。两个有用的起点是:

  • 层级结构。 一个主管智能体将工作分配给工人并收集他们的结果。Anthropic 的研究系统就是这样工作的,每个工人都有单独的上下文。Kimi K2.5 的 PARL 只训练编排者并保持子智能体冻结,因此训练多智能体系统并不意味着更新每个组件。参见 Anthropic 的系统描述 和 Kimi 的技术博客。

  • 分布式团队。 同伴互相发送消息并决定何时查看收件箱。没有主管智能体分配行动。这是我们在这里使用的设置,遵循 s³: Simple Scaling of Swarms via Cooperative Multi-agent RL 中的信息聚合任务。

我们的第一个实验:四个智能体排序数字

我们将复现 Simple Scaling of Swarms 中的信息共享任务,因为它具有可解释性且易于实现。四个智能体共享一个小语言模型,并学习整合它们各自的知识。

每个智能体接收一个从 1 到 99 的整数。它知道自己的分配及其队友的名字。它最初不知道其他智能体的数字。例如,四个私有分配可能是“五”、“二十六”、“五”和“七十八”。重复的数字保留在列表中,所以正确的最终答案是:

#### [5, 5, 26, 78]

当至少有一个智能体提交完整且正确排序的列表时,团队就成功了。一个正确的答案就足够了;成功不需要所有四个智能体都回答正确。如果没有来自队友的信息,智能体无法可靠地推断出其他私有分配。

这意味着该任务尚未直接测试图 1。每个智能体持有其他人需要的信息,因此无论重试多少次,单个智能体或没有消息传递的团队都无法成功。相反,该任务测试的是图 1 背后的前提条件:一个小共享策略能否学会沟通,以及这需要多少 token?稍后的文章将转向一个单个智能体可以单独解决的任务,其中匹配预算的比较是有意义的。

主要的通信工具是 message(to, text)、read_messages() 和 check_notifications()。通知告诉智能体存在未读消息;读取其收件箱使其内容可用。智能体可以发送直接消息或向所有人广播。

我们使用一个共享的 Qwen3-0.6B 策略定义了一个四智能体系统,具有单独的上下文和私有输入。我们不是在训练四个不同的模型。提示解释了任务和工具,包括分享分配的必要性。

四个智能体共享一个具有单独上下文和私有数字的策略,交换消息,提交排序列表,并从共同的团队奖励中进行训练

图 2. 任务和训练循环。私有数字说明了一个可能的成功片段;此图形不是记录的对话,也不是关于在第 75 次更新时学到的协议的声明。

团队奖励和每个问题的八次尝试

在本文中,_团队_意味着一个片段:四个智能体尝试一个问题一次。成功的团队获得的奖励会根据其使用的 token 进行减少。失败的团队获得零奖励:

team allowance = 4 × (8,192 work tokens + 1,024 final-answer tokens)
               = 36,864 tokens

reward = success × (1 − 0.25 × min(1, generated team tokens / 36,864))

为了说明,一个正确使用了一半配额的团队将获得 0.875。发送消息没有单独的奖励。激励措施是在使用更少生成 token 的同时完成任务。

对于每个训练问题,我们收集八个独立的团队尝试。它们的奖励在该组内进行归一化。表现优于其组平均水平的尝试获得正优势;表现较差的尝试获得负优势。同一团队中的每个智能体都会获得该团队的优势,即使其自己的最终答案是错误的。

在 TRL 中,每个智能体采样的 token 形成一个训练行。其传入的消息和工具结果提供上下文。损失在每个团队内平均,然后在团队间平均,因此较长的对话不会给团队更多的权重。

我们的结果 来自原始实验,该实验每次更新使用 256 个团队尝试(32 个问题,每个问题八次尝试)。演练 使用 TRL 默认的 --teams-per-update 128,相当于每次更新约 150 个团队尝试。

我们的结果

经过 75 步,训练成功率从 6.6% 上升到 82.3%,比较前五次和后五次更新。在第 75 次检查点,四智能体团队解决了 32 个保留问题中的 26 个(81.25%)。论文 报告称,经过 200 次更新后,四智能体成功率为 93.2%。

团队还减少了 每次尝试 37.4% 的 token 使用量,从大约 13k 下降到 8k。这一改进伴随着更活跃的信息共享:广播从每个团队 2.38 次增加到 5.73 次,尽管总 token 使用量下降。

图 3. 蓝色曲线描述了在每次更新之前收集的 256 个团队尝试的训练批次。橙色点是所示更新后的保留检查。

团队在训练后期也使用了更少的 token。比较前五次更新与第 71–75 次更新:

训练指标

更新 1–5,平均值

更新 71–75,平均值

成功率

6.56%

82.34%

每个团队的生成 token

12,826.9

8,026.0

每个团队的 message 数

3.48

6.28

每个团队的广播数

2.38

5.73

每个智能体有一次广播的团队

4.06%

18.20%

在这些窗口之间,每个训练团队的生成 token 减少了 37.4%。在第 75 批本身,平均每个团队为 7,624 个 token。这些是训练测量值;

查看原文

Part 1: Understanding swarms and training to communicate

This is an aspirational blog series for aspirational readers. We (us, the community, you) want to build our own agent swarms because they're exciting, challenging, and increasingly capable. Furthermore, it would be extremely cool if we could train our own agents to work in a swarm. And exponentially cool if those swarms used small and affordable models.

That's what we'll do in this series! Each blog post will include some context on building swarms, alongside reproducible examples that you can run on Hugging Face Jobs. This post's example takes about five hours on two H200s, which costs roughly $50.

Multi-Agent Systems are hard to get working. Adding agents changes the agent's context, the budget, and in turn the complexity of the whole system. Mixing agents' context together through communication is not an inherent performance boost compared to a single agent. The model needs to learn to communicate through training. How do we define what models should learn? And which model weights do we update when we're dealing with many agents?

In this series, we'll work through those problems with an educational overview and practical examples. Each post will introduce a question, build a small system, and examine what happens and how you can reproduce it. This first example starts with four agents, a shared language model, and a simple verifiable task. It's ideal to implement yourself, to tinker with, and to learn from.

First, we'll start off with some context on swarms.

The rise of the swarms

We've heard a lot about swarms over the past few months, both good and bad. In September this year, OpenAI announced that a swarm of roughly 10,000 agents had found a singularity in the 3D Navier-Stokes equations, one of the Millennium Prize problems. A smaller group of nearly 100 agents had already disproved regularity for the unforced 3D Euler equations, a closely related open problem.

But swarms don't always work on the problems we want them to. METR's investigation of the Hugging Face incident found that around 1,200 OpenAI agents, which were supposed to be isolated, had found a way to exchange over 70,000 messages and files. Around 700 joined an attack on Hugging Face while looking for ways to fool their benchmark's scorer, without instruction to do so.

A big swarm isn't, by itself, evidence that cooperation helped. Noam Brown estimates that less than 10% of the Navier-Stokes result came from multi-agent cooperation. In Anthropic's vulnerability-finding experiment, coordinated agents found more bugs than independent agents, but also searched more code and used more tokens. When the comparison was restricted to the same directories, the results per million tokens were about the same.

Did cooperation help, or did we just spend more?

Start with the simplest case. If four agents each try a task independently, the chance that at least one gets it right is higher than with a single attempt, as long as we can tell which answer is correct. That makes a useful baseline for a multi-agent system, but it doesn't show that the agents helped each other. They may simply have had more tries.

Four attempts also cost four times as much. So the fairer comparison is at an equal budget: if each of four agents gets a quarter of the total tokens, can they still beat one agent that spends all of them? We can only find out by testing, because the answer depends on the task, the model and how the work is divided.

This series keeps asking one question: when agents communicate, does it actually help, or are we just spending more compute?

We understand that question through this simple expectation.

Sketch of expected performance against agent count at matched agents and tokens: communicating agents sit above non-communicating agents

Figure 1. Sketch of the expectation we want to test: compare communicating and independent agents at matched budgets.

We'll treat agent count as a scaling dimension, alongside tokens and model size. Sometimes adding agents will help. Sometimes coordination will consume the budget we hoped to save. The point is to measure both. We won't start with 10,000 agents. We'll start with a small team on a task that we can check easily.

Multi-agent Systems and Reinforcement Learning

Multi-agent reinforcement learning has studied cooperation and competition long before language models were called swarms.

A single agent's task is a Markov decision process: observe, act, get a reward. In a team, everyone shares the reward, but each agent sees only part of the world. This is a decentralized partially observable Markov decision process: teammates, but no one sees the whole picture.

This creates three practical problems. First, teammates keep changing while each agent learns. Second, credit assignment: when the team succeeds, which actions deserve the credit? A winning team can include weak actions, and we may end up rewarding them. Third, a message changes what other agents observe, so communication is part of the policy we're training.

A common solution is centralized training with decentralized execution: training uses information from the whole team, but each agent acts only on its own observations. Our first example follows this pattern with a shared team reward.

Agents can also be organized in different ways. Two useful starting points are:

  • A hierarchy. A lead agent assigns work to workers and collects their results. Anthropic's Research system works this way, with a separate context for each worker. Kimi K2.5's PARL trains only the orchestrator and keeps the subagents frozen, so training a multi-agent system doesn't mean updating every component. See Anthropic's system description and Kimi's technical blog.

  • A distributed team. Peers send each other messages and decide when to read their inboxes. No lead agent assigns the actions. This is the setup we'll use here, following the information-aggregation task in s³: Simple Scaling of Swarms via Cooperative Multi-agent RL.

Our first experiment: four agents ordering numbers

We'll reproduce the information-sharing task from Simple Scaling of Swarms because it's interpretable and straightforward to implement. Four agents share a small language model and learn to pool what each of them knows.

Each agent receives one integer from 1 to 99. It knows its own assignment and its teammates' names. It does not initially know the other agents' numbers. For example, four private assignments might be "five", "twenty-six", "five" and "seventy-eight". Duplicates stay in the list, so a correct final answer is:

#### [5, 5, 26, 78]

The team succeeds when at least one agent submits the complete, correctly sorted list. One correct answer is enough; success does not require all four agents to answer correctly. An agent cannot reliably infer the other private assignments without information from its teammates.

This means the task does not yet test Figure 1 directly. Each agent holds information the others need, so a single agent, or a team without messaging, cannot succeed however many retries it gets. Instead, the task tests the precondition behind Figure 1: can a small shared policy learn to communicate at all, and how many tokens does that cost? A later post moves to a task that a single agent can solve alone, where the matched-budget comparison is meaningful.

The main communication tools are message(to, text), read_messages(), and check_notifications(). A notification tells an agent that unread messages exist; reading its inbox makes their contents available. Agents can send direct messages or broadcast to everyone.

We defined a four-agent system using one shared Qwen3-0.6B policy, with separate contexts and private inputs. We are not training four different models. The prompt explains the task and the tools, including the need to share assignments.

Four agents share one policy with separate contexts and private numbers, exchange messages, submit a sorted list, and train from a common team reward

Figure 2. The task and training loop. The private numbers illustrate a possible successful episode; this graphic is not a recorded conversation or a claim about the learned protocol at update 75.

A team reward and eight attempts at each problem

In this post, a team means one episode: four agents attempting one problem once. A successful team receives a reward reduced by the tokens it uses. A failed team receives zero:

team allowance = 4 × (8,192 work tokens + 1,024 final-answer tokens)
               = 36,864 tokens

reward = success × (1 − 0.25 × min(1, generated team tokens / 36,864))

For illustration, a correct team using half its allowance receives 0.875. There is no separate reward for sending messages. The incentive is to solve the task while using fewer generated tokens.

For every training problem, we collect eight independent team attempts. Their rewards are normalized within that group. An attempt that does better than its group average gets a positive advantage; one that does worse gets a negative advantage. Every agent in the same team receives that team's advantage, including an agent whose own final answer was wrong.

In TRL, each agent's sampled tokens form a training row. Its incoming messages and tool results provide context. The loss is averaged within each team and then across teams, so longer conversations do not give a team more weight.

Our results come from the original experiment, which used 256 team attempts per update (32 problems with eight attempts each). The walkthrough uses TRL's default of --teams-per-update 128, which works out to about 150 team attempts per update.

Our Results

Over 75 steps, training success rose from 6.6% to 82.3%, comparing the first and last five updates. At checkpoint 75, the four-agent team solved 26 of 32 held-out problems (81.25%). The paper reports 93.2% four-agent success after 200 updates.

The team also used 37.4% fewer tokens per attempt, falling from about 13k to 8k. This improvement accompanied more active information sharing: broadcasts increased from 2.38 to 5.73 per team, even as total token use fell.

Figure 3. The blue curve describes training batches of 256 team attempts, collected before each update. Orange points are held-out checks after the indicated update.

The team also used fewer tokens later in training. Comparing the first five updates with updates 71–75:

Training metric

Updates 1–5, mean

Updates 71–75, mean

Success

6.56%

82.34%

Generated tokens per team

12,826.9

8,026.0

Messages per team

3.48

6.28

Broadcasts per team

2.38

5.73

Teams with one broadcast per agent

4.06%

18.20%

That is a 37.4% reduction in generated tokens per training team between those windows. At batch 75 itself, the mean was 7,624 tokens per team. These are training measurements; we did not retain held-out token-efficiency measurements for the trained checkpoint.

Notice that fewer tokens did not mean fewer messages. More agents began participating but broadcasting became more common, rather than direct messaging. Generated tokens include reasoning and tool calls as well as message bodies, so message count alone does not tell us how much text the team produced.

Figure 4. Top: training token use and a trailing five-update mean. Bottom: mutually exclusive communication classes, based on sent-message events. A team is classified first by whether some agent never sends, then whether any direct message occurs, then whether every agent sends exactly one broadcast; the remaining teams repeat broadcasts.

More retries or a trained team?

No agent can solve the problem alone, so the closest equivalent of "a single agent with more retries" is the untrained team with more retries. The training data already contains this comparison. Each update collects eight attempts per problem, and the task's answers are easy to check, so we can count a problem as solved when any of its eight attempts succeeded. Early in training, that count gives the untrained team's best-of-8 success rate:

Success

Generated tokens per problem

Untrained team, best of 8 attempts (updates 1–5)

37.5%

about 103,000

Trained team, one attempt (updates 71–75)

82.3%

about 8,000

With eight retries, the untrained team solves fewer than half the problems and spends about 13 times as many tokens as one attempt from the trained team. Read this as an estimate. Both rows use training problems rather than held-out ones, and updates 2–5 already sample from a slightly trained policy.

Infrastructure

The model is small, but the rollouts are not. Each update generates millions of tokens of agent conversation at contexts of up to 40k tokens. We used one H200 for the trainer and seven H200s running vLLM rollout engines to get through those rollouts quickly, and kept each worker's eight attempts together. The walkthrough below runs the same task on two GPUs. Here are the infra details:

Setting

Recorded experiment

Shared policy

Qwen3-0.6B

Logical agents per team

4

Problems per update

32

Team attempts per problem

8

Work / final tokens per agent

8,192 / 1,024

Learning rate / temperature

5e-7 / 1.0

Training problem pool

1,024 generated problems

Reporting endpoint

Preserved checkpoint 75

Execution

1 trainer GPU + 7 rollout GPUs

Practical example: Train your own swarm

The figures above describe our original 75-update experiment. In this walkthrough we'll run TRL's swarm example on Hugging Face Jobs. One H200 serves the shared Qwen3-0.6B policy with vLLM and a second H200 trains it.

1. Create a bucket for the run

Sign in with a Hugging Face account that can run Jobs and create buckets. Replace YOUR_USERNAME with your Hub username.

Use a fresh bucket for each run so earlier measurements stay available.

uv tool install 'huggingface_hub==2.4.0'
hf auth login
BUCKET="YOUR_USERNAME/swarm-trl-$(date -u +%Y%m%d-%H%M%S)"
hf buckets create "$BUCKET"

2. Run the TRL example on Hugging Face Jobs

Save the script below as train-swarm.sh in your current directory.

train-swarm.sh

set -eu
git clone --depth 1 https://github.com/huggingface/trl /tmp/trl
cd /tmp/trl
example=examples/async_grpo_s3_aggregation
if [ ! -f "$example/async_grpo_s3_aggregation.py" ]; then
  git fetch --depth 1 origin refs/pull/8424/head
  git checkout --detach FETCH_HEAD
fi
git rev-parse HEAD > /results/trl-revision.txt
python -m pip install -e ".[vllm,kernels]" "vllm==0.32.0" datasets httpx trackio

base=Qwen/Qwen3-0.6B
url=http://127.0.0.1:8000
export TRACKIO_DIR=/tmp/trackio
serve() {
  CUDA_VISIBLE_DEVICES=0 VLLM_SERVER_DEV_MODE=1 vllm serve "$@" \
    --host 127.0.0.1 --max-model-len 40960 --max-num-seqs 512 --enable-prefix-caching &
  server=$!
  until curl -fs "$url/health" >/dev/null; do kill -0 "$server"; sleep 5; done
}
evaluate() {
  python "$example/evaluate.py" --url "$url" --model "$1" --name "$2" \
    --episodes 192 --concurrency 64 --out "/results/$2.jsonl"
}

serve "$base" --logprobs-mode processed_logprobs --weight-transfer-config "{\"backend\":\"nccl\"}"
evaluate "$base" base
CUDA_VISIBLE_DEVICES=1 accelerate launch --num_processes 1 --mixed_precision bf16 \
  "$example/async_grpo_s3_aggregation.py" --vllm-url "$url" \
  --updates 50 --teams-per-update 128 --concurrent-teams 128 \
  --report-to trackio --output-dir /tmp/swarm
cp -r "$TRACKIO_DIR" /tmp/swarm/checkpoint-50 /results/
kill "$server"
wait "$server" || true
serve /tmp/swarm/checkpoint-50 --logprobs-mode processed_logprobs
evaluate /tmp/swarm/checkpoint-50 trained

The command below sends its contents to the job. Inside the job, vLLM serves the shared policy on GPU 0. GPU 1 runs TRL's async_grpo_s3_aggregation.py for 50 updates with Trackio. TRL's evaluate.py scores the base model and checkpoint 50 on the same 192 held-out problems. That is a larger set than the 32-problem checks in our results, which gives tighter error bars. The job saves both scores, the checkpoint, Trackio data and the exact Git commit to your bucket.

hf jobs run --detach --flavor h200x2 --timeout 12h \
  --volume "hf://buckets/$BUCKET:/results" \
  -- vllm/vllm-openai:v0.32.0 bash -c "$(cat train-swarm.sh)"

One TRL rollout contains a whole team conversation. The trainer compares eight attempts at the same problem and gives all four agents in an attempt the same advantage. Each update uses about 150 team attempts. TRL packs micro-batches by token count rather than by team, so the --teams-per-update 128 setting is approximate. The --report-to trackio flag records training metrics at every update.

This shorter run is cheaper than our original experiment, and it stops earlier on the learning curve. TRL's run of this example took about 4.8 hours on two H100s and reached 60.9% held-out success at checkpoint 50.

To run closer to our original experiment, change the training flags to --updates 75 --teams-per-update 256 --concurrent-teams 256, replace checkpoint-50 with checkpoint-75 in the script, and raise the job's --timeout to 24h. That is three times as many rollouts. The two codebases still differ in details such as the system prompt, so expect similar results rather than an exact replication.

3. Read the results

Once the job completes, sync the bucket to a local folder. It holds the two evaluation files, the Trackio data, the TRL revision and the checkpoint-50 weights, which are the largest download. In the dashboard, compare team/success, team/messages and team/tokens over training. The job logs also give the held-out success rate for the base model and checkpoint 50. Each line of base.jsonl or trained.jsonl records one of those evaluation attempts.

hf buckets sync "hf://buckets/$BUCKET" ./swarm-results
TRACKIO_DIR="$PWD/swarm-results/trackio" uvx trackio show

What we'll try next

This first example gives us a small environment, a shared reward and a policy that improves at pooling private information. It also shows why success, token use and communication structure need to be read together. At 75 updates, the team is solving most checked problems, but it has not converged to the cleanest communication pattern.

In the coming examples, we'll take a step back from training and look at how we evaluate and analyze swarms.

For now, we have something concrete to build on: four small agents, one trainable policy, a checkable task, and a reproducible way to examine what the team learned.

原文版权归 Hugging Face Blog 及原作者所有,本站转载仅供阅读。如需删除,请联系 support@aisa.one。