
循环 Transformer:用同一份权重多想一遍
Inkling 2 Mini 与 GLM-5.4 让部分层每 token 重复运行多遍。从零训练的百万参数小模型验证:循环换来推理步数而非知识;门控维持稳定,等算力下没有免费午餐。
上周,Thinking Machines 与 Z.ai 各自发布的新语言模型做了一件初听像是 bug 的事:对每一个处理的 token,它们把网络的一部分连续运行好几遍,而且用的是完全相同的权重。
Thinking Machines 的 Inkling 2 Mini 把中间 12 层运行 3 遍,Z.ai 的 GLM-5.4 把其中 28 层运行 2 遍。重复使用同一批层并不会改变模型的参数量,那么为什么把同样的层再跑一遍会让模型更聪明?第二遍算出了第一遍算不出的什么东西?代价又是什么?
本文做两件事。第一,用两家实验室已公开的信息解释这些循环 Transformer(looped transformers)如何工作。第二,从零训练几个极小的循环 Transformer——每个约一百万参数、在普通 GPU 上训几分钟——亲眼看看循环到底带来了什么。
Inkling 2 Mini 与 GLM-5.4
深度与规模是两回事
从普通 Transformer 说起。处理过程中,每个 token 用一个向量表示,常称为残差流(residual stream)。一层读取这个向量(并通过注意力读取其他 token 的向量),计算一个更新量,加回残差流。下一层读取结果、加上自己的更新,依此类推。40 层的模型就是依次施加 40 次这样的更新。(若把注意力块与 MLP 块分开计数,则是对残差流的 80 次更新。)
这里藏着两个量,而在普通 Transformer 中它们被绑在一起:
- 规模(size):模型存储多少参数;
- 深度(depth):每个 token 经历多少步串行计算。
对常规 Transformer,每加一层就同时加一步计算和一组权重。想要更深的模型?就必须存储更大的模型。
循环 Transformer 把这两个概念解绑:取一个层块,重复应用多次,把输出馈回输入。一个 12 层的块跑 3 遍,就用 12 层权重的代价换来 36 步计算。
实践中,你不会想循环整个网络。常见布局分三段:
- 前奏(prelude):只跑一次的几层,把 token 嵌入变成模型的内部表示;
- 核心(core):真正被重复的层块;
- 尾声(coda):最后只跑一次的几层,把内部表示变回对下一个 token 的预测。
这一布局背后的直觉(Thinking Machines 在发布中说明)是:首尾两层做 token 与内部概念之间的翻译工作,中间层做更抽象的处理。翻译只需一次;抽象处理也许受益于更多轮次。
复用权重并不新鲜,为何突然集中发布?一种可能的解读是两股力量在推。其一,实验室想要更会推理的模型,而推理似乎更需要串行步数而非存储。思维链是扩展测试时计算的一条路,循环是另一条——下文实验会展示。其二,模型越来越多地跑在内存稀缺、算力相对便宜的地方:笔记本、单卡 GPU、手机。每个存储的参数都吃内存,而对已经躺在内存里的权重多跑一遍代价相对小。(话说回来,GLM-5.4 并不打算让你本地跑!)
边注:权重复用简史。Universal Transformer(Dehghani 等,2018)早已反复应用同一层,并带一个决定何时停止的机制。ALBERT(Lan 等,2019)在所有层间共享权重,主要为了让 BERT 变小。随后的理论工作证明循环 Transformer 原则上可以模拟一台可编程计算机(Giannou 等,2023),以及少数层循环多次能在推理任务上匹敌深得多的模型(Saunshi 等,2025)。2025 年,Huginn(Geiping 等,2025)在一个 3.5B 参数、循环次数可在测试时选择的模型中引入了 prelude/core/coda 词汇;字节跳动的 Ouro 系列(Zhu 等,2025)则把循环预训练推到数万亿 token。
Inkling 2 Mini:为循环而设计
Inkling 2 Mini 有 24 层,分成 4 个 6 层块。第一块(前奏)跑一次,中间两块(核心,12 层)跑 3 次,最后一块(尾声)跑一次。于是每 token 48 次层应用,只来自 24 层权重。
它还是 MoE 模型:总参数 26.4B,每层中每个 token 路由到 128 个专家中的 8 个。一遍激活 3.4B 参数,核心每多跑一遍约增加 1B。因此 3 遍时模型干的是 5.4B 激活模型的活,却只存 26B 模型的权重。checkpoint 约 20 GB——小到能放进 32 GB 内存的笔记本。
循环的三个细节值得注意:
- 每一遍都从前奏的输出重新开始。第 2、3 遍还会收到上一遍的"消息",经一个学习到的门控合并进来。
- 那个门初始完全关闭。训练初期每一遍的行为与非循环模型完全一致,门在训练过程中逐渐打开。Thinking Machines 称这让他们能在训练中途引入循环而不破坏模型稳定。
- 48 次层应用各自保留自己的 key-value 缓存,所以注意力的内存开销仍随遍数增长。
发布还附带了一些有用的测量:循环中间 12 层在 28 项评测中的 27 项上胜过循环最后 12 层。与同系列非循环模型相比,非循环模型训练算力少 7.5%,但要达到循环模型的 loss 需要多 140% 的推理算力(在长 agent 轨迹上测得)。
最后,Thinking Machines 发布了研究版姊妹模型 TML-d24-varloop-research,用 1 到 5 遍训练,因此加载时可以自选遍数。其模型卡报告了分数随遍数的变化;文末会回到这些数字,并在小模型上看到同样的现象。
GLM-5.4:把大模型改造成循环模型
GLM-5.4 是另一种生物。它是约 750B 参数的模型,Z.ai 并没有从零把它训成循环模型,而是拿已预训练好的 GLM-5 基座,通过继续训练改造成把其中 28 层跑 2 遍的模型。他们的理由是:"在相同预训练算力预算下,从零训练的循环模型仍落后于不共享权重的模型。"
改造一个本不为循环设计的模型会带来实际问题。Z.ai 写道,若第二遍直接覆盖隐藏状态,"激活范数会在迭代间爆炸",下游层会收到从未见过的尺度与分布的向量。他们的解法是每 token、每遍一个门,决定每遍更新写回多少比例。训练后第一遍写得谨慎(门值小),第二遍把门开大;更难的 token 获得更大的第一遍更新。
另外两处改动压低成本:第二遍复用第一遍选出的注意力缓存,自己只保留一个短滑动窗口,因此"多一次循环只花一个滑动窗口的 KV 缓存,而非整段上下文缓存";并且复用第一遍的稀疏注意力索引,不再重算。
Z.ai 的证据来自 30B 模型上的对照实验:参数量相同时,循环版多花约 10% 训练算力,结果更好,收益主要在数学、科学推理与长上下文任务。
两个模型的快速对比:
| Inkling 2 Mini | GLM-5.4 | |
|---|---|---|
| 总规模 | 26.4B(MoE) | 约 750B |
| 循环部分 | 24 层中的中间 12 层 | GLM-5 基座的 28 层 |
| 遍数 | 3(研究版 1 到 5) | 2 |
| 遍间连接 | 从前奏输出重启 + 上一遍的门控"消息" | 对更新施加每 token、每遍的门 |
| 训练方式 | 训练中途引入循环 | 由训好的非循环模型改造 |
| 注意力缓存 | 每次层应用各一份 | 第二遍复用第一遍缓存 + 滑动窗口 |
用小实验理解循环 Transformer
给微型 Transformer 的寻宝游戏
要突出并量化循环架构的好处,实验室们比得起数十亿参数的循环与非循环模型。我比不起。但上面的论断关乎原理——深度对存储、推理对知识——而原理只要选一个简单得多的任务,就能在小尺度上检验。
我选的任务是这样:想象一场寻宝,每条线索告诉你下一条线索藏在哪,目标是顺着走到最后一条。相当于沿有向图的边一直走,直到走不动为止。
具体地:64 个符号(称为节点)。输入是一组箭头 a → b,把节点连成若干条互不相交的链,再加一个查询节点;答案是查询所在链的最后一个节点。从查询到链尾的跳数就是难度旋钮。例如:
arrows: 17→42 5→9 42→3 9→61 3→28 61→12 6→8
23→31 43→41 58→1 45→48 11→19 48→51 46→35
40→22 60→16 57→32 54→11 20→4 14→38 26→34
53→54 2→46 35→59 24→44 56→10 49→27 55→57
39→63 0→37 37→40 50→7 29→49 38→33 18→15
41→20 15→2 63→36 59→55 44→58 8→14 25→21
31→43 47→29 34→0 12→30 1→6 32→13 19→45
query: 17
这里要跟随的链是 17 → 42 → 3 → 28;接着 28 没有出箭头,所以要预测的 token 是 28——共 3 跳。
我喜欢这个任务的地方在于:答对所需跳数是一个旋钮,我可以精确设定一个问题需要几步推理。而且无需记忆任何东西——模型需要的一切都在输入里。某种意义上它是语言模型常做之事的极简版:在代码里追踪一个变量,或链式查询"Alice 的经理的经理"。它也接近 Inkling 可变循环模型随遍数提升显著的基准 GraphWalks:在上下文给出的图上行走。
下文所有模型共用同一配方:128 维向量、4 个注意力头、1 层前奏、1 层尾声,中间的核心或循环或不循环。参数量 0.6 到 2 百万,每个在单张 A10G GPU 上训 3 到 30 分钟(跑在 Hugging Face Jobs 上)。训练时最大链长逐步增长——一个课程(curriculum)——因为首轮试点发现:直接在长链上训练的模型什么都学不会。
跟链:存储的层数,还是应用的层数?
第一个问题:模型跟链时,要紧的是它存储多少层,还是应用多少层?
我在最长 48 跳的链上训了两族模型。循环族的核心是单层,重复 1 到 4 次;加深族的核心含 1 到 4 个不同层,各跑一次。算上前奏与尾声,两族每 token 都应用 3 到 6 层(记作 $L$)。差别在存储:循环族始终 0.63 百万参数,加深族从 0.63 长到 1.22 百万。
看结果前先做预测。朴素策略是每层跟一条箭头,6 层走 6 跳。但注意力允许好得多的做法——并行计算里的经典技巧指针跳跃(pointer jumping)。设每条箭头 a → b 同时发问:"b 指向哪?"一轮之后,每个节点知道两步之后的节点。下一轮,每个节点向那个两步之后的节点问同样的问题,于是知道四步之后的节点。然后八、十六……每轮跳跃翻倍。注意力天然适合此事:每个 token 在一层内就能查任意其他 token。原则上 $L$ 层能跟的链长约为
$$\mathrm{reach} \approx 2^{L} - 1 \quad\text{跳:}\quad 3 \text{ 层 } 7,\ 4 \text{ 层 } 15,\ 5 \text{ 层 } 31,\ 6 \text{ 层 } 63.$$
3 层模型恰好跟到 7 跳然后崩溃——与预测一致。4 层时加深模型到 14–15 跳(两次训练运行),循环模型 10–11。5 层时两者都达不到理论的 31:循环 16–19 跳,加深 15。6 层时两者解出直到 48 跳的所有链。
可能令人意外的是:更长的链上性能似乎回升。怎么回事?这来自一种排除伪影(elimination artefact):链越长,剩下的其他链越少,模型更容易猜中答案。这不算原始能力的真实提升。
这张汇总图讲清了故事。左图两族彼此跟随——循环族在 5 层领先、4 层落后。右图把同样的结果对存储参数数作图:循环模型从 7 跳走到 48 跳,一个参数都没多。跟链这件事,要紧的是应用了多少层,而不是存储了多少层。这正是循环模型押的注。
记忆事实:参数说了算
现在问相反的问题。大语言模型知道的大多数东西不在输入里:秘鲁的首都、某篇论文的年份。这些必须存在权重里。循环对此有帮助吗?大概没有。
为检验这一点,取三个两层核心的模型:
- shallow:核心跑 1 次(应用 4 层,0.83M 参数);
- looped:核心跑 4 次(应用 10 层,0.83M 参数);
- deep:8 个不同核心层(应用 10 层,2.0M 参数)。
每个模型都被训练去记忆一张一百万条随机事实的表。一条事实把"主语"(4 个符号)连到"答案"(64 个符号之一)。事实是随机的,所以无可推理、无可泛化:一条事实要么存在权重里,要么不在。一百万条超过任何这些模型的容量,所以问题是各自能留住多少。
subject answer
47 44 54 1 → 34
47 44 54 21 → 19
19 13 46 25 → 37
19 13 46 48 → 33
19 13 46 16 → 38
38 25 40 16 → 50
... (1,000,000 rows in total)
把每行想成"秘鲁的首都是利马"这样的事实,只是用一套词无含义、答案随机抽取的密码写成。共享 4 个符号中 3 个的主语彼此答案无关,因此无规律可利用:答对一行的唯一办法是记住它。
shallow 与 looped 存的事实数几乎相同:299,000 与 294,000。循环模型应用了两倍半的层数,却毫无差别。参数多 2.4 倍的 deep 模型存了 662,000 条。
把存储的信息量除以参数数(每个答案值 6 比特),三个模型都约每参数 2 比特:2.17、2.13、1.97。这接近 Allen-Zhu 与 Li 2024 年在语言模型上测得的数字(Physics of Language Models, Part 3.3):无论架构如何,约每参数 2 比特知识。循环不改变这个数。
在测试时选择遍数
此前每个循环模型都以固定遍数训练和测试。Inkling 的研究版做了更有意思的事:用随机遍数(1 到 5)训练,因此使用时可以自选跑几遍。我们也来这么做。
我训了一个两层核心的模型,每个训练步随机抽 1 到 6 遍。所有训练链最长 16 跳。然后在最长 48 跳的链上测试,遍数从 1 到 16 任选。
两件有意思的事。第一,每多一遍都扩展触及范围。1 遍时跟到 7 跳(准确率 ≥90%);2 遍 16;3 遍 24;6 遍 36;7 遍——比训练见过的多一遍——38 跳。记住训练链没有超过 16 跳的:从 3 遍起,模型就在解比训练所见更长的问题。
第二,这不只是算力问题。点线是架构完全相同、始终用 4 遍训练的模型。跑 4 遍时它与可变循环模型跑 4 遍消耗完全相同的算力,却在 18 跳崩溃,而可变循环模型到 29 跳。用随机遍数训练似乎迫使模型学会一种"重复执行仍然有效"的程序——而这种程序也能迁移到更长的链上。
但存在上限。超过六七遍后触及范围不再增长:第一次运行甚至下降(10 遍 31 跳、16 遍 25 跳);第二次运行则到 16 遍都平在约 30 跳。无论如何,把循环跑得比训练长得多买不到任何东西,甚至有害——原因马上出现。
观察循环内部
因为这个模型被训练成任意遍数后都能作答,我们可以做普通网络做不到的事:在第 1、2、3……遍后停下来,读模型每一阶段的答案。(Thinking Machines 的可变循环模型允许完全相同的操作。)
下图对 16、24、32 跳的链,展示每遍之后模型给查询链上各节点的概率。位置 0 是查询,最后一个位置是正确答案。
看模型还没完成时概率集中在哪。第 1 遍后,它指向链下 8 跳的节点;第 2 遍后指向 16 跳。24 跳的链在第 3 遍到终点;32 跳的链——训练所见的两倍长——第 3 遍部分到达、第 4 遍基本到达。在这次运行中,最初每一遍都把模型能看多远翻倍。
这又是指针跳跃,深度实验里的那个技巧,但现在我们能亲眼看着它发生。模型从未被告知这个算法。它自己找到了,并用核心的每一遍执行一次翻倍。
对第二次训练运行要诚实:那里图景更模糊。中间猜测也逐遍前移(约链下 13、15、21 跳),但没有干净的"先 8 后 16"模式。翻倍是训练能找到的解之一,不是唯一解。
链尾也是一个自然的停靠点:一旦模型指向它,就无处可去,答案保持不动。这就是额外遍数起初几乎无害的原因。
让循环保持稳定
现在看 Z.ai 为 GLM-5.4 描述的工程问题:循环很多遍时内部状态会怎样?我比较了三种遍间连接方式:
- 直接重复(plain repeat):第 $t$ 遍的输出就是第 $t+1$ 遍的输入,仅此而已。
- 重加前奏输出:每遍进入核心前,把前奏输出加回状态。此前所有图用的就是这个变体(Inkling 也每遍从前奏输出重启)。
- 门控更新:核心提议一个新状态,一个小的学习门——每 token 一个数——决定写回多少(0 = 保留旧状态,1 = 替换)。这是 GLM-5.4 门控的简化版;区别之一是 GLM-5.4 每遍有独立门参数,而我的门跨遍共享,以便模型跑任意遍数。
三者都以 1 到 6 随机遍数、相同方式训练。
中面板是查询 token 内部向量每遍后的大小(范数)。没有门时它稳定增长——找到答案后每遍约增 50——16 遍后达到初始大小的 17 到 27 倍。没有任何东西阻止它,因为每一遍都在上一遍之上叠加自己的贡献。这正是 Z.ai 描述的爆炸——"激活范数会在迭代间爆炸"——在一个不足百万参数的模型里复现。它是第一次运行中超过 7 遍后触及范围下降的一个合理原因:后面的层收到比训练所见大得多的向量。(也不总是致命:第二次运行范数同样从 39 涨到 710,触及范围却保持住了。)
有门时,两次运行的范数都保持平坦,触及范围从不退化:从 5 遍到 16 遍一直 26–28 跳(第二次运行 24–25)。代价是:门控模型的最佳触及更近(28 跳对 38 跳)。
再看右面板:查询 token 的门值逐遍变化,按链长分组。门在最初几遍大开,然后降到几乎为零——而且链越长关得越晚:4 跳链在第 3 遍降到 0.1 以下,8 跳链第 4 遍,16 跳及以上的链第 6 遍。没有人要求模型这么做。它自己学会:答案没找到就继续工作,找到了就停止写回。这是一种自适应计算(对更难的输入花更多步数)——恰是 Z.ai 在 GLM-5.4 公告末尾列出的开放问题。
第二次运行显示同样倾向但更粗糙:4 跳链第 2 遍关门,8 跳及以上所有链第 3 遍关门。此后不再自适应,那个模型从未超过 25 跳。关得太早的门会给模型能走多远封顶。
来自最初尝试的一句告诫。我先试了 Inkling 式初始全关的门(训练开始时上一遍的消息乘零)。2,000 个训练步后它只开到约 0.06,循环模型最终与同参数非循环模型无异:它基本忽略了自己的额外遍数。Inkling 的门有完整规模的训练去打开;而在我这样的小预算下,关着的门可能一直关着。
结论:小模型对大模型说了什么
把小尺度结果与两家实验室的报告并排,看看这些微型实验是否教给了我们有用的东西。
有一件事微型实验复现不了:两家都报告循环模型写更短的推理(GPQA 上 Inkling 可变循环模型从 1 遍 3,703 个推理 token 降到 3 遍 1,731;GLM-5.4 输出短 10% 到 14%)。玩具模型单 token 作答,根本没有书面推理。一个自然的扩展是让它们写出中间节点,数数各遍数下需要写多少。
(基准数字来自 TML-d24-varloop-research 模型卡;转载前请对照模型卡核实。)
请记住:这些模型约一百万参数、只见过一个合成任务;它们的注意力是对无序集合的双向注意力,而语言模型从左到右读文本。把这些结果当作机制的示例,而非对 26B 模型中所发生之事的测量。
现阶段仍有几个开放问题(我想对实验室们也是如此):
- 每个 token 需要几遍?两个发布都对每个 token 用固定遍数。Z.ai 明确把自适应计算列为未来工作。小模型里的门暗示模型能自己学会停……但能否在规模上存活是另一回事。
- 我们还能读懂模型在想什么吗?若部分推理从书面 token 移进循环,就更难监控。Thinking Machines 研究过这一点,在此规模上未发现监控性的有意义损失,但警告这可能不会持续——这对可解释性是一个关切。
- 为什么从零训练的循环模型落后?玩具实验中,等算力下循环在推理上无损、只损失存储。这是否是大模型的全部解释,未知。
- 收益随模型规模与遍数如何演化?Z.ai 也把这列为开放问题。
复现实验
一切都在一个脚本 loopexp.py 里,可在 Hugging Face Jobs 上零配置运行:
hf jobs uv run --flavor a10g-small loopexp.py law --train_hops 48 # depth sweep
hf jobs uv run --flavor a10g-small loopexp.py facts --K 1000000 --fact_steps 50000 # memorisation
hf jobs uv run --flavor a10g-small loopexp.py varloop --only inject # variable-loop model
hf jobs uv run --flavor a10g-small loopexp.py varloop --only gated,plain # the two other variants
本文各图背后的运行共约 3.5 GPU 小时(A10G)——按写作时 Hugging Face Jobs 价格约 3.50 美元。
loopexp.py —— 完整实验脚本(305 行,点击展开)
# /// script
# requires-python = ">=3.10"
# dependencies = ["torch>=2.3", "numpy"]
# ///
"""Small looped-transformer experiments for the blog post.
Task "chains": N nodes are split into disjoint chains. The input is the *unordered set*
of edges (a -> b), one token per edge, plus a query token holding one node. The answer is
the last node of the query's chain. The number of hops (distance from query to chain end)
is the difficulty knob. There are no positional embeddings, so edge order carries no
information.
Task "facts": a fixed table of K random facts. The subject is a triple of symbols, the
answer one of N symbols. Pure memorisation, used as a control.
Architecture (same layout as Inkling 2 Mini, in miniature):
prelude (1 block) -> core (n_core blocks, run `passes` times, shared weights)
-> coda (1 block) -> linear readout at the query token.
How the state is carried from one pass to the next (`carry`):
inject : x_t = h_{t-1} + e, h_0 = 0 (prelude output e re-added at every pass)
plain : x_t = h_{t-1}, h_0 = e (plain weight-tied deep network)
gated : c_t = core(h_{t-1} + e); h_t = h_{t-1} + g_t * (c_t - h_{t-1}),
g_t = sigmoid(w . [norm(c_t), norm(h_{t-1})] + b) is one scalar per token
(inspired by GLM-5.4's per-token gates; shared across passes here).
Usage: python loopexp.py SUITE [--steps S] with SUITE in sanity|depth|varloop|facts
Each run prints one line "RESULT_JSON {...}".
"""
import argparse, json, math, sys, time
import torch, torch.nn as nn, torch.nn.functional as F
DEV = "cuda" if torch.cuda.is_available() else "cpu"
def amp(): # bfloat16 mixed precision on GPU, no-op on CPU
return torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=(DEV == "cuda"))
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
N = 64 # number of node symbols
D, HEADS = 128, 4
P_BREAK = 0.2 # probability that a distractor chain ends at a given node
TRAIN_MAX_HOPS = 16
# ----------------------------------------------------------------------------- data
def chain_batch(B, max_hops=TRAIN_MAX_HOPS, fixed_hops=None):
"""Edges are perm[j] -> perm[j+1] unless broken. The target chain is perm[0..L-1]."""
perm = torch.argsort(torch.rand(B, N, device=DEV), dim=1)
if fixed_hops is None:
L = torch.randint(2, max_hops + 2, (B,), device=DEV) # nodes in target chain
d = 1 + (torch.rand(B, device=DEV) * (L - 1).float()).long() # hops, uniform in 1..L-1
else:
L = torch.full((B,), fixed_hops + 1, device=DEV)
d = torch.full((B,), fixed_hops, device=DEV)
j = torch.arange(N - 1, device=DEV)[None]
brk = torch.rand(B, N - 1, device=DEV) < P_BREAK
brk = torch.where(j < (L[:, None] - 1), torch.zeros_like(brk), brk) # target chain unbroken
brk = brk | (j == (L[:, None] - 1)) # ...and ends at L-1
src, dst, mask = perm[:, :-1], perm[:, 1:], ~brk
q = perm.gather(1, (L - 1 - d)[:, None]).squeeze(1)
ans = perm.gather(1, (L - 1)[:, None]).squeeze(1)
return dict(src=src, dst=dst, mask=mask, q=q), ans, d, perm, L
SLOTS = 4 # symbols per fact subject (N**4 = 16.7M possible subjects)
class FactTable:
def __init__(self, K, seed=1234):
assert K <= N ** SLOTS, "not enough distinct subjects"
g = torch.Generator().manual_seed(seed)
ids = torch.randperm(N ** SLOTS, generator=g)[:K]
self.subj = torch.stack([(ids // N ** i) % N for i in range(SLOTS)], 1).to(DEV)
self.ans = torch.randint(0, N, (K,), generator=g).to(DEV)
self.K = K
def batch(self, B):
i = torch.randint(0, self.K, (B,), device=DEV)
return dict(subj=self.subj[i]), self.ans[i]
# ----------------------------------------------------------------------------- model
class Block(nn.Module):
def __init__(self):
super().__init__()
self.n1, self.n2 = nn.LayerNorm(D), nn.LayerNorm(D)
self.qkv, self.proj = nn.Linear(D, 3 * D), nn.Linear(D, D)
self.mlp = nn.Sequential(nn.Linear(D, 4 * D), nn.GELU(), nn.Linear(4 * D, D))
def forward(self, x, am):
B, S, _ = x.shape
q, k, v = self.qkv(self.n1(x)).view(B, S, 3, HEADS, D // HEADS).permute(2, 0, 3, 1, 4)
a = F.scaled_dot_product_attention(q, k, v, attn_mask=am)
x = x + self.proj(a.transpose(1, 2).reshape(B, S, D))
return x + self.mlp(self.n2(x))
class LoopNet(nn.Module):
def __init__(self, n_core=2, passes=1, carry="inject"):
super().__init__()
self.passes, self.carry = passes, carry
self.e_src, self.e_dst, self.e_q = nn.Embedding(N, D), nn.Embedding(N, D), nn.Embedding(N, D)
self.e_subj = nn.Embedding(SLOTS * N, D) # used by the facts task only
self.prelude = Block()
self.core = nn.ModuleList([Block() for _ in range(n_core)])
self.coda = Block()
self.out_norm, self.head = nn.LayerNorm(D), nn.Linear(D, N)
if carry == "gated":
self.gn1, self.gn2 = nn.LayerNorm(D), nn.LayerNorm(D)
self.gate = nn.Linear(2 * D, 1)
def embed(self, inp):
if "subj" in inp:
s = inp["subj"]
x = self.e_subj(s + torch.arange(s.shape[1], device=s.device) * N)
x = torch.cat([x, self.e_q.weight[:1].expand(s.shape[0], 1, D)], 1)
return x, None
x = torch.cat([self.e_src(inp["src"]) + self.e_dst(inp["dst"]), self.e_q(inp["q"])[:, None]], 1)
m = torch.cat([inp["mask"], torch.ones_like(inp["mask"][:, :1])], 1)
return x, m[:, None, None, :]
def readout(self, h, am):
return self.head(self.out_norm(self.coda(h, am)[:, -1]))
def forward(self, inp, passes=None, trace=False):
passes = passes or self.passes
x, am = self.embed(inp)
e = self.prelude(x, am)
h = torch.zeros_like(e) if self.carry == "inject" else e
tr = dict(logits=[], norm=[], gate=[])
for t in range(passes):
x = h + e if self.carry in ("inject", "gated") else h
for blk in self.core:
x = blk(x, am)
if self.carry == "gated":
g = torch.sigmoid(self.gate(torch.cat([self.gn1(x), self.gn2(h)], -1)))
h = h + g * (x - h)
if trace: tr["gate"].append(g[:, -1, 0])
else:
h = x
if trace:
tr["norm"].append(h[:, -1].norm(dim=-1))
tr["logits"].append(self.readout(h, am))
return tr if trace else self.readout(h, am)
def nparams(m):
skip = {"e_subj.weight"}
return sum(p.numel() for n, p in m.named_parameters() if n not in skip)
# ----------------------------------------------------------------------------- train / eval
@torch.no_grad()
def eval_hops(model, passes=None, hops=range(1, 49), n=1024):
model.eval(); out = {}
for d in hops:
inp, ans, *_ = chain_batch(n, fixed_hops=d)
with amp(): pred = model(inp, passes=passes).argmax(-1)
out[d] = (pred == ans).float().mean().item()
model.train(); return out
def max_solved(acc, thr=0.9):
m = 0
for d in sorted(acc):
if acc[d] >= thr: m = d
else: break
return m
def train_chains(model, steps, varloop=None, B=512, lr=1e-3, seed=0, log_every=1000):
torch.manual_seed(seed)
opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01, betas=(0.9, 0.98))
curve, t0 = [], time.time()
for step in range(steps):
cur = lr * min(1, (step + 1) / 300) * 0.5 * (1 + math.cos(math.pi * step / steps))
for g in opt.param_groups: g["lr"] = cur
hmax = min(TRAIN_MAX_HOPS, 4 + int((TRAIN_MAX_HOPS - 4) * step / (0.4 * steps))) # curriculum
inp, ans, *_ = chain_batch(B, max_hops=hmax)
p = int(torch.randint(varloop[0], varloop[1] + 1, (1,))) if varloop else None
with amp(): loss = F.cross_entropy(model(inp, passes=p).float(), ans)
opt.zero_grad(set_to_none=True); loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
if (step + 1) % log_every == 0 or step == 0:
acc = eval_hops(model, hops=[2, 4, 8, 12, 16], n=256)
curve.append(dict(step=step + 1, loss=round(loss.item(), 4), acc={k: round(v, 3) for k, v in acc.items()}))
print(f" step {step+1} loss {loss.item():.3f} hmax {hmax} acc {curve[-1]['acc']} {time.time()-t0:.0f}s", flush=True)
return curve, time.time() - t0
def run_chain(name, n_core, passes, carry="inject", steps=15000, varloop=None, seed=0, test_passes=None):
torch.manual_seed(seed)
m = LoopNet(n_core, passes, carry).to(DEV)
eff = 2 + n_core * passes
print(f"== {name}: core={n_core} passes={passes} carry={carry} params={nparams(m)} effective_layers={eff}", flush=True)
curve, secs = train_chains(m, steps, varloop=varloop, seed=seed)
res = dict(name=name, task="chains", n_core=n_core, passes=passes, carry=carry, seed=seed,
params=nparams(m), effective_layers=eff, steps=steps, train_seconds=round(secs),
varloop=varloop, curve=curve)
if test_passes is None:
acc = eval_hops(m)
res["acc"] = acc; res["max_solved"] = max_solved(acc)
print(f" max hops solved (>=90%): {res['max_solved']}", flush=True)
else:
res["acc_by_passes"] = {}
for p in test_passes:
acc = eval_hops(m, passes=p)
res["acc_by_passes"][p] = acc
print(f" passes={p:2d} max solved {max_solved(acc):2d}", flush=True)
res["trace"] = trace_model(m, max(test_passes))
print("RESULT_JSON " + json.dumps(res), flush=True)
return m, res
@torch.no_grad()
def trace_model(m, P, n=1024):
"""Decode after every pass. For chains of d hops, record the average probability the
model puts on each node of the query's chain (position 0 = query, d = answer)."""
m.eval(); out = {}
for d in [4, 8, 16, 24, 32, 48]:
inp, ans, dd, perm, L = chain_batch(n, fixed_hops=d)
with amp(): tr = m(inp, passes=P, trace=True)
chain_nodes = perm[:, :d + 1] # target chain occupies perm[0..d]
mass, acc = [], []
for lg in tr["logits"]:
pr = lg.float().softmax(-1)
mass.append(pr.gather(1, chain_nodes).mean(0).tolist())
acc.append((lg.argmax(-1) == ans).float().mean().item())
out[d] = dict(mass=mass, acc=acc,
norm=[x.float().mean().item() for x in tr["norm"]],
gate=[x.float().mean().item() for x in tr["gate"]])
m.train(); return out
def run_facts(name, n_core, passes, K, steps, B=2048, lr=1e-3, seed=0):
torch.manual_seed(seed)
m = LoopNet(n_core, passes).to(DEV)
table = FactTable(K)
opt = torch.optim.AdamW(m.parameters(), lr=lr, weight_decay=0.0, betas=(0.9, 0.98))
print(f"== {name}: facts K={K} core={n_core} passes={passes} params={nparams(m)}", flush=True)
t0, curve = time.time(), []
for step in range(steps):
cur = lr * min(1, (step + 1) / 300) * 0.5 * (1 + math.cos(math.pi * step / steps))
for g in opt.param_groups: g["lr"] = cur
inp, ans = table.batch(B)
with amp(): loss = F.cross_entropy(m(inp).float(), ans)
opt.zero_grad(set_to_none=True); loss.backward()
torch.nn.utils.clip_grad_norm_(m.parameters(), 1.0); opt.step()
if (step + 1) % 5000 == 0 or step == 0:
curve.append(dict(step=step + 1, loss=round(loss.item(), 4)))
print(f" step {step+1} loss {loss.item():.3f} {time.time()-t0:.0f}s", flush=True)
m.eval(); correct = 0
with torch.no_grad():
for i in range(0, K, 8192):
s = table.subj[i:i + 8192]
with amp(): pred = m(dict(subj=s)).argmax(-1)
correct += (pred == table.ans[i:i + 8192]).sum().item()
res = dict(name=name, task="facts", K=K, n_core=n_core, passes=passes, params=nparams(m),
effective_layers=2 + n_core * passes, steps=steps, facts_correct=correct,
frac_correct=correct / K, bits_stored=correct * math.log2(N),
train_seconds=round(time.time() - t0), curve=curve)
print(f" facts stored: {correct}/{K} ({correct / K:.1%}), {res['bits_stored']/res['params']:.2f} bits/param", flush=True)
print("RESULT_JSON " + json.dumps(res), flush=True)
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("suite")
ap.add_argument("--steps", type=int, default=15000)
ap.add_argument("--fact_steps", type=int, default=40000)
ap.add_argument("--K", type=int, default=250000)
ap.add_argument("--only", default="", help="comma-separated run names to keep")
ap.add_argument("--train_hops", type=int, default=16)
ap.add_argument("--seed", type=int, default=0)
a = ap.parse_args()
print("device", DEV, torch.cuda.get_device_name() if DEV == "cuda" else "", flush=True)
S = a.steps
TRAIN_MAX_HOPS = a.train_hops
if a.suite == "smoke": # quick CPU check of every code path
run_chain("smoke-loop", 2, 2, steps=S)
run_chain("smoke-gated", 2, 2, carry="gated", steps=S, varloop=(1, 3), test_passes=[1, 4])
run_facts("smoke-facts", 2, 2, K=1000, steps=S)
elif a.suite == "sanity":
for name, c, p in [("looped-2x4", 2, 4), ("deep-8", 8, 1), ("shallow-2", 2, 1)]:
run_chain(name, c, p, steps=S)
elif a.suite == "depth": # equal effective depth: looped (2 shared layers x p) vs deep (unique layers)
keep = set(a.only.split(",")) if a.only else None
for name, c, p in [("shallow-2", 2, 1), ("looped-2x2", 2, 2), ("deep-4", 4, 1),
("looped-2x3", 2, 3), ("deep-6", 6, 1), ("looped-2x4", 2, 4),
("deep-8", 8, 1), ("looped-2x6", 2, 6), ("deep-12", 12, 1)]:
if keep is None or name in keep:
run_chain(name, c, p, steps=S)
elif a.suite == "varloop": # trained with 1..6 passes, tested with 1..16
for carry in (a.only.split(",") if a.only else ["inject", "gated", "plain"]):
run_chain(f"varloop-{carry}", 2, 4, carry=carry, steps=S, varloop=(1, 6), seed=a.seed,
test_passes=list(range(1, 17)))
elif a.suite == "law": # one-layer core: is reach set by layers applied (compute) or by parameters?
keep = set(a.only.split(",")) if a.only else None
for name, c, p in [("looped-1x1", 1, 1), ("looped-1x2", 1, 2), ("looped-1x3", 1, 3), ("looped-1x4", 1, 4),
("deep-2", 2, 1), ("deep-3", 3, 1), ("deep-4", 4, 1)]:
if keep is None or name in keep:
run_chain(name, c, p, steps=S, seed=a.seed)
elif a.suite == "facts":
keep = set(a.only.split(",")) if a.only else None
for name, c, p in [("shallow-2", 2, 1), ("looped-2x4", 2, 4), ("deep-8", 8, 1)]:
if keep is None or name in keep:
run_facts(name, c, p, K=a.K, steps=a.fact_steps)
来源
- Thinking Machines,Introducing Inkling 2 Mini、Inkling 2 Mini 模型卡、TML-d24-varloop-research
- Hugging Face,Welcome Inkling 2 Mini
- Z.ai,GLM-5.4 概览
- VentureBeat,Z.ai's GLM-5.4 aims to match models up to four times its size by running 28 layers twice
- Goodfire,Interpreting Inkling 2 Mini
- Dehghani 等,Universal Transformers(2018);Lan 等,ALBERT(2019);Giannou 等,Looped Transformers as Programmable Computers(2023);Saunshi 等,Reasoning with Latent Thoughts(2025);Geiping 等,Scaling up Test-Time Compute with Latent Reasoning(2025);Zhu 等,Scaling Latent Reasoning via Looped Language Models(2025);Allen-Zhu 与 Li,Physics of Language Models: Part 3.3, Knowledge Capacity Scaling Laws(2024)
来源与许可。本文是 David Louapre(Hugging Face)2026 年 11 月 25 日发表于 Hugging Face Spaces 的 《Looped transformers: thinking twice with the same weights》 的完整翻译/改编。原文文字与图表采用 CC-BY 4.0 许可。本站图片为原文交互可视化的静态渲染;交互版、数据与实验脚本见原文 Space。
原文来源:Hugging Face Spaceshttps://huggingface.co/spaces/dlouapre/looped-transformers