Track VI · Frontier Tech Reports · 20/20

GLM-5 — DSA, 비동기 agent RL, on-policy 교차 단계 증류GLM-5 — DSA, asynchronous agent RL and on-policy cross-stage distillation

Zhipu AI의 GLM-5 보고서(그리고 같은 보고서를 인용하는 GLM-5.1–5.3)를 읽는다. 744B/40B MoE에 MLA-256·Muon Split·DSA를 얹은 구조, 28.5T 토큰과 200K까지의 mid-training, IcePop 기반 reasoning RL, π_old를 추적하지 않는 double-sided IS와 staleness 필터로 돌리는 완전 비동기 agentic RL, 단계별 RL로 잃은 능력을 되찾는 on-policy cross-stage distillation을 식과 그림, 코드로 따라간다.A reading of Zhipu AI's GLM-5 report (also the report cited by GLM-5.1–5.3). The 744B/40B MoE with MLA-256, Muon Split and DSA; 28.5T tokens with mid-training up to 200K; IcePop-based reasoning RL; fully asynchronous agentic RL with double-sided importance sampling that never tracks π_old plus a staleness filter; and on-policy cross-stage distillation that recovers what sequential RL stages forget — through equations, figures and code.

GLM-5 is Zhipu AI’s flagship of February 2026, and its report is the one the GitHub README still points to for GLM-5.1, 5.2 and 5.3. The title states the ambition: move from “vibe coding” (a human prompts, the model writes code) to “agentic engineering” (agents plan, implement and iterate on their own). The skeleton is GLM-4.5: a deep MoE, pre-training plus mid-training, staged RL, the slime framework. Four things are new. The model doubles to 744B parameters and adopts DeepSeek Sparse Attention (DSA); the RL infrastructure becomes fully asynchronous, with new algorithms to keep off-policy training stable; the RL stages are stitched together by on-policy cross-stage distillation; and the whole stack is adapted to seven Chinese accelerator platforms. This lesson concentrates on the parts that matter for post-training: the importance-sampling corrections, the asynchronous loop, and distillation as the final stage.

At a glance

ItemGLM-5
LabZhipu AI (Z.ai) & Tsinghua University
Releasereport arXiv v1 2026-02-17, v2 2026-02-24
Size744B total / 40B active (MTP included, embeddings and output layer excluded; Table 10)
ArchitectureMoE: 3 dense + 75 MoE layers + 1 MTP layer, 256 routed experts (8 active) + 1 shared; MLA (64 heads) + DSA (indexer 32 heads × 128, top-k 2048)
Context200K (202,752 tokens in SFT and DSA training)
Tokens28.5T for the base model (18T + 9T pre-training, 1T + 500B + 50B mid-training, 20B DSA adaptation)
Post-trainingSFT → Reasoning RL → Agentic RL → General RL → on-policy cross-stage distillation
Weightsopen, MIT (Hugging Face model card)
LinksarXiv 2602.15763 · GitHub · slime

What is new

  • Scale and attention. 744B/40B with 256 experts, fewer layers than GLM-4.5 (to cut expert-parallel communication), MLA instead of GQA — made competitive with GQA by Muon Split and made cheaper to decode by MLA-256 (fewer, larger heads) — plus DSA introduced by a short continued pre-training.
  • Three MTP layers with shared parameters at training time, giving a longer speculative accept length (2.76 vs DeepSeek-V3.2’s 2.55).
  • Reasoning RL = GRPO + IcePop without KL, with explicit hyper-parameters (β = 2, εlow = 0.2, εhigh = 0.28, group 32, batch 32), and a deterministic top-k in the DSA indexer to keep RL stable.
  • Fully asynchronous agentic RL: a Multi-Task Rollout Orchestrator (1k+ concurrent rollouts), a token-in-token-out gateway, double-sided importance sampling against the rollout log-probs, a staleness filter and group padding for crashed environments.
  • On-policy cross-stage distillation as the last stage: earlier stages’ checkpoints become teachers and the advantage is the teacher–student log-ratio.

GLM-5는 Zhipu AI가 2026년 2월 낸 플래그십이고, 이 보고서는 GLM-5.1·5.2·5.3에 대해서도 GitHub README가 여전히 가리키는 기술 보고서다. 제목이 곧 목표다. 사람이 프롬프트를 쓰고 모델이 코드를 쓰는 “vibe coding”에서, agent가 스스로 계획·구현·반복하는 “agentic engineering”으로 옮겨 간다는 것이다. 골격은 GLM-4.5와 같다(깊은 MoE, 사전학습 + mid-training, 단계별 RL, slime). 새로운 것은 넷이다. 모델을 744B로 두 배 키우며 DeepSeek Sparse Attention(DSA) 을 들였고, RL 인프라를 완전 비동기로 바꾸면서 off-policy 학습을 안정시키는 알고리즘을 더했고, RL 단계들을 on-policy cross-stage distillation으로 묶었고, 전체 스택을 중국 가속기 7종에 맞췄다. 이 레슨은 사후학습에 중요한 부분, 즉 importance sampling 보정, 비동기 루프, 마지막 단계의 증류에 집중한다.

한눈에

항목GLM-5
연구소Zhipu AI (Z.ai) & 칭화대
공개보고서 arXiv v1 2026-02-17, v2 2026-02-24
크기744B / 40B active (MTP 포함, embedding·출력층 제외; Table 10)
구조MoE: dense 3 + MoE 75층 + MTP 1층, routed expert 256개 중 8개 + shared 1개. MLA(64 head) + DSA(indexer 32 head × 128, top-k 2048)
문맥200K (SFT·DSA 학습에서 202,752 토큰)
토큰base 모델 28.5T (사전학습 18T + 9T, mid-training 1T + 500B + 50B, DSA 적응 20B)
사후학습SFT → Reasoning RL → Agentic RL → General RL → on-policy cross-stage distillation
공개가중치 공개, MIT (Hugging Face 모델 카드)
링크arXiv 2602.15763 · GitHub · slime

무엇이 새로운가

  • 규모와 attention. 256 expert의 744B/40B. expert 병렬 통신을 줄이려고 층은 GLM-4.5보다 줄였다. GQA 대신 MLA를 쓰되 Muon Split으로 GQA 수준 품질을 맞추고 MLA-256(head를 줄이고 키움)으로 decode를 싸게 했으며, 짧은 continued pre-training으로 DSA를 들였다.
  • 파라미터를 공유하는 MTP 3층으로 학습해 speculative decoding의 accept length를 늘렸다(2.76 vs DeepSeek-V3.2 2.55).
  • Reasoning RL = GRPO + IcePop, KL 없음. 하이퍼파라미터가 명시되어 있다(β = 2, εlow = 0.2, εhigh = 0.28, group 32, batch 32). RL 안정성을 위해 DSA indexer에 결정적 top-k를 쓴다.
  • 완전 비동기 agentic RL. Multi-Task Rollout Orchestrator(동시 rollout 1천 개 이상), token-in-token-out gateway, rollout log-prob 기준의 double-sided importance sampling, staleness 필터, 환경이 죽은 그룹의 padding.
  • 마지막 단계의 on-policy cross-stage distillation: 앞 단계 체크포인트가 teacher가 되고, advantage는 teacher와 학생의 log 비율이다.

Architecture

Size: 256 experts, fewer layers

GLM-4.5 had argued for depth. GLM-5 goes the other way on purpose: it “scales to 256 experts and reduces its layer count to 80 to minimize expert parallelism communication overhead” (§2.1). At this size, every MoE layer adds an all-to-all, so the number of layers becomes a systems cost.

(Table 10)GLM-4.5GLM-5
total / active355B / 32B744B / 40B
dense / MoE / MTP layers3 / 89 / 13 / 75 / 1
hidden51206144
expert FFN15362048
experts (routed active / shared)160 (8 / 1)256 (8 / 1)
attentionGQA: 96 heads, 8 KV heads, head dim 128MLA: 64 heads, QK head 192, V head 256, Q LoRA 2048, KV LoRA 512
DSA indexer–32 heads × 128
vocabulary151,552154,880

(The text says 80 layers; Table 10 adds up to 3 + 75 + 1 = 79. We report the table.)

MLA, and two fixes to make it work

MLA (inference lesson) caches one 512-dim latent plus a 64-dim RoPE key per token, 576 numbers in all, instead of per-head K and V. The GLM team found that with the Muon optimizer, MLA with a 576-dim cache could not match GQA-8 with its 2,048-dim cache (Table 1). Their fix, Muon Split: instead of orthogonalising the whole up-projections WUQ,WUK,WUVW^{UQ}, W^{UK}, W^{UV} as one matrix each, split them per head and orthogonalise each head’s block separately,

ΔWUK=NS⁡(MUK)⟶ΔWhUK=NS⁡(MhUK)  (h=1,…,H),\Delta W^{UK} = \operatorname{NS}\big(M^{UK}\big)\quad\longrightarrow\quad \Delta W^{UK}_h = \operatorname{NS}\big(M^{UK}_h\big)\ \ (h=1,\dots,H),

so that different heads can update at different scales. The report also notes that with Muon Split the attention logits stayed stable during pre-training without any clipping.

(Table 1)HellaSwagMMLUC-EvalRACEBBHGSM8KHumanEval
GQA-877.361.260.079.653.347.638.5
MLA77.361.559.777.848.946.233.5
MLA + Muon Split77.862.562.179.951.845.036.7
MLA-256 + Muon Split77.462.059.979.651.347.536.6

The second problem is decode cost. In decoding, MLA is run in an “absorbed” MQA form: every head does a 576-dim dot product against the shared cache instead of GQA’s 128. DeepSeek chose its head count for the H800 roofline, which the GLM team calls inappropriate for other hardware. Their MLA-256 raises the head dimension from 192 to 256 and cuts the number of heads by a third, keeping training compute and parameters about the same while reducing decode compute; it matches MLA under Muon Split (Table 1).

아키텍처

크기: expert 256개, 층은 줄인다

GLM-4.5는 깊이를 주장했다. GLM-5는 일부러 반대로 간다. “expert parallelism 통신 부담을 줄이려고 expert를 256개로 늘리고 층 수를 80으로 줄였다”(§2.1). 이 규모에서는 MoE 층마다 all-to-all이 하나씩 붙으므로 층 수 자체가 시스템 비용이 된다.

(Table 10)GLM-4.5GLM-5
총 / active355B / 32B744B / 40B
dense / MoE / MTP 층3 / 89 / 13 / 75 / 1
hidden51206144
expert FFN15362048
expert (선택 / shared)160 (8 / 1)256 (8 / 1)
attentionGQA: 96 head, KV head 8, head 차원 128MLA: 64 head, QK head 192, V head 256, Q LoRA 2048, KV LoRA 512
DSA indexer–32 head × 128
어휘151,552154,880

(본문은 80층이라고 쓰지만 Table 10은 3 + 75 + 1 = 79다. 표를 따랐다.)

MLA, 그리고 그것을 쓰기 위한 두 가지 수정

MLA(추론 최적화)는 head별 K·V 대신 토큰당 512차원 latent와 64차원 RoPE key, 합해 576개 숫자만 캐시한다. GLM 팀은 Muon 옵티마이저로 학습하면 576차원 캐시의 MLA가 2,048차원 캐시의 GQA-8을 따라가지 못한다는 것을 발견했다(Table 1). 해결책은 Muon Split이다. up-projection WUQ,WUK,WUVW^{UQ}, W^{UK}, W^{UV}를 각각 하나의 행렬로 직교화하는 대신 head별로 쪼개 각 블록을 따로 직교화한다.

ΔWUK=NS⁡(MUK)⟶ΔWhUK=NS⁡(MhUK)  (h=1,…,H)\Delta W^{UK} = \operatorname{NS}\big(M^{UK}\big)\quad\longrightarrow\quad \Delta W^{UK}_h = \operatorname{NS}\big(M^{UK}_h\big)\ \ (h=1,\dots,H)

그래서 head마다 다른 크기로 갱신될 수 있다. Muon Split을 쓰면 사전학습 내내 attention logit이 clipping 없이도 안정적이었다고도 쓴다.

(Table 1)HellaSwagMMLUC-EvalRACEBBHGSM8KHumanEval
GQA-877.361.260.079.653.347.638.5
MLA77.361.559.777.848.946.233.5
MLA + Muon Split77.862.562.179.951.845.036.7
MLA-256 + Muon Split77.462.059.979.651.347.536.6

두 번째 문제는 decode 비용이다. decode에서 MLA는 “흡수된” MQA 형태로 돌아서, 모든 head가 공유 캐시에 대해 GQA의 128차원 대신 576차원 내적을 한다. DeepSeek은 head 수를 H800의 roofline에 맞춰 골랐고, GLM 팀은 그것이 다른 하드웨어에는 맞지 않는다고 본다. MLA-256은 head 차원을 192에서 256으로 늘리고 head 수를 1/3 줄여, 학습 연산과 파라미터는 거의 그대로 두면서 decode 연산을 줄인다. Muon Split 하의 MLA와 성능이 같다(Table 1).

한 층에서 캐시된 토큰 하나당 드는 양을 비교한다. 학습·prefill에서 MLA는 latent를 head별 K·V로 펼친 MHA처럼 계산하므로 비용이 H×(dqk+dv)에 비례한다. decode에서는 up-projection을 query·output 쪽에 흡수한 MQA 모드로 576차원(latent 512 + RoPE 64) 캐시 하나를 모든 head가 읽으므로 비용이 H×(576+512), 즉 head 수에만 비례한다. head 수를 줄이고 head 차원을 키우면 학습 비용은 비슷하게 두고 decode 연산만 줄일 수 있다(보고서의 MLA-256). 마지막 줄은 decode의 연산 밀도(FLOPs/byte)다. ridge point를 넘으면 메모리가 아니라 연산이 병목이다. MTP/speculative decoding으로 step당 query 토큰 q를 늘리면 밀도가 q배가 되어 MLA가 금세 연산 병목에 걸린다. GQA-8 행은 GLM-4.5 구성(96 head, KV head 8, head 차원 128)이다. Costs for one cached token in one layer. In training and prefill MLA expands the latent into per-head K and V and runs like MHA, so the cost scales with H×(dqk+dv). In decoding the up-projections are absorbed into the query and output side (MQA mode) and every head reads the same 576-dim cache (512 latent + 64 RoPE), so the cost is H×(576+512) — proportional to the number of heads only. Fewer heads with a larger head dim keeps the training cost about the same and cuts only the decode compute (the report's MLA-256). The last group is the decode arithmetic intensity (FLOPs/byte); above the ridge point the bottleneck is compute, not memory. Raising the query tokens per step q with MTP / speculative decoding multiplies the intensity by q, and MLA quickly becomes compute-bound. The GQA-8 row is the GLM-4.5 configuration (96 heads, 8 KV heads, head dim 128).

Why this works follows from where the head dimension enters each phase. In training and prefill the latent is expanded into per-head keys and values, so the cost per query–key pair is 2H(dqk+dv)2H(d_{qk}+d_v): it depends on H⋅dhH\cdot d_h, which MLA-256 keeps roughly fixed. In absorbed decoding the per-head key is the 576-dim cache itself, so the cost per cached token is 2H(576+512)2H(576+512): it depends on HH only. Fewer heads means cheaper decoding at the same training cost. The figure’s last group shows why it matters most with speculative decoding: with qq draft tokens verified per step, arithmetic intensity is multiplied by qq and MLA with many heads becomes compute-bound.

Note that the head count in Table 10 (64) and the MLA-256 description (head dim 192 → 256, heads −1/3) are not obviously the same configuration (Table 10 lists QK head dim 192 and V head dim 256). The figure lets you compare both readings.

MTP with shared parameters

Predicting nn future tokens normally takes nn MTP layers, so memory grows with the number of speculative steps. DeepSeek-V3 trains one MTP layer and reuses it for two tokens at inference, which lowers the acceptance rate of the second token. GLM-5 shares the parameters of three MTP layers during training: the draft model costs the same memory as one layer but is trained for the multi-step use it gets at inference. With four speculative steps on a private prompt set, the accept length is 2.76 versus DeepSeek-V3.2’s 2.55 (Table 2).

DSA by continued pre-training

DSA (DeepSeek-V3.2 review) adds a lightning indexer that scores all previous tokens and keeps the top-kk (k=2048k=2048) for the main attention, cutting long-context attention cost by about 1.5–2× according to the report. GLM-5 introduces it after mid-training in two stages: a dense warm-up of 1,000 steps (14 sequences of 202,752 tokens per step, LR 5e-3 → 2e-4) that trains only the indexer, then sparse adaptation for 20B tokens with the mid-training data at a constant LR of 1e-5. That is far less than DeepSeek-V3.2’s 943.7B tokens, yet the DSA model ties MLA on long-context tests and on SFT loss.

(Table 3)MQ-NIAH-128kMV-NIAH-128kSQuAD-128kHotpotQA-128k
MLA100.095.579.766.3
DSA100.097.086.063.0

Before settling on DSA, the team ran an ablation on GLM-9B (40 layers, 128K): replacing half of the layers with sliding-window attention (SWA), either alternating or with a layer pattern found by beam search on RULER at 16K, and linear attention (Gated DeltaNet and a simplified version, SimpleGDN, that maps the pre-trained Q/K/V weights directly into the recurrence).

→ Go deeper: Design choices compared — GLM-5’s choices side by side with gpt-oss, MiMo-V2, MiniMax-M2 and MAI-Base-2.

이것이 통하는 이유는 head 차원이 각 단계에 어떻게 들어가는지에서 나온다. 학습·prefill에서는 latent를 head별 key·value로 펼치므로 query–key 쌍당 비용이 2H(dqk+dv)2H(d_{qk}+d_v), 즉 H⋅dhH\cdot d_h에 비례하고 MLA-256은 이 값을 대략 유지한다. 흡수된 decode에서는 head별 key가 576차원 캐시 자체이므로 캐시 토큰당 비용이 2H(576+512)2H(576+512), 즉 HH에만 비례한다. head가 적으면 같은 학습 비용으로 decode가 싸진다. 그림의 마지막 묶음은 이것이 speculative decoding에서 왜 특히 중요한지 보여 준다. step마다 draft 토큰 qq개를 검증하면 연산 밀도가 qq배가 되어 head가 많은 MLA는 연산 병목에 걸린다.

Table 10의 head 수(64)와 MLA-256 설명(head 차원 192 → 256, head 1/3 감소)이 같은 구성인지는 분명하지 않다(Table 10은 QK head 192, V head 256). 그림에서 두 해석을 모두 비교해 볼 수 있다.

파라미터를 공유하는 MTP

미래 토큰 nn개를 예측하려면 보통 MTP 층 nn개가 필요해서, speculative step 수만큼 메모리가 늘어난다. DeepSeek-V3는 MTP 층 하나로 학습하고 추론 때 두 토큰에 재사용하는데, 이 학습–추론 차이가 두 번째 토큰의 수락률을 떨어뜨린다. GLM-5는 학습 때 MTP 3층의 파라미터를 공유한다. draft 모델의 메모리는 한 층과 같지만 추론 때 쓰이는 다단계 방식으로 학습된다. speculative step 4에서 내부 프롬프트셋의 accept length가 2.76으로 DeepSeek-V3.2의 2.55보다 길다(Table 2).

continued pre-training으로 들인 DSA

DSA(DeepSeek-V3.2 리뷰)는 이전 토큰 전체를 점수 매겨 top-kk(k=2048k=2048)만 본 attention에 넘기는 lightning indexer를 더한다. 보고서는 긴 문맥 attention 비용이 1.5–2배 줄어든다고 쓴다. GLM-5는 mid-training 뒤에 두 단계로 들였다. indexer만 학습하는 dense warm-up 1,000 step(step당 202,752 토큰 시퀀스 14개, LR 5e-3 → 2e-4), 그다음 mid-training 데이터로 20B 토큰의 sparse 적응(LR 1e-5 고정). DeepSeek-V3.2의 943.7B보다 훨씬 적지만 DSA 모델은 긴 문맥 시험과 SFT 손실에서 MLA와 비긴다.

(Table 3)MQ-NIAH-128kMV-NIAH-128kSQuAD-128kHotpotQA-128k
MLA100.095.579.766.3
DSA100.097.086.063.0

DSA로 정하기 전에 GLM-9B(40층, 128K)에서 ablation을 돌렸다. 층의 절반을 sliding window attention(SWA)으로 바꾸되 교대로 바꾸거나 16K RULER로 beam search해 찾은 층 pattern으로 바꾸는 방법, 그리고 linear attention(Gated DeltaNet과, 사전학습된 Q/K/V 가중치를 recurrence에 그대로 옮기는 단순화판 SimpleGDN)이다.

→ 더 깊이: 설계 선택 비교 — GLM-5의 선택을 gpt-oss, MiMo-V2, MiniMax-M2, MAI-Base-2와 나란히 놓는다.

위: GLM-9B(40층)에서 SWA(창 4,096)로 바꿀 층(S)과 full attention으로 남길 층(F). 고정 교대(interleave)와 beam search로 찾은 pattern 모두 1:1 비율이다. 가운데: 추가 학습 없이 층만 바꿨을 때의 RULER(Table 4). 아래: 64K 문맥으로 190B 토큰 계속 학습한 뒤 full attention 대비 차이(Table 5). 벤치마크를 바꿔 보면 어느 방법이든 128K의 세밀한 검색(RULER, RepoQA)에서 손실이 남는다는 것이 보인다. DSA를 겹치면 base가 다른(GLM-4.7-Flash) 별도 실험이지만, indexer warm-up만으로는 128K에서 떨어졌다가 150B 토큰 공동 학습 뒤 거의 회복하는 모양이다. 찾은 pattern 문자열은 보고서에 41자(S 21, F 20)로 적혀 있어 40층과 한 자리가 맞지 않는다. 그대로 옮겼다. Top: in GLM-9B (40 layers), the layers converted to SWA (window 4,096; S) and the layers kept as full attention (F), for the fixed alternation (interleave) and the beam-searched pattern; both use a 1:1 ratio. Middle: RULER when only the layers are swapped, without further training (Table 4). Bottom: the difference to full attention after 190B tokens of continued training at 64K (Table 5). Switch the benchmark: every method keeps a loss on fine-grained retrieval at 128K (RULER, RepoQA). The DSA overlay is a separate experiment on a different base (GLM-4.7-Flash): indexer warm-up alone drops at 128K, and 150B tokens of joint training nearly recover it. The searched pattern string is printed in the report with 41 characters (21 S, 20 F), one more than the 40 layers; it is reproduced as printed.

The report’s reading: naive interleaving is catastrophic (−30.35 on RULER@128K), the searched pattern narrows the gap, linear attention narrows it further, but every variant keeps a loss on fine-grained retrieval at 128K (up to −5.69 RULER, −7.33 RepoQA for the best ones), “even when half of the layers retain full attention”. DSA, in contrast, is “lossless by construction”: the indexer picks tokens per query, so no long-range dependency is structurally removed. A small DSA experiment on GLM-4.7-Flash (Table 6) supports this: after 150B tokens of joint training it beats the dense baseline at 16K–64K and is 0.35 points behind at 128K.

Data

보고서의 해석은 이렇다. 단순 교대는 파국적이고(RULER@128K −30.35), 찾은 pattern이 격차를 줄이고, linear attention이 더 줄이지만, 모든 변형이 128K의 세밀한 검색에서 손실을 남긴다(가장 나은 쪽도 RULER −5.69, RepoQA −7.33). “층의 절반이 full attention을 유지하는데도” 그렇다. 반면 DSA는 “구조상 손실이 없다”. indexer가 query마다 토큰을 고르므로 어떤 장거리 의존도 구조적으로 잘리지 않는다는 것이다. GLM-4.7-Flash에서 한 소규모 DSA 실험(Table 6)이 이를 뒷받침한다. 150B 토큰 공동 학습 뒤 16K–64K에서 dense 기준선을 넘고 128K에서는 0.35점 뒤진다.

데이터

단계stage –seq –LR –batch –

커서를 끌어 보면 그 시점의 단계·sequence 길이·학습률·batch 크기가 읽힌다. "토큰 비례"로 보면 mid-training은 전체의 5% 남짓에 불과하지만, "단계별 같은 폭"으로 펼치면 그 짧은 구간에서 sequence 길이가 4K→128K(GLM-5는 200K)로 늘고 데이터 성격이 repo 코드·합성 추론·agent 궤적으로 바뀐다는 것이 보인다. 학습률 warmup 길이는 두 보고서 모두 밝히지 않아 짧게 그렸다(개략). Drag the cursor to read off the stage, sequence length, learning rate and batch size at that point. On the "proportional" axis mid-training is only about 5% of all tokens, but spread out with "equal width per stage" you can see that in this short stretch the sequence length grows from 4K to 128K (200K for GLM-5) and the data changes to repo code, synthetic reasoning and agent trajectories. Neither report gives the learning-rate warm-up length, so it is drawn short (schematic).

The pipeline is GLM-4.5’s, scaled (report Fig. 5, §2.2–2.3).

  • Pre-training (27T at 4K). 18T general, then 9T code & reasoning. New for the web: a sentence-embedding DCLM classifier to find more high-quality data, and a World-Knowledge classifier (trained on Wikipedia entries and LLM labels) to pull long-tail knowledge out of medium/low-quality pages. Code: refreshed snapshots and more code-containing web pages give +28% unique tokens after fuzzy dedup; metadata fixes for Software Heritage files; classifiers for low-resource languages (Scala, Swift, Lua, …). Maths & science: better HTML/PDF extraction, LLM scoring that keeps only the most educational content, chunk-and-aggregate scoring for long documents, and explicit exclusion of synthetic, AI-generated or templated data.
  • Mid-training (1.55T). 32K for 1T, 128K for 500B, 200K for 50B. SWE data: relaxed repository-level filters but stricter issue-level filters yield about 10 million issue–PR pairs, with more relevant files retrieved per pair; the issue–PR part is about 160B unique tokens. Long context: natural long documents (filtered by PPL, dedup, length) plus synthetic long-range data inspired by NextLong and EntropyLong, with similar texts packed together against lost-in-the-middle; MRCR-style multi-turn recall data at 200K. The 200K stage improved scores even inside 128K.
  • DSA adaptation (20B at 200K).
  • SFT. Much more agent and coding data than GLM-4.5, maximum length 202,752. For maths and science, only problems that are hard for GLM-4.7 are kept. Agent trajectories come from many execution environments; erroneous segments are kept in the trajectory but masked out of the loss, so the model learns to recover from errors without being trained to make them.

Training

Pre-training recipe and infrastructure

Muon, cosine decay and batch-size warm-up as in GLM-4.5; LR warms up to 2e-4 and decays to 4e-5 by the end of pre-training, then linearly from 4e-5 to 1e-5 through mid-training (Appendix A). The infrastructure section lists memory and parallelism work: placing the MTP output layer with the main output layer on the last pipeline stage, ZeRO-2-style gradient sharding inside pipeline stages with double buffering, a zero-redundancy Muon all-gather, layer-wise activation offloading, chunked output projection + loss, deferred weight-gradient computation, and context-parallel groups of variable size for long sequences. INT4 quantization-aware training is applied in SFT, with a kernel shared by training and offline quantization so the two are bit-identical.

Post-training

파이프라인은 GLM-4.5의 것을 키운 것이다(보고서 Fig. 5, §2.2–2.3).

  • 사전학습 (27T, 4K). 일반 18T, 이어서 코드·추론 9T. 웹에는 문장 임베딩 기반 DCLM 분류기(고품질 데이터를 더 찾기)와 Wikipedia 항목·LLM 라벨로 학습한 World Knowledge 분류기(중·저품질 페이지에서 long-tail 지식 건지기)를 더했다. 코드는 스냅샷 갱신과 코드가 든 웹 페이지 확대로 fuzzy dedup 기준 고유 토큰 +28%, Software Heritage 파일의 메타데이터 수정, 저자원 언어(Scala, Swift, Lua …) 분류기. 수학·과학은 HTML·PDF 추출 개선, 가장 교육적인 내용만 남기는 LLM 점수, 긴 문서용 chunk-and-aggregate 점수, 그리고 합성·AI 생성·템플릿 데이터의 명시적 배제.
  • Mid-training (1.55T). 32K 1T, 128K 500B, 200K 50B. SWE 데이터는 repo 단위 필터를 완화하고 issue 단위 필터를 강화해 issue–PR 쌍 약 1천만 개, 쌍마다 관련 파일을 더 많이 붙였고, issue–PR 부분이 약 160B 고유 토큰이다. 긴 문맥은 자연 긴 문서(PPL·dedup·길이 필터)와 NextLong·EntropyLong에서 착안한 합성 장거리 데이터, lost-in-the-middle을 막는 유사 텍스트 묶음, 200K 단계의 MRCR식 멀티턴 recall 데이터. 200K 단계는 128K 이내 점수도 올렸다.
  • DSA 적응 (20B, 200K).
  • SFT. GLM-4.5보다 agent·코딩 데이터가 훨씬 많고 최대 길이 202,752. 수학·과학은 GLM-4.7에게 어려운 문제만 남긴다. agent 궤적은 다수의 실행 환경에서 얻고, 궤적 안의 잘못된 구간은 남기되 손실에서 mask한다. 실수를 학습하지 않으면서 실수에서 회복하는 법을 배우게 하려는 것이다.

학습

사전학습 recipe와 인프라

GLM-4.5처럼 Muon, cosine 감쇠, batch warm-up. LR은 2e-4까지 올라 사전학습 끝에 4e-5로 내려가고, mid-training 동안 4e-5에서 1e-5로 선형 감소한다(부록 A). 인프라 절은 메모리·병렬화 작업을 나열한다. MTP 출력층을 주 출력층과 같은 마지막 pipeline stage에 두기, pipeline stage 안의 ZeRO-2식 gradient sharding과 double buffering, 중복 없는 Muon all-gather, 층 단위 activation offloading, 구간별 output projection + loss, weight gradient 지연 계산, 긴 시퀀스를 위한 가변 크기 context-parallel 그룹. SFT에서는 INT4 quantization-aware training을 하고, 학습과 오프라인 양자화가 같은 kernel을 써서 비트 단위로 일치한다.

사후학습

입력input
출력output
입력 길이input length –직전 호출과 같은 prefixprefix shared with previous call –새로 prefill할 토큰tokens to prefill anew –
보고서 Fig. 7을 옮긴 것이다. turn 1에서는 tool 호출 사이사이에 추론한다(interleaved). turn 2로 넘어갈 때 지난 턴의 추론 블록을 지우는 것이 흔한 chat template이고, GLM-5는 coding agent 상황에서 이를 보존한다(preserved). 두 turn 2 버튼을 번갈아 눌러 보면 보존할 때 입력이 길어지는 대신 직전 호출의 시퀀스 전체가 그대로 prefix가 되어 KV cache를 재사용할 수 있고, 지우면 User 1 뒤부터 prefix가 어긋나 나머지를 다시 prefill해야 한다는 것이 보인다(캐시 재사용 수치는 이 그림의 계산이며 보고서의 측정이 아니다). A re-drawing of the report's Fig. 7. In turn 1 the model reasons between tool calls (interleaved). Many chat templates delete the previous turn's reasoning blocks when moving to turn 2; in coding-agent settings GLM-5 preserves them. Toggle the two turn-2 buttons: preserving makes the input longer, but the entire previous sequence becomes a prefix whose KV cache can be reused; deleting breaks the prefix right after User 1, so everything after it must be prefilled again (the cache-reuse numbers are this figure's arithmetic, not a measurement from the report).

SFT and thinking modes (§3.1). The chat template supports three behaviours: interleaved thinking (think before every response and tool call), preserved thinking (in coding-agent settings, keep all thinking blocks across turns and reuse them instead of re-deriving), and turn-level thinking (switch reasoning on or off per turn). The report credits Claude for the first two ideas. For agent post-training, preserved thinking matters twice: the model sees its own earlier reasoning, and — as the figure shows — the previous call’s whole sequence remains a prefix, which keeps the KV cache reusable (later GLM-5.3 makes clear_thinking=false the template default).

Reasoning RL (§3.2). GRPO plus IcePop, with the KL term removed “to accelerate RL improvement”. The report distinguishes the policy used for gradients, πtrain\pi^{\text{train}}, from the policy that sampled, πinfer\pi^{\text{infer}} (same weights, different engine and kernels):

L(θ)=−Ex,{yi}∼πθoldinfer[1G∑i=1G1∣yi∣∑t=1∣yi∣pop⁡(ρi,t,1β,β)⋅min⁡(ri,tA^i, clip⁡(ri,t,1−εlow,1+εhigh)A^i)]\mathcal{L}(\theta)=-\mathbb{E}_{x,\{y_i\}\sim\pi^{\text{infer}}_{\theta_{\text{old}}}}\Bigg[\frac1G\sum_{i=1}^{G}\frac{1}{|y_i|}\sum_{t=1}^{|y_i|}\operatorname{pop}\big(\rho_{i,t},\tfrac1\beta,\beta\big)\cdot\min\Big(r_{i,t}\hat A_{i},\ \operatorname{clip}(r_{i,t},1-\varepsilon_{\text{low}},1+\varepsilon_{\text{high}})\hat A_{i}\Big)\Bigg]ρi,t=πθoldtrain(yi,t∣⋅)πθoldinfer(yi,t∣⋅),ri,t=πθtrain(yi,t∣⋅)πθoldtrain(yi,t∣⋅),pop⁡(ρ,1β,β)={ρ1β≤ρ≤β0otherwise\rho_{i,t}=\frac{\pi^{\text{train}}_{\theta_{\text{old}}}(y_{i,t}\mid\cdot)}{\pi^{\text{infer}}_{\theta_{\text{old}}}(y_{i,t}\mid\cdot)},\qquad r_{i,t}=\frac{\pi^{\text{train}}_{\theta}(y_{i,t}\mid\cdot)}{\pi^{\text{train}}_{\theta_{\text{old}}}(y_{i,t}\mid\cdot)},\qquad \operatorname{pop}(\rho,\tfrac1\beta,\beta)=\begin{cases}\rho & \tfrac1\beta\le\rho\le\beta\\ 0&\text{otherwise}\end{cases}

with A^i=(Ri−mean⁡R)/std⁡R\hat A_i=(R_i-\operatorname{mean} R)/\operatorname{std} R, β=2\beta=2, εlow=0.2\varepsilon_{\text{low}}=0.2, εhigh=0.28\varepsilon_{\text{high}}=0.28, fully on-policy, group 32, batch 32. Two factors play different roles. ri,tr_{i,t} is the usual PPO ratio across updates; ρi,t\rho_{i,t} is a truncated importance weight that corrects for the fact that samples came from the inference engine, and tokens whose engines disagree by more than a factor of 2 are dropped entirely (train–inference mismatch). The domains are maths, science, code and tool-integrated reasoning, mixed roughly evenly; maths/science problems are filtered to those GLM-4.7 rarely or never solves but stronger teachers (e.g. GPT-5.2 xhigh, Gemini 3 Pro Preview) can.

DSA in RL. The indexer’s top-kk is to DSA what expert routing is to MoE: if training and inference select different tokens, they are evaluating different functions. Replaying the indices (like MoE routing replay) is impractical because k=2048k=2048 indices per token is too much to store and send. The fix was mundane: use the deterministic torch.topk in the training engine instead of the non-deterministic CUDA/TileLang top-k used in SGLang’s indexer. With non-deterministic top-k, RL “degraded drastically after only a few steps, accompanied by a sharp drop in entropy”. The indexer parameters are also frozen during RL.

Agentic RL (§3.3, §4). Coding and search agents, trained fully asynchronously (deep dive below) on more than 10K verifiable SWE environments (built with a RepoLaunch-based pipeline across 9 languages), thousands of synthesized terminal tasks in Harbor format (Docker build accuracy above 90%), and multi-hop search questions generated from a web knowledge graph of over two million pages and filtered for difficulty. The agentic objective is the same group-mean-baseline policy gradient as in GLM-4.5, with environment tokens masked.

General RL (§3.4). Three objectives — foundational correctness, emotional intelligence, task-specific quality — supervised by a hybrid of rule-based rewards, outcome reward models (low variance but hackable) and generative reward models (robust but noisier), plus human-written responses as stylistic anchors against “model-like” verbosity.

On-policy cross-stage distillation (§3.5). Sequential RL stages erode earlier skills. The last stage therefore takes the final checkpoints of earlier stages as teachers, samples prompts from each teacher’s RL training set, and replaces the advantage in Eq. (1) with

A^i,t=sg⁡[log⁡πθteacherinfer(yi,t∣x,yi,<t)πθtrain(yi,t∣x,yi,<t)],\hat A_{i,t}=\operatorname{sg}\Big[\log\frac{\pi^{\text{infer}}_{\theta_{\text{teacher}}}(y_{i,t}\mid x,y_{i,<t})}{\pi^{\text{train}}_{\theta}(y_{i,t}\mid x,y_{i,<t})}\Big],

with group size 1 and batch size 1024 — no group is needed because the baseline is the teacher, not other samples. Since y∼πθy\sim\pi_\theta, the expected gradient is that of the reverse KL −∇θDKL(πθ ∥ πteacher)-\nabla_\theta D_{\text{KL}}(\pi_\theta\,\|\,\pi_{\text{teacher}}) per prompt (distillation lesson).

slime (§3.6). No new components, but GLM-5 leans on: free-form rollout functions and HTTP-exposed rollout servers/router; tail-latency work — multi-node inference (e.g. EP64 / DP64 over 8 nodes) with DP-attention so requests never queue, FP8 rollouts, MTP (most useful for small-batch stragglers), prefill–decode disaggregation so long multi-turn prefills do not stall decodes; and heartbeat-based fault tolerance that deregisters unhealthy servers.

→ Go deeper: Engineering away the training–inference mismatch for IcePop and index replay, Long-horizon RL for the agentic stages, and Inference for RL and Parallelism for serving, and MoE for slime’s rollout side (EP/DP-attention, prefill–decode disaggregation).

SFT와 thinking 모드 (§3.1). chat template이 세 가지 동작을 지원한다. interleaved thinking(응답과 tool 호출 전마다 생각), preserved thinking(coding agent 상황에서 모든 thinking 블록을 turn을 넘어 유지하고 다시 유도하는 대신 재사용), turn-level thinking(turn마다 추론을 켜고 끔). 앞의 두 아이디어는 Claude에서 왔다고 밝힌다. agent 사후학습에서 preserved thinking은 두 번 중요하다. 모델이 자신의 이전 추론을 보고, 그림에서 보듯 직전 호출의 시퀀스 전체가 prefix로 남아 KV cache를 재사용할 수 있다(이후 GLM-5.3은 template 기본값을 clear_thinking=false로 둔다).

Reasoning RL (§3.2). GRPO + IcePop, KL 항은 “RL 향상을 빠르게 하려고” 뺐다. 보고서는 gradient에 쓰는 정책 πtrain\pi^{\text{train}}과 샘플을 뽑은 정책 πinfer\pi^{\text{infer}}(같은 가중치, 다른 엔진·kernel)를 구분한다.

L(θ)=−Ex,{yi}∼πθoldinfer[1G∑i=1G1∣yi∣∑t=1∣yi∣pop⁡(ρi,t,1β,β)⋅min⁡(ri,tA^i, clip⁡(ri,t,1−εlow,1+εhigh)A^i)]\mathcal{L}(\theta)=-\mathbb{E}_{x,\{y_i\}\sim\pi^{\text{infer}}_{\theta_{\text{old}}}}\Bigg[\frac1G\sum_{i=1}^{G}\frac{1}{|y_i|}\sum_{t=1}^{|y_i|}\operatorname{pop}\big(\rho_{i,t},\tfrac1\beta,\beta\big)\cdot\min\Big(r_{i,t}\hat A_{i},\ \operatorname{clip}(r_{i,t},1-\varepsilon_{\text{low}},1+\varepsilon_{\text{high}})\hat A_{i}\Big)\Bigg]ρi,t=πθoldtrain(yi,t∣⋅)πθoldinfer(yi,t∣⋅),ri,t=πθtrain(yi,t∣⋅)πθoldtrain(yi,t∣⋅),pop⁡(ρ,1β,β)={ρ1β≤ρ≤β0그 외\rho_{i,t}=\frac{\pi^{\text{train}}_{\theta_{\text{old}}}(y_{i,t}\mid\cdot)}{\pi^{\text{infer}}_{\theta_{\text{old}}}(y_{i,t}\mid\cdot)},\qquad r_{i,t}=\frac{\pi^{\text{train}}_{\theta}(y_{i,t}\mid\cdot)}{\pi^{\text{train}}_{\theta_{\text{old}}}(y_{i,t}\mid\cdot)},\qquad \operatorname{pop}(\rho,\tfrac1\beta,\beta)=\begin{cases}\rho & \tfrac1\beta\le\rho\le\beta\\ 0&\text{그 외}\end{cases}

A^i=(Ri−mean⁡R)/std⁡R\hat A_i=(R_i-\operatorname{mean} R)/\operatorname{std} R, β=2\beta=2, εlow=0.2\varepsilon_{\text{low}}=0.2, εhigh=0.28\varepsilon_{\text{high}}=0.28, 완전 on-policy, group 32, batch 32. 두 인자의 역할이 다르다. ri,tr_{i,t}는 갱신 사이의 보통 PPO ratio이고, ρi,t\rho_{i,t}는 샘플이 추론 엔진에서 나왔다는 사실을 보정하는 잘린 importance weight다. 두 엔진이 2배 넘게 어긋나는 토큰은 통째로 빠진다(학습–추론 불일치). 도메인은 수학·과학·코드·tool-integrated reasoning을 대략 같은 비율로 섞고, 수학·과학 문제는 GLM-4.7이 거의 못 풀거나 전혀 못 풀지만 더 강한 teacher(GPT-5.2 xhigh, Gemini 3 Pro Preview 등)는 푸는 것으로 거른다.

RL 속의 DSA. indexer의 top-kk는 DSA에게 MoE의 expert routing과 같다. 학습과 추론이 다른 토큰을 고르면 서로 다른 함수를 평가하는 셈이다. MoE의 routing replay처럼 index를 재생하는 것은 토큰마다 2,048개 index를 저장·전송해야 해서 비현실적이다. 해결은 평범했다. SGLang indexer의 비결정적 CUDA/TileLang top-k 대신 학습 엔진에서 결정적인 torch.topk 를 쓴다. 비결정적 top-k로는 RL이 “몇 step 만에 급격히 나빠지고 entropy가 급락”했다. RL 동안 indexer 파라미터는 고정한다.

Agentic RL (§3.3, §4). coding·search agent를 완전 비동기로 학습한다(아래 깊게 보기). 환경은 RepoLaunch 기반 파이프라인으로 9개 언어에 걸쳐 만든 1만 개 이상의 검증 가능한 SWE 환경, Harbor 형식으로 합성한 수천 개 terminal 과제(Docker 빌드 정확도 90% 이상), 200만 페이지 넘는 웹 지식 그래프에서 만들고 난이도로 거른 multi-hop 검색 질문이다. 목적함수는 GLM-4.5와 같은 그룹 평균 baseline 정책 경사이고 환경 토큰은 mask한다.

General RL (§3.4). 기본 정확성, 감성 지능, 과제별 품질의 세 목표를 규칙 보상, outcome RM(분산이 낮지만 해킹에 약함), generative RM(견고하지만 잡음이 큼)의 혼합으로 감독한다. “모델 같은” 장황함을 막으려고 사람이 쓴 응답을 문체의 기준점으로 쓴다.

On-policy cross-stage distillation (§3.5). RL 단계를 이어 가면 앞에서 얻은 능력이 깎인다. 그래서 마지막 단계는 앞 단계들의 최종 체크포인트를 teacher로 삼아, 각 teacher의 RL 학습 프롬프트를 섞어 뽑고, 식 (1)의 advantage를 다음으로 바꾼다.

A^i,t=sg⁡[log⁡πθteacherinfer(yi,t∣x,yi,<t)πθtrain(yi,t∣x,yi,<t)]\hat A_{i,t}=\operatorname{sg}\Big[\log\frac{\pi^{\text{infer}}_{\theta_{\text{teacher}}}(y_{i,t}\mid x,y_{i,<t})}{\pi^{\text{train}}_{\theta}(y_{i,t}\mid x,y_{i,<t})}\Big]

group 크기 1, batch 1024다. baseline이 다른 샘플이 아니라 teacher이므로 그룹이 필요 없다. y∼πθy\sim\pi_\theta이므로 기대 gradient는 프롬프트마다 reverse KL −∇θDKL(πθ ∥ πteacher)-\nabla_\theta D_{\text{KL}}(\pi_\theta\,\|\,\pi_{\text{teacher}})의 gradient다(증류 레슨).

slime (§3.6). 새 구성요소는 없지만 GLM-5가 기대는 기능은 이렇다. 자유로운 rollout 함수와 HTTP로 노출된 rollout 서버·router, tail latency 작업(요청이 줄 서지 않도록 DP-attention을 쓴 다중 노드 추론, 예: 8노드 EP64/DP64, FP8 rollout, 작은 batch의 꼬리 샘플에 특히 좋은 MTP, 긴 멀티턴 prefill이 decode를 멈추지 않게 하는 prefill–decode 분리), 그리고 불량 서버를 router에서 빼는 heartbeat 기반 장애 허용.

→ 더 깊이: IcePop과 index replay는 학습–추론 불일치 엔지니어링, agentic 단계는 Long-horizon RL, slime의 rollout 쪽(EP/DP-attention, prefill–decode 분리)은 RL을 위한 추론과 서빙을 위한 병렬화와 MoE.

Key methods in depth

1. Two ways to discard a token: IcePop vs double-sided IS

Both reasoning RL and agentic RL multiply each token’s gradient by a ratio and zero it when the ratio leaves a band. They differ in which ratio.

  • Synchronous (Eq. 1). πθold\pi_{\theta_{\text{old}}} is known exactly, so two ratios can be separated: ρ\rho (engine mismatch, same weights) gets the wide IcePop band [1/β,β]=[0.5,2][1/\beta,\beta]=[0.5,2], while rr (policy change) gets the usual PPO clip.
  • Asynchronous (Eqs. 3–5). A trajectory may be generated across several weight versions, so πθold\pi_{\theta_{\text{old}}} would require keeping a history of checkpoints. GLM-5 drops it and uses the rollout log-probs directly:
L(θ)=Et[f(rt;εℓ,εh) A^tlog⁡πθ(at∣st)],rt=exp⁡(log⁡πθ(at∣st)−log⁡πrollout(at∣st)),f(x)={x1−εℓ<x<1+εh0otherwise\mathcal{L}(\theta)=\mathbb{E}_t\big[f(r_t;\varepsilon_\ell,\varepsilon_h)\,\hat A_t\log\pi_\theta(a_t\mid s_t)\big],\qquad r_t=\exp\big(\log\pi_\theta(a_t\mid s_t)-\log\pi_{\text{rollout}}(a_t\mid s_t)\big),\qquad f(x)=\begin{cases}x & 1-\varepsilon_\ell<x<1+\varepsilon_h\\0&\text{otherwise}\end{cases}

Read with ff as a constant weight (stop-gradient), the gradient is f(rt)A^t∇log⁡πθ=rtA^t∇log⁡πθf(r_t)\hat A_t\nabla\log\pi_\theta = r_t\hat A_t\nabla\log\pi_\theta inside the band — the same as the PPO surrogate rtA^tr_t\hat A_t — and exactly zero outside it, on both sides and for both signs of A^\hat A. That is the difference from PPO’s clip, which only stops a token on the side where the update would push it further. One ratio now carries engine mismatch, staleness and the current update together, so the band must be tight.

핵심 method 깊게 보기

1. 토큰을 버리는 두 방법: IcePop vs double-sided IS

reasoning RL과 agentic RL 모두 토큰마다 gradient에 비율을 곱하고, 비율이 띠를 벗어나면 0으로 만든다. 차이는 어떤 비율이냐다.

  • 동기 (식 1). πθold\pi_{\theta_{\text{old}}}를 정확히 알므로 두 비율을 나눌 수 있다. 엔진 불일치(같은 가중치) ρ\rho에는 넓은 IcePop 띠 [1/β,β]=[0.5,2][1/\beta,\beta]=[0.5,2]를, 정책 변화 rr에는 보통의 PPO clip을 건다.
  • 비동기 (식 3–5). 궤적 하나가 여러 가중치 버전에 걸쳐 생성될 수 있어 πθold\pi_{\theta_{\text{old}}}를 쓰려면 체크포인트 이력을 들고 있어야 한다. GLM-5는 그것을 버리고 rollout 때 기록한 log-prob을 직접 쓴다.
L(θ)=Et[f(rt;εℓ,εh) A^tlog⁡πθ(at∣st)],rt=exp⁡(log⁡πθ(at∣st)−log⁡πrollout(at∣st)),f(x)={x1−εℓ<x<1+εh0그 외\mathcal{L}(\theta)=\mathbb{E}_t\big[f(r_t;\varepsilon_\ell,\varepsilon_h)\,\hat A_t\log\pi_\theta(a_t\mid s_t)\big],\qquad r_t=\exp\big(\log\pi_\theta(a_t\mid s_t)-\log\pi_{\text{rollout}}(a_t\mid s_t)\big),\qquad f(x)=\begin{cases}x & 1-\varepsilon_\ell<x<1+\varepsilon_h\\0&\text{그 외}\end{cases}

ff를 상수 가중치(stop-gradient)로 읽으면, 띠 안에서 gradient는 f(rt)A^t∇log⁡πθ=rtA^t∇log⁡πθf(r_t)\hat A_t\nabla\log\pi_\theta = r_t\hat A_t\nabla\log\pi_\theta로 PPO 대리목적 rtA^tr_t\hat A_t의 gradient와 같고, 띠 밖에서는 양쪽 모두, A^\hat A의 부호와 무관하게 정확히 0이다. 갱신이 더 밀어붙이는 쪽에서만 토큰을 멈추는 PPO clip과 다른 점이다. 이제 비율 하나가 엔진 불일치, staleness, 현재 갱신을 모두 담으므로 띠가 좁아야 한다.

mask된 토큰masked tokens – 남은 토큰의 평균 가중치mean weight of kept tokens – |log 비율| > 1 인 꼬리tail with |log ratio| > 1 –
토큰 4,000개의 log 비율 분포(회색 막대, 꼬리가 두꺼운 t-분포로 흉내 낸 가상의 예)와, 그 토큰에 곱해지는 가중치 함수(빨간 선, 오른쪽 축)다. 초록 띠 밖의 토큰은 gradient에서 완전히 빠진다. 동기 모드에서 비율은 같은 파라미터 θold에 대한 학습 엔진과 추론 엔진의 확률 비 ρ = πtrain/πinfer이고, IcePop은 [1/β, β] 밖을 0으로 만든다(보고서 β=2). 이 띠는 넓어서 수치 차이가 극단적인 토큰만 잘라낸다. 비동기 모드에서는 πold를 추적하지 않고 rollout 때 기록한 log-prob을 그대로 써서 r = πθ/πrollout을 계산하므로, 수치 차이에 정책 지연(rollout 중에도 가중치가 바뀐다)이 더해진다. 지연을 키우면 분포가 퍼지고 [1−εℓ, 1+εh] 밖으로 mask되는 토큰이 빠르게 는다. 보고서는 비동기 쪽 ε 값을 밝히지 않아 기본값은 reasoning RL의 0.2/0.28을 썼다. The distribution of log ratios over 4,000 tokens (grey bars; an illustrative heavy-tailed t-distribution) and the weight multiplied onto each token (red line, right axis). Tokens outside the green band are removed from the gradient entirely. In sync mode the ratio is ρ = πtrain/πinfer, the probability ratio between the training and the inference engine for the same parameters θold; IcePop zeroes everything outside [1/β, β] (report: β=2). That band is wide and only removes tokens with extreme numerical disagreement. In async mode πold is not tracked; the log-probs recorded at rollout time are used directly, r = πθ/πrollout, so policy lag (weights change even during a rollout) adds to the numerical noise. Increase the lag and the distribution widens; the share masked outside [1−εℓ, 1+εh] grows quickly. The report does not give the async ε values; the defaults reuse the reasoning-RL 0.2/0.28.
NumPy IcePop loss, double-sided IS, and the staleness / group filter
import numpy as np

rng = np.random.default_rng(0)
G, T = 4, 6                                         # group of 4 responses, 6 tokens each (toy)
R = np.array([1.0, 0.0, 1.0, 0.0])                  # outcome rewards
A = (R - R.mean()) / (R.std() + 1e-6)               # GRPO advantage, shared by all tokens of a response
A_tok = np.repeat(A[:, None], T, axis=1)

logp_infer = np.log(rng.uniform(0.05, 0.9, (G, T)))          # log π_old^infer (rollout engine)
logp_train_old = logp_infer + rng.normal(0, 0.15, (G, T))    # log π_old^train (same θ_old, other kernels)
logp_train_old[1, 2] += 1.2                                  # one token with a big train–infer mismatch
logp_new = logp_train_old + rng.normal(0, 0.1, (G, T))       # log π_θ after a few updates


def icepop_loss(logp_new, beta=2.0, eps_low=0.2, eps_high=0.28):
    """GLM-5 Eq. (1): pop(ρ) · min(r Â, clip(r) Â), sequence-mean then group-mean, no KL."""
    rho = np.exp(logp_train_old - logp_infer)                    # train–inference mismatch (constant)
    pop = np.where((rho >= 1 / beta) & (rho <= beta), rho, 0.0)
    r = np.exp(logp_new - logp_train_old)                        # PPO ratio
    surr = np.minimum(r * A_tok, np.clip(r, 1 - eps_low, 1 + eps_high) * A_tok)
    return -(pop * surr).mean(axis=1).mean(), pop


def double_sided_loss(logp_new, logp_rollout, eps_l=0.2, eps_h=0.28):
    """GLM-5 Eqs. (3)–(5): f(r) Â log π_θ with r = π_θ / π_rollout; f is used as a constant weight."""
    r = np.exp(logp_new - logp_rollout)
    f = np.where((r > 1 - eps_l) & (r < 1 + eps_h), r, 0.0)
    return -(f * A_tok * logp_new).mean(), f


L1, pop = icepop_loss(logp_new)
print("IcePop loss %.4f | tokens zeroed by pop: %d of %d" % (L1, (pop == 0).sum(), pop.size))
print("  zeroed position(s):", [(int(i), int(t)) for i, t in zip(*np.where(pop == 0))])

# gradient check w.r.t. log π_θ (finite differences): masked tokens get exactly 0
eps = 1e-6
g = np.zeros_like(logp_new)
for i in range(G):
    for t in range(T):
        d = np.zeros_like(logp_new); d[i, t] = eps
        g[i, t] = (icepop_loss(logp_new + d)[0] - icepop_loss(logp_new - d)[0]) / (2 * eps)
print("  dL/dlogp at the mismatched token:", round(g[1, 2], 6), "| max |dL| elsewhere:", round(np.abs(g).max(), 4))

# asynchronous case: the rollout log-probs come from a policy that is `lag` versions old
for lag in [0, 2, 6]:
    logp_rollout = logp_new - rng.normal(0, 0.06 * np.sqrt(lag) + 0.05, (G, T))
    L2, f = double_sided_loss(logp_new, logp_rollout)
    print(f"double-sided IS, lag={lag}: masked {(f == 0).mean():.0%} of tokens, loss {L2:.4f}")


def filter_group(group, w_now, tau, G):
    """§4.1.2: drop stale samples (w' - w0 > tau) and env crashes; pad if more than G/2 survive."""
    valid = [s for s in group if not s["env_fail"] and w_now - s["versions"][0] <= tau]
    if 2 * len(valid) <= G:
        return []                                    # drop the whole group
    out = list(valid)
    while len(out) < G:                              # pad by repeating valid samples
        out.append(valid[len(out) % len(valid)])
    return out


group = [{"id": 0, "versions": [7, 8], "env_fail": False},
         {"id": 1, "versions": [4, 5, 6, 7, 8], "env_fail": False},   # long, very stale
         {"id": 2, "versions": [8], "env_fail": True},                # sandbox crashed
         {"id": 3, "versions": [6, 7], "env_fail": False}]
for tau in [1, 2, 4]:
    kept = filter_group(group, w_now=8, tau=tau, G=4)
    print(f"tau={tau}: ids used for training ->", [s["id"] for s in kept] or "group dropped")
 

The finite-difference check confirms that the token with a 2×+ engine mismatch contributes exactly zero gradient. In the async part, as the lag grows, more tokens fall outside [0.8,1.28][0.8, 1.28]. The filter shows the coupling the report leaves implicit: with τ=2\tau=2 the long trajectory that started at version 4 is dropped, which leaves only two of four samples and therefore drops the whole group — long-horizon trajectories are exactly the ones most at risk. (Combining the staleness rule with the group-padding rule in one function is our choice; the report describes them separately.)

2. The asynchronous loop

NumPy IcePop 손실, double-sided IS, staleness·그룹 필터
import numpy as np

rng = np.random.default_rng(0)
G, T = 4, 6                                         # 응답 4개, 각 6토큰 (장난감)
R = np.array([1.0, 0.0, 1.0, 0.0])                  # 결과 보상
A = (R - R.mean()) / (R.std() + 1e-6)               # GRPO advantage, 응답의 모든 토큰이 공유
A_tok = np.repeat(A[:, None], T, axis=1)

logp_infer = np.log(rng.uniform(0.05, 0.9, (G, T)))          # log π_old^infer (rollout 엔진)
logp_train_old = logp_infer + rng.normal(0, 0.15, (G, T))    # log π_old^train (같은 θ_old, 다른 kernel)
logp_train_old[1, 2] += 1.2                                  # 학습–추론 불일치가 큰 토큰 하나
logp_new = logp_train_old + rng.normal(0, 0.1, (G, T))       # 몇 번 갱신된 log π_θ


def icepop_loss(logp_new, beta=2.0, eps_low=0.2, eps_high=0.28):
    """GLM-5 식 (1): pop(ρ) · min(r Â, clip(r) Â), 시퀀스 평균 후 그룹 평균, KL 없음."""
    rho = np.exp(logp_train_old - logp_infer)                    # 학습–추론 불일치 (상수)
    pop = np.where((rho >= 1 / beta) & (rho <= beta), rho, 0.0)
    r = np.exp(logp_new - logp_train_old)                        # PPO ratio
    surr = np.minimum(r * A_tok, np.clip(r, 1 - eps_low, 1 + eps_high) * A_tok)
    return -(pop * surr).mean(axis=1).mean(), pop


def double_sided_loss(logp_new, logp_rollout, eps_l=0.2, eps_h=0.28):
    """GLM-5 식 (3)–(5): f(r) Â log π_θ, r = π_θ / π_rollout. f는 상수 가중치로 쓴다."""
    r = np.exp(logp_new - logp_rollout)
    f = np.where((r > 1 - eps_l) & (r < 1 + eps_h), r, 0.0)
    return -(f * A_tok * logp_new).mean(), f


L1, pop = icepop_loss(logp_new)
print("IcePop 손실 %.4f | pop이 0으로 만든 토큰: %d / %d" % (L1, (pop == 0).sum(), pop.size))
print("  위치:", [(int(i), int(t)) for i, t in zip(*np.where(pop == 0))])

# log π_θ에 대한 gradient 수치 확인: mask된 토큰은 정확히 0
eps = 1e-6
g = np.zeros_like(logp_new)
for i in range(G):
    for t in range(T):
        d = np.zeros_like(logp_new); d[i, t] = eps
        g[i, t] = (icepop_loss(logp_new + d)[0] - icepop_loss(logp_new - d)[0]) / (2 * eps)
print("  불일치 토큰의 dL/dlogp:", round(g[1, 2], 6), "| 나머지 최대 |dL|:", round(np.abs(g).max(), 4))

# 비동기: rollout log-prob이 `lag` 버전 낡은 정책에서 나왔다
for lag in [0, 2, 6]:
    logp_rollout = logp_new - rng.normal(0, 0.06 * np.sqrt(lag) + 0.05, (G, T))
    L2, f = double_sided_loss(logp_new, logp_rollout)
    print(f"double-sided IS, lag={lag}: mask된 토큰 {(f == 0).mean():.0%}, 손실 {L2:.4f}")


def filter_group(group, w_now, tau, G):
    """§4.1.2: 낡은 샘플(w' - w0 > tau)과 환경 crash 제거, G/2 초과로 남으면 padding."""
    valid = [s for s in group if not s["env_fail"] and w_now - s["versions"][0] <= tau]
    if 2 * len(valid) <= G:
        return []                                    # 그룹 전체 폐기
    out = list(valid)
    while len(out) < G:                              # 유효 샘플을 반복해 채움
        out.append(valid[len(out) % len(valid)])
    return out


group = [{"id": 0, "versions": [7, 8], "env_fail": False},
         {"id": 1, "versions": [4, 5, 6, 7, 8], "env_fail": False},   # 길고 매우 낡음
         {"id": 2, "versions": [8], "env_fail": True},                # sandbox crash
         {"id": 3, "versions": [6, 7], "env_fail": False}]
for tau in [1, 2, 4]:
    kept = filter_group(group, w_now=8, tau=tau, G=4)
    print(f"tau={tau}: 학습에 쓰는 id ->", [s["id"] for s in kept] or "그룹 폐기")
 

수치 미분 확인이 엔진 불일치가 2배를 넘는 토큰의 gradient가 정확히 0임을 보여 준다. 비동기 부분에서는 지연이 커질수록 [0.8,1.28][0.8, 1.28] 밖으로 나가는 토큰이 는다. 필터는 보고서가 드러내지 않은 연결을 보여 준다. τ=2\tau=2이면 버전 4에서 시작한 긴 궤적이 버려지고, 그러면 네 개 중 두 개만 남아 그룹 전체가 버려진다. 긴 궤적일수록 가장 위험하다. (staleness 규칙과 그룹 padding 규칙을 한 함수로 합친 것은 이 레슨의 선택이고, 보고서는 둘을 따로 설명한다.)

2. 비동기 루프

학습에 쓰인 샘플samples trained on – 낡아서 버림dropped as stale – 환경 crashenv crashes – 그룹 padding / 폐기groups padded / dropped – 학습 샘플 평균 stalenessmean staleness (kept) –
각 행은 rollout slot 하나, 가로축은 시간이다. 막대 하나가 궤적 하나이고, 같은 프롬프트의 궤적 G=4개가 그룹을 이룬다. 맨 위 줄은 trainer다(보라 = 학습 step, 세로 눈금 = 추론 엔진에 weight push → 버전 +1). 막대 색은 학습에 쓰일 때의 staleness w′ − w0(파랑 0, 청록 1, 주황 2, 빨강 3 이상), 빗금은 τ를 넘어 버려진 궤적, 회색 ×는 환경 crash로 빠진 궤적이다. 막대 안의 세로선은 생성 도중 weight가 바뀐 지점이다. τ를 0으로 내리면 긴 궤적 대부분이 버려져 긴 과제를 거의 배우지 못하고, τ를 키우면 다 쓰지만 off-policy가 심해진다. K를 키우면 push가 드물어 staleness는 줄지만 rollout이 낡은 정책으로 오래 돈다. crash 비율을 올리면 G/2 이하만 남은 그룹이 통째로 버려진다. 시간 단위와 분포는 가상이며 규칙만 보고서를 따른다. Each row is a rollout slot; the x-axis is time. A bar is one trajectory, and G=4 trajectories of the same prompt form a group. The top row is the trainer (violet = training step, tick = weight push to the inference engine → version +1). Bar colour is the staleness w′ − w0 when it is consumed (blue 0, teal 1, amber 2, red 3+); hatched bars were dropped for exceeding τ, grey × bars were removed as environment crashes. Thin vertical lines inside a bar mark weight changes during generation. Set τ to 0 and most long trajectories are discarded, so long tasks are barely learned; raise τ and everything is used but more off-policy. A larger K pushes less often (less staleness, but rollouts run on an old policy for longer). A higher crash rate makes whole groups with ≤ G/2 valid samples disappear. Time units and distributions are made up; only the rules follow the report.

The rules in §4.1.1–4.1.2 are: rollout engines generate continuously on their own GPUs; when the number of finished trajectories reaches a threshold, a batch goes to the trainer; the trainer pushes new weights every KK gradient updates; and — a detail easy to miss — the optimizer is reset after each weight update of the inference engine, because the rollout policy defines a slightly different optimisation problem after every push. Each trajectory carries the sequence of versions it was generated with, (w0,…,wk)(w_0,\dots,w_k), and is dropped if w′−w0>τw'-w_0>\tau. Trajectories are standardised into a unified message-list format; a token-in-token-out (TITO) gateway records the exact token IDs the engine produced, because re-tokenising text can shift boundaries, whitespace or special tokens and corrupt the alignment between actions and advantages. Finally, DP-aware routing hashes each rollout ID to a fixed data-parallel rank so every turn of an agent hits the same KV cache, and prefill cost grows only with the new tokens.

3. On-policy cross-stage distillation in a toy

A shared-parameter policy is trained with RL on a “reasoning” prompt type, then on a “general” type whose features overlap; the second stage overwrites the first. Distilling from both stage checkpoints with the Eq. (2) advantage (group size 1) recovers both.

NumPy Sequential RL forgets; on-policy cross-stage distillation recovers
import numpy as np

V = 6                                                  # candidate answers
X = {"reasoning": np.array([1.0, 0.0, 0.0]),           # features: [shared, general flag, unused]
     "general":   np.array([1.0, 1.0, 0.0])}
GOOD = {"reasoning": 0, "general": 1}                  # the answer each domain rewards


def probs(W, x):
    z = W @ x
    e = np.exp(z - z.max())
    return e / e.sum()


def acc(W):
    return {d: round(float(probs(W, x)[GOOD[d]]), 3) for d, x in X.items()}


def rl(W, dom, steps, rng, lr=0.5, G=8):
    """group-mean-baseline policy gradient on one domain"""
    for _ in range(steps):
        x = X[dom]; p = probs(W, x)
        y = rng.choice(V, size=G, p=p)
        A = (y == GOOD[dom]).astype(float); A -= A.mean()
        g = np.zeros_like(W)
        for yi, ai in zip(y, A):
            gl = -p.copy(); gl[yi] += 1                # d log π(y) / d logits
            g += ai * np.outer(gl, x)
        W = W + lr * g / G
    return W


def opd(W, teachers, steps, rng, lr=0.5, B=16):
    """GLM-5 Eq. (2): advantage = sg[log π_teacher(y) - log π_θ(y)], y ~ π_θ, group size 1."""
    doms = list(teachers)
    for _ in range(steps):
        g = np.zeros_like(W)
        for b in range(B):
            d = doms[b % len(doms)]; x = X[d]; p = probs(W, x)
            y = rng.choice(V, p=p)
            A = np.log(probs(teachers[d], x)[y]) - np.log(p[y])
            gl = -p.copy(); gl[y] += 1
            g += A * np.outer(gl, x)
        W = W + lr * g / B
    return W


def rev_kl(W, T, x):
    p, q = probs(W, x), probs(T, x)
    return float((p * np.log(p / q)).sum())


rng = np.random.default_rng(0)
W0 = rng.normal(0, 0.3, (V, 3))
print("after SFT          ", acc(W0))
W_reason = rl(W0, "reasoning", 40, rng)
print("after reasoning RL ", acc(W_reason))
W_general = rl(W_reason, "general", 150, rng, lr=1.0, G=16)
print("after general RL   ", acc(W_general), "<- reasoning skill forgotten")
teachers = {"reasoning": W_reason, "general": W_general}
W_final = opd(W_general, teachers, 200, rng)
print("after cross-stage OPD", acc(W_final))
for d in X:
    print(f"  reverse KL to the {d} teacher: {rev_kl(W_general, teachers[d], X[d]):.3f} -> {rev_kl(W_final, teachers[d], X[d]):.3f}")
 

The general RL stage pushes up the logit of answer 1 through the shared feature, which also changes the reasoning prompts’ answer; the reasoning skill collapses. Distillation pulls each prompt type towards its own teacher; since the parameters can represent both, the reverse KL to the reasoning teacher drops from 2.6 to about 0.01 while the one to the general teacher stays near 0. Note what the student can never do in this scheme: exceed its teachers on their domains. OPD consolidates; it does not improve.

§4.1.1–4.1.2의 규칙은 이렇다. rollout 엔진은 자기 GPU에서 쉬지 않고 생성한다. 끝난 궤적 수가 임계값에 이르면 batch가 trainer로 간다. trainer는 gradient 갱신 KK번마다 새 가중치를 push한다. 그리고 놓치기 쉬운 세부로, push마다 rollout 정책이 정의하는 최적화 문제가 조금씩 달라지므로 추론 엔진의 가중치를 갱신할 때마다 optimizer를 reset한다. 궤적마다 생성에 쓰인 버전 열 (w0,…,wk)(w_0,\dots,w_k)를 기록하고, w′−w0>τw'-w_0>\tau이면 버린다. 궤적은 통일된 message-list 형식으로 표준화되고, token-in-token-out(TITO) gateway가 엔진이 낸 정확한 token ID를 기록한다. 텍스트를 다시 tokenize하면 경계·공백·특수 토큰이 어긋나 행동과 advantage의 정렬이 깨질 수 있기 때문이다. 마지막으로 DP-aware routing이 rollout ID를 consistent hashing으로 고정된 data-parallel rank에 묶어 agent의 모든 turn이 같은 KV cache를 쓰게 하므로, prefill 비용이 새 토큰에만 비례한다.

3. 장난감으로 보는 on-policy cross-stage distillation

파라미터를 공유하는 정책을 “reasoning” 프롬프트로 RL한 뒤 특징이 겹치는 “general” 프롬프트로 RL하면 두 번째 단계가 첫 번째를 덮어쓴다. 두 단계의 체크포인트에서 식 (2)의 advantage(group 크기 1)로 증류하면 둘 다 돌아온다.

NumPy 단계별 RL은 잊고, on-policy cross-stage distillation은 되찾는다
import numpy as np

V = 6                                                  # 후보 답
X = {"reasoning": np.array([1.0, 0.0, 0.0]),           # 특징: [공유, general 표시, 미사용]
     "general":   np.array([1.0, 1.0, 0.0])}
GOOD = {"reasoning": 0, "general": 1}                  # 도메인별 정답


def probs(W, x):
    z = W @ x
    e = np.exp(z - z.max())
    return e / e.sum()


def acc(W):
    return {d: round(float(probs(W, x)[GOOD[d]]), 3) for d, x in X.items()}


def rl(W, dom, steps, rng, lr=0.5, G=8):
    """한 도메인에서 그룹 평균 baseline 정책 경사"""
    for _ in range(steps):
        x = X[dom]; p = probs(W, x)
        y = rng.choice(V, size=G, p=p)
        A = (y == GOOD[dom]).astype(float); A -= A.mean()
        g = np.zeros_like(W)
        for yi, ai in zip(y, A):
            gl = -p.copy(); gl[yi] += 1                # d log π(y) / d logits
            g += ai * np.outer(gl, x)
        W = W + lr * g / G
    return W


def opd(W, teachers, steps, rng, lr=0.5, B=16):
    """GLM-5 식 (2): advantage = sg[log π_teacher(y) - log π_θ(y)], y ~ π_θ, group 크기 1."""
    doms = list(teachers)
    for _ in range(steps):
        g = np.zeros_like(W)
        for b in range(B):
            d = doms[b % len(doms)]; x = X[d]; p = probs(W, x)
            y = rng.choice(V, p=p)
            A = np.log(probs(teachers[d], x)[y]) - np.log(p[y])
            gl = -p.copy(); gl[y] += 1
            g += A * np.outer(gl, x)
        W = W + lr * g / B
    return W


def rev_kl(W, T, x):
    p, q = probs(W, x), probs(T, x)
    return float((p * np.log(p / q)).sum())


rng = np.random.default_rng(0)
W0 = rng.normal(0, 0.3, (V, 3))
print("SFT 후           ", acc(W0))
W_reason = rl(W0, "reasoning", 40, rng)
print("reasoning RL 후  ", acc(W_reason))
W_general = rl(W_reason, "general", 150, rng, lr=1.0, G=16)
print("general RL 후    ", acc(W_general), "<- reasoning 능력 망각")
teachers = {"reasoning": W_reason, "general": W_general}
W_final = opd(W_general, teachers, 200, rng)
print("교차 단계 OPD 후 ", acc(W_final))
for d in X:
    print(f"  {d} teacher까지 reverse KL: {rev_kl(W_general, teachers[d], X[d]):.3f} -> {rev_kl(W_final, teachers[d], X[d]):.3f}")
 

general RL 단계는 공유 특징을 통해 답 1의 logit을 올리고, 그것이 reasoning 프롬프트의 답까지 바꿔 reasoning 능력이 무너진다. 증류는 프롬프트 종류마다 자기 teacher 쪽으로 끌어당긴다. 파라미터가 둘을 함께 표현할 수 있으므로 reasoning teacher까지의 reverse KL은 2.6에서 0.01 정도로 떨어지고, general teacher까지는 0 근처에 머문다. 이 방식에서 학생이 결코 할 수 없는 일도 보인다. 자기 teacher를 그 도메인에서 넘어서는 것이다. OPD는 굳히는 단계이지 끌어올리는 단계가 아니다.

PyTorch PyTorch: GLM-5 RL losses (IcePop, double-sided IS, cross-stage OPD) 로컬에서 실행run locally (pip install torch)
import torch

def glm5_icepop_loss(logp, old_logp_train, old_logp_infer, rewards, mask, G,
                     beta=2.0, eps_low=0.2, eps_high=0.28):
    """Eq. (1). logp, old_logp_*: (N, T); rewards: (N,); mask: (N, T) generated tokens. N = B*G."""
    r = rewards.view(-1, G)
    adv = ((r - r.mean(1, keepdim=True)) / (r.std(1, keepdim=True) + 1e-6)).view(-1, 1)
    rho = torch.exp(old_logp_train - old_logp_infer)              # no grad: both are constants
    pop = torch.where((rho >= 1 / beta) & (rho <= beta), rho, torch.zeros_like(rho))
    ratio = torch.exp(logp - old_logp_train)
    surr = torch.minimum(ratio * adv, ratio.clamp(1 - eps_low, 1 + eps_high) * adv)
    m = mask.float()
    per_seq = (pop * surr * m).sum(1) / m.sum(1).clamp(min=1)   # 1/|y_i| Σ_t
    return -per_seq.mean()                                       # 1/G Σ_i (and over prompts)

def glm5_async_loss(logp, rollout_logp, adv_tok, mask, eps_l=0.2, eps_h=0.28):
    """Eqs. (3)-(5): r = π_θ / π_rollout (rollout log-probs reused; no π_old).
    f(r) = r inside (1-eps_l, 1+eps_h), else 0, used as a detached weight on log π_θ.
    The report does not give eps_l / eps_h for this stage; defaults are placeholders."""
    r = torch.exp(logp.detach() - rollout_logp)
    f = torch.where((r > 1 - eps_l) & (r < 1 + eps_h), r, torch.zeros_like(r))
    m = mask.float()
    return -(f * adv_tok * logp * m).sum() / m.sum().clamp(min=1)

def cross_stage_opd_advantage(teacher_logp_infer, student_logp_train):
    """Eq. (2): Â_t = sg[log π_teacher(y_t) - log π_θ(y_t)] on tokens sampled from the student."""
    return (teacher_logp_infer - student_logp_train).detach()
    # plug into glm5_icepop_loss in place of the group advantage, with G = 1

def keep_sample(versions, w_now, tau):
    """Drop a trajectory whose oldest rollout version is more than tau behind."""
    return (w_now - versions[0]) <= tau
 
PyTorch PyTorch: GLM-5 RL 손실 (IcePop, double-sided IS, 교차 단계 OPD) 로컬에서 실행run locally (pip install torch)
import torch

def glm5_icepop_loss(logp, old_logp_train, old_logp_infer, rewards, mask, G,
                     beta=2.0, eps_low=0.2, eps_high=0.28):
    """식 (1). logp, old_logp_*: (N, T); rewards: (N,); mask: (N, T) 생성 토큰. N = B*G."""
    r = rewards.view(-1, G)
    adv = ((r - r.mean(1, keepdim=True)) / (r.std(1, keepdim=True) + 1e-6)).view(-1, 1)
    rho = torch.exp(old_logp_train - old_logp_infer)              # grad 없음: 둘 다 상수
    pop = torch.where((rho >= 1 / beta) & (rho <= beta), rho, torch.zeros_like(rho))
    ratio = torch.exp(logp - old_logp_train)
    surr = torch.minimum(ratio * adv, ratio.clamp(1 - eps_low, 1 + eps_high) * adv)
    m = mask.float()
    per_seq = (pop * surr * m).sum(1) / m.sum(1).clamp(min=1)   # 1/|y_i| Σ_t
    return -per_seq.mean()                                       # 1/G Σ_i (프롬프트 평균 포함)

def glm5_async_loss(logp, rollout_logp, adv_tok, mask, eps_l=0.2, eps_h=0.28):
    """식 (3)-(5): r = π_θ / π_rollout (rollout log-prob 재사용, π_old 없음).
    f(r) = (1-eps_l, 1+eps_h) 안이면 r, 밖이면 0. log π_θ에 곱하는 상수(detach) 가중치로 쓴다.
    보고서는 이 단계의 eps_l / eps_h를 밝히지 않는다. 기본값은 자리표시자."""
    r = torch.exp(logp.detach() - rollout_logp)
    f = torch.where((r > 1 - eps_l) & (r < 1 + eps_h), r, torch.zeros_like(r))
    m = mask.float()
    return -(f * adv_tok * logp * m).sum() / m.sum().clamp(min=1)

def cross_stage_opd_advantage(teacher_logp_infer, student_logp_train):
    """식 (2): 학생이 뽑은 토큰에서 Â_t = sg[log π_teacher(y_t) - log π_θ(y_t)]."""
    return (teacher_logp_infer - student_logp_train).detach()
    # glm5_icepop_loss의 그룹 advantage 자리에 넣고 G = 1로 쓴다

def keep_sample(versions, w_now, tau):
    """가장 오래된 rollout 버전이 tau보다 많이 뒤처진 궤적은 버린다."""
    return (w_now - versions[0]) <= tau
 
확인 문제Check yourself

In GLM-5's asynchronous agentic RL, why is the importance ratio computed against the rollout log-probs instead of a separately evaluated π_old?

Rollout engines receive new weights every KK updates, possibly in the middle of a trajectory, so different tokens of the same trajectory were sampled by different policies πθold(1),…,πθold(N)\pi_{\theta^{(1)}_{\text{old}}},\dots,\pi_{\theta^{(N)}_{\text{old}}}. Recomputing each would require keeping all those checkpoints. The rollout log-probs are exactly the behaviour probabilities that produced each token, so using them as the denominator sidesteps the problem at the cost of a “controlled degree of off-policy bias” (the ratio now also carries engine mismatch), which the tight two-sided mask contains.

확인 문제Check yourself

GLM-5의 비동기 agentic RL에서 importance ratio를 따로 계산한 π_old 대신 rollout log-prob 기준으로 구하는 이유는?

rollout 엔진은 갱신 KK번마다, 궤적 생성 도중에도 새 가중치를 받는다. 그래서 같은 궤적의 토큰들이 서로 다른 정책 πθold(1),…,πθold(N)\pi_{\theta^{(1)}_{\text{old}}},\dots,\pi_{\theta^{(N)}_{\text{old}}}에서 뽑혔다. 각각을 다시 계산하려면 그 체크포인트를 모두 보관해야 한다. rollout log-prob은 각 토큰을 실제로 만든 행동 확률 그 자체이므로 분모로 쓰면 이 문제를 피한다. 대가는 “통제된 수준의 off-policy 편향”(비율이 엔진 불일치까지 함께 담는다)이고, 좁은 양쪽 mask가 그것을 묶는다.

Results

ARC benchmarks (Table 7)

실험 결과

ARC 벤치마크 (Table 7)

출처Source: GLM-5 report Table 7
분야와 벤치마크를 바꿔 보면 같은 모델이라도 어디서 앞서고 어디서 뒤지는지가 바로 보인다. 색 막대가 GLM, 회색이 비교 모델이다. 값은 보고서 표를 그대로 옮겼고, 빈 값(–)은 보고서에 없는 것이다. Switch the area and benchmark to see where the same model leads and where it trails. Coloured bars are GLM models, grey bars the comparison models. Values are copied from the report's tables; a dash (–) means the report gives no number.
  • GLM-5 leads the open models on most coding and agentic rows and is close to Claude Opus 4.5 on SWE-bench Verified (77.8 vs 80.9) and Terminal-Bench 2.0 (56.2 vs 59.3; 60.7 on the team’s verified version of the benchmark).
  • BrowseComp is its strongest showing: 62.0 without and 75.9 with context management, the best in the table.
  • On HLE without tools, GPQA-Diamond and IMO-AnswerBench it trails Gemini 3 Pro and GPT-5.2 (xhigh); on AIME 2026 I it is level with everyone (≈92–93).
  • The HLE “w/ Tools” values marked * for proprietary models are on the full set, GLM-5’s on the text subset; Terminal-Bench ”†” numbers use a modified benchmark. Read those cells with care.

Base model (Table 11, excerpt). GLM-5-Base vs GLM-4.5-Base: MMLU 88.3 vs 86.1, SimpleQA 36.0 vs 30.0, EvalPlus 87.0 vs 78.1, LiveCodeBench-Base 34.4 vs 28.1 — but GSM8K 68.8 vs 79.4 and MATH 56.4 vs 61.0, lower than its predecessor. The report does not comment on the drop.

Real-world agentic engineering (Table 8, CC-Bench-V2, fully automated).

TaskMetricGLM-5GLM-4.7Claude Opus 4.5
Frontend HTML / React / VueISR38.9 / 34.6 / 32.735.4 / 17.2 / 24.552.2 / 39.7 / 46.9
Frontend HTML / React / VueCSR76.3 / 71.0 / 77.164.9 / 49.4 / 53.882.2 / 70.7 / 74.3
Backend (85 tasks, 6 languages)Pass@125.819.626.9
Large-repo explorationPass@165.647.864.5
Multi-step chained tasksPass@152.343.061.6

Frontend is judged by an Agent-as-a-Judge (Claude Code with Claude Sonnet 4.5 and Playwright) that agrees with human experts on 94% of 130 sampled check-items and ranks 8 models with a Spearman correlation of 85.7%. The pattern is honest and informative: GLM-5 meets most individual requirements (CSR close to or above Opus 4.5) but completes whole tasks less often (ISR), and the gap is largest on chained tasks, where an early mistake silently breaks later steps.

Fresh tasks (Table 9, SWE-rebench, January 2026). GLM-5 resolves 42.1% (pass@5 50.0%), behind Claude Opus 4.6 (52.9%), GPT-5.2 xhigh (51.7%), Claude Sonnet 4.5, Gemini 3 Pro and Claude Opus 4.5 (43.8%), and essentially level with GLM-4.7 (41.3%). The jump from 73.8 to 77.8 on SWE-bench Verified does not show up on newly mined issues — a useful caution about static benchmarks.

Context management for search agents

The report finds BrowseComp accuracy sensitive to the judge (it standardises on the official prompt with o3-mini) and accuracy degrading beyond about 100K tokens of context. Two inference-time strategies follow.

  • GLM-5는 코딩·agentic 행 대부분에서 공개 모델 중 앞서고, SWE-bench Verified(77.8 vs 80.9)와 Terminal-Bench 2.0(56.2 vs 59.3, 팀이 고친 verified 버전에서는 60.7)에서 Claude Opus 4.5에 가깝다.
  • BrowseComp가 가장 강한 항목이다. context 관리 없이 62.0, 있으면 75.9로 표에서 최고다.
  • 도구 없는 HLE, GPQA-Diamond, IMO-AnswerBench에서는 Gemini 3 Pro·GPT-5.2(xhigh)에 뒤진다. AIME 2026 I은 모두 비슷하다(≈92–93).
  • 독점 모델의 HLE “w/ Tools” 값 중 *표시는 전체 셋, GLM-5는 텍스트 부분집합이다. Terminal-Bench의 ”†” 수치는 수정된 벤치마크다. 그 칸들은 조심해서 읽어야 한다.

Base 모델 (Table 11 일부). GLM-5-Base vs GLM-4.5-Base: MMLU 88.3 vs 86.1, SimpleQA 36.0 vs 30.0, EvalPlus 87.0 vs 78.1, LiveCodeBench-Base 34.4 vs 28.1. 그런데 GSM8K 68.8 vs 79.4, MATH 56.4 vs 61.0으로 전작보다 낮다. 보고서는 이 하락을 설명하지 않는다.

실제 agentic engineering (Table 8, CC-Bench-V2, 완전 자동).

과제지표GLM-5GLM-4.7Claude Opus 4.5
Frontend HTML / React / VueISR38.9 / 34.6 / 32.735.4 / 17.2 / 24.552.2 / 39.7 / 46.9
Frontend HTML / React / VueCSR76.3 / 71.0 / 77.164.9 / 49.4 / 53.882.2 / 70.7 / 74.3
Backend (85과제, 6개 언어)Pass@125.819.626.9
대형 repo 탐색Pass@165.647.864.5
다단계 연쇄 과제Pass@152.343.061.6

frontend는 Agent-as-a-Judge(Claude Sonnet 4.5를 쓴 Claude Code + Playwright)가 채점하는데, 표본 130개 check-item에서 사람 전문가와 94% 일치하고 8개 모델 순위의 Spearman 상관이 85.7%다. 결과의 모양이 솔직하고 유익하다. GLM-5는 개별 요구사항은 대부분 맞추지만(CSR이 Opus 4.5에 근접하거나 위) 과제 전체를 끝내는 비율(ISR)은 낮고, 격차는 앞 단계의 실수가 뒤 단계를 조용히 깨뜨리는 연쇄 과제에서 가장 크다.

새 과제 (Table 9, SWE-rebench, 2026년 1월). GLM-5는 42.1%(pass@5 50.0%)로 Claude Opus 4.6(52.9%), GPT-5.2 xhigh(51.7%), Claude Sonnet 4.5, Gemini 3 Pro, Claude Opus 4.5(43.8%)에 뒤지고 GLM-4.7(41.3%)과 사실상 같다. SWE-bench Verified의 73.8 → 77.8 상승이 새로 채굴한 issue에서는 보이지 않는다. 정적 벤치마크에 대한 좋은 경고다.

검색 agent의 context 관리

보고서는 BrowseComp 정확도가 judge에 민감하고(공식 프롬프트 + o3-mini로 표준화), 문맥이 약 100K 토큰을 넘으면 정확도가 떨어진다는 것을 발견했다. 그래서 추론 시 전략 두 가지가 나온다.

128K 한도에 닿는 round (관리 없음)round that hits 128K (no management) – keep-recent 최대 길이keep-recent peak length – discard 횟수: discard-all / HCMresets: discard-all / HCM –
검색 agent 궤적 (q, r1, a1, o1, …)의 round별 문맥 길이다(r 추론, a 행동, o tool 결과; 토큰 수는 가상). keep-recent-k는 최근 k round보다 오래된 oi만 "Tool result is omitted to save tokens."로 접는다. discard-all은 길이가 T를 넘으면 tool 호출 기록 전체를 지우고 새로 시작한다. HCM은 keep-recent를 계속 쓰다가 그래도 T를 넘을 때만 discard-all을 한다. k와 T를 바꿔 보면 keep-recent만으로는 길이가 천천히 계속 자라고, discard-all만으로는 자주 리셋되어 쌓은 추론까지 잃으며, HCM은 리셋 횟수를 줄이면서 길이를 묶는다는 것이 보인다. 보고서: keep-recent(k=5)로 BrowseComp 55.3% → 62.0%, HCM(T=32K)으로 75.9%. Context length per round of a search-agent trajectory (q, r1, a1, o1, …) — r reasoning, a action, o tool observation; token counts are made up. keep-recent-k folds only the observations older than the last k rounds into "Tool result is omitted to save tokens.". discard-all wipes the whole tool-call history and restarts once the length exceeds T. HCM keeps applying keep-recent and discards only when the length still exceeds T. Vary k and T: keep-recent alone still grows slowly, discard-all alone resets often and throws away the accumulated reasoning, and HCM bounds the length with far fewer resets. Report: keep-recent (k=5) lifts BrowseComp from 55.3% to 62.0%; HCM (T=32K) reaches 75.9%.

Keep-recent-k folds only observations older than the last kk rounds; with k=5k=5 BrowseComp goes from 55.3% to 62.0%. Hierarchical Context Management (HCM) adds discard-all on top: if the context still exceeds T=32KT=32\text{K}, the whole tool history is dropped and the agent restarts while keeping keep-recent. With a growing step budget this reaches 75.9, above every open model with context management in the report (Fig. 8). Neither strategy is trained for specifically, as far as the report says; both are inference policies, which also means they interact with how the model was trained to use (preserved) thinking.

Other results

  • Slide generation RL with a three-level reward (static HTML attributes, runtime rendering geometry, visual perception), after fixing renderer loopholes that the policy exploited (truncating overflowing content, squeezing spacing): strict 16:9 compliance rises from 40% to 92%, and humans prefer GLM-5 over GLM-4.5 67.5% of the time overall.
  • Chinese accelerators: W4A8 mixed quantization (INT4 experts, INT8 attention/MLP) to fit the model on one Atlas 800T A3 machine; fused Lightning Indexer and Sparse Flash Attention kernels; the report claims a single domestic node matches “dual-GPU international clusters” and halves long-sequence deployment cost — a claim without a table.

After GLM-5: GLM-5.1 to 5.3

There is no separate technical report for the later models; the README of the GLM-5 repository describes them and still cites this report. As of December 2026:

  • GLM-5.1: same 744B-A40B size; post-training aimed at long-horizon agentic engineering (“sustains optimization over hundreds of rounds and thousands of tool calls”).
  • GLM-5.2: a “solid 1M-token context”; IndexShare — one indexer reused across every four sparse-attention layers, reducing per-token FLOPs by 2.9× at 1M context — and an improved MTP layer with up to 20% longer accept length; reasoning effort high/max.
  • GLM-5.3: “uses the same base model as GLM-5.2 — every gain comes from post-training”; strongest on coding and cyber; reasoning_effort low/high/max, and clear_thinking defaults to false (thinking is preserved).
  • GLM-5.3-Flash (320B-A18B): a newly trained base with the series’ first hybrid of sparse and linear attention and Manifold-Constrained Hyper-Connections, trained on a 30T-token multimodal corpus.

IndexShare is described in the Z.ai paper IndexCache (arXiv 2603.12201). The indexer itself is still O(L2)O(L^2) at every layer; IndexCache keeps indexers only in a few “Full” layers and lets “Shared” layers reuse the nearest Full layer’s top-kk, choosing which layers keep indexers by greedy search on LM loss (training-free) or training each kept indexer against the averaged attention of the layers it serves. On a 30B DSA model (from GLM-4.7-Flash):

(IndexCache Tables 1–2)Long avgG&R avgprefill 200Kdecode 200K
DSA50.274.619.5 s58 tok/s
1/4 indexers, uniform interleave43.073.8––
1/4 indexers, searched pattern49.974.910.7 s86 tok/s

The paper reports at least 1.3× prefill and decode speed-up for GLM-5 beyond 100K context. The lesson echoes the SWA ablation above: which layers keep the expensive component matters far more than how many.

Reading critically

  • Ablations are scattered across models. MLA/Muon Split (Table 1) on an unspecified smaller model; efficient-attention ablation on GLM-9B; DSA confirmation on GLM-4.7-Flash; none on GLM-5 itself except Table 3.
  • Asynchronous RL hyper-parameters are missing. εℓ\varepsilon_\ell, εh\varepsilon_h, τ\tau, KK, the trajectory threshold, and the share of data dropped by each filter are not given; nor is any ablation of double-sided IS versus IcePop or PPO in the async setting (“more stable” is asserted, not plotted).
  • No measurement of the distillation stage. On-policy cross-stage distillation is the last step before release, but there is no before/after table showing what it recovered.
  • Benchmark settings vary. OpenHands with a “tailored instruction prompt” for SWE-bench; Terminal-Bench on a verified variant made by the team; τ²-Bench with prompt adjustments and the airline fixes from Anthropic’s system card; MCP-Atlas re-run with a 10-minute timeout; BrowseComp scores depend on judge and context management. These choices are disclosed, which is good, but they make cross-report comparison fragile.
  • Fresh-task evidence is sobering. On SWE-rebench GLM-5 is level with GLM-4.7; on CC-Bench-V2 chained tasks it trails Opus 4.5 by 9 points. The headline gains are concentrated in static, public benchmarks.
  • Base-model maths regressed (GSM8K, MATH) without comment, and the base-model evaluation framework is internal.
  • Unexplained inconsistencies: 80 layers in the text vs 79 in Table 10; a 41-character layer pattern for a 40-layer model; MLA-256 described as “head dim 192 → 256, heads −1/3” vs Table 10’s 64 heads with QK 192 / V 256.
확인 문제Check yourself

On-policy cross-stage distillation uses group size 1. Why can it drop the group of 32 used in reasoning RL?

In GRPO the group exists to estimate a baseline: the advantage of a response is its reward minus the mean reward of other responses to the same prompt. In Eq. (2) every token already has its own signal, log⁡πteacher(yt)−log⁡πθ(yt)\log\pi_{\text{teacher}}(y_t)-\log\pi_\theta(y_t): positive where the teacher likes the sampled token more than the student does, negative where less. Its expectation under the student is minus the reverse KL, so one sample per prompt gives an unbiased (if noisy) gradient, and more prompts per batch (1024) buy more diversity than more samples per prompt would.

Summary

  • GLM-5 is a 744B/40B MoE (256 experts, 79–80 layers) with MLA made competitive by Muon Split, cheaper to decode with fewer, larger heads (MLA-256), shared-parameter MTP, and DSA added after mid-training with only 20B tokens of sparse adaptation.
  • The base is trained on 28.5T tokens, with mid-training at 32K / 128K / 200K focused on repo-level code (≈10M issue–PR pairs) and long-context / agent data.
  • Reasoning RL is GRPO + IcePop without KL (β=2, ε 0.2/0.28, group 32); DSA RL needs a deterministic top-k and a frozen indexer.
  • Agentic RL is fully asynchronous: TITO, rollout log-probs as the behaviour policy with a double-sided mask, staleness filtering, crash-aware group padding, optimizer reset at each push, DP-aware routing.
  • On-policy cross-stage distillation (advantage = teacher/student log-ratio, group 1) consolidates the stages. Results are near Claude Opus 4.5 on many static benchmarks, but fresh and chained tasks show a clear remaining gap. GLM-5.1–5.3 keep this report as their reference and extend it with IndexShare/IndexCache, 1M context and more post-training.

keep-recent-k는 최근 kk round보다 오래된 관찰만 접는다. k=5k=5로 BrowseComp가 55.3%에서 62.0%가 된다. Hierarchical Context Management(HCM) 는 그 위에 discard-all을 더한다. 그래도 문맥이 T=32KT=32\text{K}를 넘으면 tool 기록 전체를 지우고 keep-recent를 유지한 채 다시 시작한다. step 예산을 늘리면 75.9에 이르러, 보고서의 context 관리를 쓰는 모든 공개 모델보다 높다(Fig. 8). 보고서가 말하는 한 두 전략 모두 학습 대상이 아니라 추론 정책이고, 그래서 모델이 (preserved) thinking을 쓰도록 학습된 방식과 맞물린다.

그 밖의 결과

  • 슬라이드 생성 RL: 세 단계 보상(정적 HTML 속성, 실행 시 렌더링 기하, 시각 지각). 정책이 파고든 렌더러 허점(넘치는 내용 자르기, 간격 쥐어짜기)을 고친 뒤, 16:9 엄수 비율이 40%에서 92%로, 사람 평가에서 GLM-4.5 대비 전체 승률 67.5%.
  • 중국 가속기: Atlas 800T A3 한 대에 모델을 올리는 W4A8 혼합 양자화(expert는 INT4, attention·MLP는 INT8), Lightning Indexer·Sparse Flash Attention 융합 kernel. 국산 노드 하나가 “듀얼 GPU 해외 클러스터”와 맞먹고 긴 시퀀스 배포 비용을 절반으로 줄였다고 주장하지만 표는 없다.

GLM-5 이후: GLM-5.1에서 5.3까지

후속 모델에는 별도 기술 보고서가 없다. GLM-5 저장소의 README가 그것들을 설명하고 여전히 이 보고서를 인용한다. 2026년 12월 기준으로:

  • GLM-5.1: 같은 744B-A40B. 장기 agentic engineering을 겨냥한 사후학습(“수백 round, 수천 번의 tool 호출에 걸쳐 최적화를 지속”).
  • GLM-5.2: “견고한 1M 토큰 문맥”. IndexShare(sparse attention 4층마다 indexer 하나를 공유, 1M 문맥에서 토큰당 FLOPs 2.9배 감소)와 accept length가 최대 20% 긴 개선된 MTP 층. reasoning effort high/max.
  • GLM-5.3: “GLM-5.2와 같은 base 모델, 모든 향상은 사후학습에서”. 코딩과 사이버 보안에서 가장 강하다. reasoning_effort low/high/max, clear_thinking 기본값 false(thinking 보존).
  • GLM-5.3-Flash (320B-A18B): 새로 학습한 base. 시리즈 최초의 sparse + linear attention 하이브리드와 Manifold-Constrained Hyper-Connections, 30T 토큰 멀티모달 corpus.

IndexShare는 Z.ai의 논문 IndexCache(arXiv 2603.12201)에 설명되어 있다. indexer 자체는 층마다 여전히 O(L2)O(L^2)다. IndexCache는 소수의 “Full” 층에만 indexer를 두고 “Shared” 층은 가장 가까운 Full 층의 top-kk를 재사용하며, 어느 층에 indexer를 남길지를 LM 손실에 대한 greedy search(학습 없이)로 고르거나, 남긴 indexer를 그것이 맡는 층들의 평균 attention에 맞춰 학습한다. 30B DSA 모델(GLM-4.7-Flash 기반)에서:

(IndexCache Table 1–2)Long 평균G&R 평균prefill 200Kdecode 200K
DSA50.274.619.5 s58 tok/s
indexer 1/4, 균일 교대43.073.8––
indexer 1/4, 찾은 pattern49.974.910.7 s86 tok/s

논문은 GLM-5에서도 100K 넘는 문맥에서 prefill·decode가 최소 1.3배 빨라졌다고 보고한다. 위 SWA ablation과 같은 교훈이다. 비싼 구성요소를 어느 층에 남기느냐가 몇 층에 남기느냐보다 훨씬 중요하다.

비판적으로 읽기

  • ablation이 여러 모델에 흩어져 있다. MLA/Muon Split(Table 1)은 크기를 밝히지 않은 작은 모델, 효율 attention ablation은 GLM-9B, DSA 확인은 GLM-4.7-Flash다. GLM-5 자체의 ablation은 Table 3뿐이다.
  • 비동기 RL 하이퍼파라미터가 없다. εℓ\varepsilon_\ell, εh\varepsilon_h, τ\tau, KK, 궤적 임계값, 필터마다 버려진 데이터 비율이 없다. 비동기에서 double-sided IS를 IcePop이나 PPO와 비교한 ablation도 없다(“더 안정적”이라는 서술뿐).
  • 증류 단계의 측정이 없다. on-policy cross-stage distillation은 공개 직전의 마지막 단계인데, 무엇을 되찾았는지 보여 주는 전후 표가 없다.
  • 벤치마크 설정이 제각각이다. SWE-bench는 “맞춤 instruction 프롬프트”를 쓴 OpenHands, Terminal-Bench는 팀이 만든 verified 변형, τ²-Bench는 프롬프트 조정과 Anthropic system card의 airline 수정, MCP-Atlas는 10분 timeout으로 재측정, BrowseComp는 judge와 context 관리에 좌우된다. 공개한 것은 좋지만 보고서 간 비교는 그만큼 깨지기 쉽다.
  • 새 과제의 증거는 냉정하다. SWE-rebench에서 GLM-5는 GLM-4.7과 같고, CC-Bench-V2 연쇄 과제에서 Opus 4.5보다 9점 뒤진다. 큰 향상은 정적·공개 벤치마크에 몰려 있다.
  • base 모델의 수학이 후퇴했는데(GSM8K, MATH) 설명이 없고, base 평가 프레임워크는 내부 것이다.
  • 설명 없는 불일치: 본문 80층 vs Table 10의 79층, 40층 모델에 41자 층 pattern, MLA-256 설명(“head 차원 192 → 256, head 1/3 감소”) vs Table 10의 64 head·QK 192/V 256.
확인 문제Check yourself

On-policy cross-stage distillation은 group 크기 1을 쓴다. reasoning RL의 group 32를 버릴 수 있는 이유는?

GRPO에서 그룹은 baseline을 추정하려고 있다. 응답의 advantage는 그 보상에서 같은 프롬프트의 다른 응답들의 평균 보상을 뺀 것이다. 식 (2)에서는 토큰마다 이미 자기 신호 log⁡πteacher(yt)−log⁡πθ(yt)\log\pi_{\text{teacher}}(y_t)-\log\pi_\theta(y_t)가 있다. teacher가 학생보다 그 토큰을 더 좋아하면 양수, 덜 좋아하면 음수다. 학생 분포에서의 기댓값은 reverse KL의 음수이므로 프롬프트당 샘플 하나로도 (잡음은 있지만) 편향 없는 gradient가 나오고, 프롬프트당 샘플을 늘리는 것보다 batch의 프롬프트 수(1024)를 늘리는 편이 다양성을 더 산다.

정리

  • GLM-5는 744B/40B MoE(expert 256개, 79–80층)로, Muon Split으로 경쟁력을 얻은 MLA, head를 줄이고 키운 MLA-256으로 싸진 decode, 파라미터 공유 MTP, mid-training 뒤 20B 토큰 sparse 적응만으로 들인 DSA를 갖는다.
  • base는 28.5T 토큰으로 학습했고, mid-training은 32K / 128K / 200K에서 repo 단위 코드(issue–PR 쌍 ≈1천만)와 긴 문맥·agent 데이터에 집중한다.
  • Reasoning RL은 KL 없는 GRPO + IcePop(β=2, ε 0.2/0.28, group 32)이고, DSA RL에는 결정적 top-k와 고정된 indexer가 필요했다.
  • Agentic RL은 완전 비동기다. TITO, rollout log-prob을 행동 정책으로 쓰는 양쪽 mask, staleness 필터, crash를 고려한 그룹 padding, push마다 optimizer reset, DP-aware routing.
  • On-policy cross-stage distillation(advantage = teacher/학생 log 비율, group 1)이 단계들을 굳힌다. 많은 정적 벤치마크에서 Claude Opus 4.5에 근접하지만 새 과제와 연쇄 과제에서는 격차가 분명하다. GLM-5.1–5.3은 이 보고서를 그대로 참조하며 IndexShare/IndexCache, 1M 문맥, 더 많은 사후학습으로 확장한다.

더 읽을거리Further reading