Track VI · Frontier Tech Reports · 19/20

GLM-4.5 — 깊은 MoE, mid-training, expert 반복과 자기 증류GLM-4.5 — a deep MoE, mid-training, expert iteration and self-distillation

Zhipu AI의 GLM-4.5 보고서를 읽는다. 넓이 대신 깊이를 택한 355B/32B MoE, 사전학습과 사후학습 사이의 mid-training(repo 코드·합성 추론·긴 문맥·agent), 세 expert를 RL로 키운 뒤 self-distillation으로 하나의 hybrid thinking 모델로 합치는 사후학습, 그리고 난이도 curriculum·64K 단일 단계 RL·동적 temperature·agentic RL의 세부를 식과 그림, 코드로 따라간다.A reading of Zhipu AI's GLM-4.5 report: a 355B/32B MoE that chose depth over width, mid-training between pre- and post-training (repository code, synthetic reasoning, long context, agent data), post-training that grows experts with RL and merges them into one hybrid-thinking model by self-distillation, and the details of the difficulty curriculum, single-stage 64K RL, dynamic temperature and agentic RL — through equations, figures and code.

GLM-4.5 is the MoE model that Zhipu AI (Z.ai) and Tsinghua University released in July 2025, with the report following in August. The title is the goal: put agentic, reasoning and coding abilities — ARC for short — into one model. The method has three strands. A separate mid-training phase after pre-training feeds the model repository-level code, synthetic reasoning and agent trajectories. Post-training grows capability-specific expert models with RL and then merges them into one model by self-distillation. And the RL inside that process manages difficulty, length and temperature so that the learning signal never dries up. GLM-5 (next lesson) keeps almost all of this skeleton, so this lesson is also the reference point for reading the GLM line.

At a glance

ItemGLM-4.5
LabZhipu AI (Z.ai) & Tsinghua University
Releasemodel 2025-07, report arXiv v1 2025-08-08
SizeGLM-4.5 355B / 32B active, GLM-4.5-Air 106B / 12B (MTP layers included, embeddings and output layer excluded; Table 1)
Architecture89 MoE + 3 dense + 1 MTP layer. 8 of 160 routed experts + 1 shared, sigmoid gates, loss-free load balancing. GQA (96 heads, 8 KV heads) + partial RoPE + QK-Norm
Context128K (extended to 131,072 in mid-training)
Training tokensabout 23T (pre-training 15T + 7T, mid-training 500B + 500B + 100B; Fig. 3)
Post-trainingexpert (Reasoning / Agent / General) RL → merged by self-distillation SFT, hybrid thinking
Releaseopen weights, MIT (Hugging Face model card); evaluation toolkit glm-simple-evals released
LinksarXiv 2508.06471 · GitHub · slime

What is new

  • Depth instead of width. Unlike DeepSeek-V3 and Kimi K2, GLM-4.5 shrinks the hidden size and the number of experts and adds layers (89 MoE layers). It also uses 96 heads at hidden size 5120, about 2.5× the usual head count. Training loss does not improve, but reasoning benchmarks do — that is the report’s observation.
  • Mid-training. Between pre- and post-training it trains on medium-sized domain data (including instruction data): repository-level code (32K), synthetic reasoning (32K), then long context and agent trajectories (128K).
  • Expert iteration + unified self-distillation. Reasoning, Agent and General experts are each grown with cold-start SFT and RL, and one model is then fine-tuned on their outputs. Mixing data with and without a thought process puts both thinking and direct-answer modes into one model.
  • RL that keeps the signal alive. A two-stage difficulty curriculum (problems with pass@8 = 0 but pass@512 > 0), single-stage RL at 64K from the start, a temperature raised when progress plateaus, and a token-weighted loss for code RL.
  • Infrastructure and templates for agents. slime, an RL framework that runs both synchronous and asynchronous modes, and an XML-style function-call template that removes escaping from code arguments.

Architecture

A deep, narrow MoE

GLM-4.5 is the first MoE in the GLM line. Next to the models it compares against, DeepSeek-V3 and Kimi K2, its design direction is clear (report Table 1).

GLM-4.5GLM-4.5-AirDeepSeek-V3Kimi K2
total / active355B / 32B106B / 12B671B / 37B1043B / 32B
dense / MoE / MTP layers3 / 89 / 11 / 45 / 13 / 58 / 11 / 60 / 0
hidden5120409671687168
expert FFN1536140820482048
attention heads (KV heads)96 (8)96 (8)128 (128)64 (64)
experts total / active / shared160 / 8 / 1128 / 8 / 1256 / 8 / 1384 / 8 / 1
QK-NormYesNoNoNo

The report’s claim is a single sentence: “deeper models exhibited better reasoning capacity.” Whether to spend a parameter budget on layers or on width (hidden size, number of experts) is a trade-off, and GLM-4.5 chose depth. Compute it yourself in the figure below.

Parameters are counted as follows. With hidden size dd, HH heads, HkvH_{kv} KV heads, head dimension dhd_h, expert FFN width ded_e, kk of EE routed experts active and one shared expert, the attention and MoE parameters of one layer are

Pattn=2 d Hdh⏟WQ, WO+2 d Hkvdh⏟WK, WV,PMoEtotal=(E+1)⋅3 d de,PMoEactive=(k+1)⋅3 d deP_{\text{attn}} = \underbrace{2\,d\,H d_h}_{W_Q,\ W_O} + \underbrace{2\,d\,H_{kv} d_h}_{W_K,\ W_V},\qquad P_{\text{MoE}}^{\text{total}} = (E+1)\cdot 3\,d\,d_e,\qquad P_{\text{MoE}}^{\text{active}} = (k+1)\cdot 3\,d\,d_e

(3dde3dd_e are SwiGLU’s gate, up and down matrices). For GLM-4.5 that is 136M per layer for attention, and 3.8B total / 212M active per MoE layer. With 89 MoE layers, 3 dense layers and the MTP layer, the totals come out at 355B and 32B.

GLM-4.5는 Zhipu AI(Z.ai)와 칭화대가 2025년 7월 공개하고 8월 보고서를 낸 MoE 모델이다. 보고서의 제목이 곧 목표다. agent(Agentic), 추론(Reasoning), 코딩(Coding) 세 능력, 줄여서 ARC를 모델 하나에 모은다. 그 방법은 세 갈래다. 사전학습 뒤에 mid-training 단계를 따로 두어 repo 코드와 합성 추론, agent 궤적을 먹이고, 사후학습에서는 능력별 expert 모델을 RL로 키운 다음 self-distillation으로 하나로 합치며, 그 과정의 RL에서 신호가 마르지 않도록 난이도·길이·temperature를 관리한다. GLM-5(다음 레슨)가 거의 모든 골격을 그대로 이어받기 때문에, 이 레슨은 GLM 계열을 읽는 기준점이기도 하다.

한눈에

항목GLM-4.5
연구소Zhipu AI (Z.ai) & 칭화대
공개모델 2025-07, 보고서 arXiv v1 2025-08-08
크기GLM-4.5 355B / 32B active, GLM-4.5-Air 106B / 12B (MTP 층 포함, embedding·출력층 제외; Table 1)
구조MoE 89층 + dense 3층 + MTP 1층. routed expert 160개 중 8개 + shared 1개, sigmoid gate, loss-free 부하 균형. GQA(96 head, KV head 8) + partial RoPE + QK-Norm
문맥128K (mid-training에서 131,072까지 확장)
학습 토큰약 23T (사전학습 15T + 7T, mid-training 500B + 500B + 100B; Fig. 3)
사후학습expert(Reasoning / Agent / General) RL → self-distillation SFT로 통합, hybrid thinking
공개가중치 공개, MIT (Hugging Face 모델 카드). 평가 도구 glm-simple-evals 공개
링크arXiv 2508.06471 · GitHub · slime

무엇이 새로운가

  • 넓이 대신 깊이. DeepSeek-V3·Kimi K2와 달리 hidden 차원과 expert 수를 줄이고 층을 늘렸다(89 MoE 층). 또 hidden 5120에 head 96개를 두어 head 수를 보통의 약 2.5배로 했다. 학습 손실은 그대로인데 추론 벤치마크가 좋아졌다는 관찰이다.
  • mid-training. 사전학습과 사후학습 사이에 중간 크기의 도메인 데이터(instruction 데이터 포함)로 repo 단위 코드(32K), 합성 추론(32K), 긴 문맥·agent 궤적(128K)을 차례로 학습한다.
  • expert 반복 + 통합 self-distillation. Reasoning·Agent·General 세 expert를 각각 cold-start SFT와 RL로 키운 뒤, 그 출력으로 하나의 모델을 SFT한다. 사고 과정이 있는 데이터와 없는 데이터를 섞어 thinking/direct 두 모드를 한 모델에 넣는다.
  • 신호가 마르지 않게 하는 RL. 2단계 난이도 curriculum(pass@8 = 0, pass@512 > 0인 문제), 처음부터 64K 길이로 하는 단일 단계 RL, 정체되면 올리는 동적 temperature, 코드 RL의 token-weighted 손실.
  • agent용 인프라와 템플릿. 동기·비동기를 모두 지원하는 RL 프레임워크 slime, 코드 인자의 escape를 없앤 XML식 function call 템플릿.

아키텍처

깊고 좁은 MoE

GLM-4.5는 GLM 계열의 첫 MoE다. 비교 대상으로 삼은 DeepSeek-V3·Kimi K2와 나란히 놓으면 설계 방향이 선명하다(보고서 Table 1).

GLM-4.5GLM-4.5-AirDeepSeek-V3Kimi K2
총 / active355B / 32B106B / 12B671B / 37B1043B / 32B
dense / MoE / MTP 층3 / 89 / 11 / 45 / 13 / 58 / 11 / 60 / 0
hidden5120409671687168
expert FFN1536140820482048
attention head (KV head)96 (8)96 (8)128 (128)64 (64)
expert 총 / 선택 / shared160 / 8 / 1128 / 8 / 1256 / 8 / 1384 / 8 / 1
QK-NormYesNoNoNo

보고서의 주장은 한 문장이다. “더 깊은 모델이 더 나은 추론 능력을 보였다.” 같은 파라미터 예산을 층에 쓸지 폭(hidden, expert 수)에 쓸지는 trade-off인데, GLM-4.5는 깊이를 골랐다. 아래 그림에서 직접 계산해 보자.

파라미터는 다음처럼 센다. hidden dd, head HH, KV head HkvH_{kv}, head 차원 dhd_h, expert FFN 폭 ded_e, routed expert EE개 중 kk개 선택, shared expert 1개라면 한 층의 attention과 MoE는

Pattn=2 d Hdh⏟WQ, WO+2 d Hkvdh⏟WK, WV,PMoEtotal=(E+1)⋅3 d de,PMoEactive=(k+1)⋅3 d deP_{\text{attn}} = \underbrace{2\,d\,H d_h}_{W_Q,\ W_O} + \underbrace{2\,d\,H_{kv} d_h}_{W_K,\ W_V},\qquad P_{\text{MoE}}^{\text{total}} = (E+1)\cdot 3\,d\,d_e,\qquad P_{\text{MoE}}^{\text{active}} = (k+1)\cdot 3\,d\,d_e

(3dde3dd_e는 SwiGLU의 gate·up·down 세 행렬). GLM-4.5에 넣으면 attention이 층당 1.36억, MoE가 층당 총 38억·active 2.1억이다. 89개 MoE 층에 dense 3층과 MTP 층을 더하면 총 355B, active 32B가 맞아떨어진다.

총total –active –active 비율active share – heads ÷ (d/128) –
왼쪽은 Table 1의 네 모델을 세로 = 층 수, 가로 = hidden 차원으로 그린 모양이고, 점선이 지금 슬라이더의 구성이다. 오른쪽은 파라미터가 어디에 들어가는지(진한 색 = 토큰당 활성)다. "DeepSeek-V3 폭으로"를 누르면 총 파라미터를 거의 그대로 둔 채 d=7168, E=256, expert FFN 2048로 넓히고 층 수를 다시 맞춘다. 같은 예산에서 층이 89개에서 30개 남짓으로 줄어드는 것이 GLM-4.5가 피한 선택이다. attention은 GQA(KV head 8, head 차원 128)로 고정했다. 이 근사로 GLM-4.5는 355B/32B, Air는 108B/12B가 나온다(보고서 355B/32B, 106B/12B). Left: the four models of Table 1 drawn as height = number of layers, width = hidden size; the dashed box is the current slider configuration. Right: where the parameters go (dark = active per token). "Same total, DeepSeek-V3 width" keeps the total parameter count roughly fixed, widens to d=7168, E=256, expert FFN 2048 and refits the layer count. With the same budget the depth drops from 89 to about 30 layers — the choice GLM-4.5 avoided. Attention is fixed to GQA (8 KV heads, head dim 128). With this approximation GLM-4.5 comes out at 355B/32B and Air at 108B/12B (report: 355B/32B, 106B/12B).

Things to check in the figure:

  1. In GLM-4.5, 95% of all parameters sit in routed experts. In the active count, attention is about 40% — raising the head count to 96 is far from free per token.
  2. Press “Same total, DeepSeek-V3 width”: the same 355B fits only about 30 layers, because each layer gets heavier. GLM-4.5 went the other way, shrinking the per-expert width (ded_e 1536) and the hidden size (5120) to afford more layers.
  3. Change the number of heads and “heads ÷ (d/128)” moves. Usually Hdh≈dH d_h \approx d, so this is near 1; GLM-4.5 has 2.4. The report says more heads did not improve training loss but consistently improved reasoning benchmarks such as MMLU and BBH — an effect you would miss by picking architectures on loss curves alone.

Attention and routing details

  • GQA + partial RoPE. Eight KV heads shrink the KV cache (inference lesson); RoPE is applied to part of the head dimension. When extending to 32K the RoPE base goes from 10,000 to 1,000,000 (§2.4).
  • QK-Norm. Normalising queries and keys stabilises the range of attention logits (GLM-4.5 only, not Air).
  • Sigmoid gates + loss-free load balancing. This is DeepSeek-V3’s scheme. The affinity of token utu_t to expert centroid eie_i is si,t=σ(ut⊤ei)s_{i,t}=\sigma(u_t^\top e_i); an expert bias bib_i is added only for selection, and the weights are normalised with the bias-free ss:
Kt=TopK⁡i(si,t+bi, k),gi,t=si,t∑j∈Ktsj,t (i∈Kt),bi←bi+γ sign⁡(cˉ−ci)\mathcal{K}_t=\operatorname{TopK}_i\big(s_{i,t}+b_i,\ k\big),\qquad g_{i,t}=\frac{s_{i,t}}{\sum_{j\in\mathcal{K}_t}s_{j,t}}\ (i\in\mathcal{K}_t),\qquad b_i \leftarrow b_i+\gamma\,\operatorname{sign}(\bar c-c_i)

cic_i is the number of tokens expert ii received in the batch and cˉ\bar c the mean. An overloaded expert’s bias goes down and it is picked less. Nothing is added to the loss, so the gradient is not distorted. GLM-4.5 uses γ=0.001\gamma=0.001 for the first 15T tokens and then freezes the bias with γ=0\gamma=0. A sequence-level auxiliary loss with weight 10−410^{-4} only guards against extreme imbalance inside a single sequence.

  • MTP layer. One MoE layer is added as a Multi-Token Prediction layer, which adds training signal and serves as the draft for speculative decoding. Its loss weight λ\lambda is 0.3 for the first 15T tokens and 0.1 afterwards.

Data

Pre-training has two stages and mid-training three (report Fig. 3). The figure puts these five stages on one axis with the learning-rate, batch and sequence-length schedules the report states. The GLM-5 button shows the successor’s schedule from the next lesson.

그림에서 확인할 것:

  1. GLM-4.5에서 총 파라미터의 95%가 routed expert에 있다. active로 보면 attention이 약 40%를 차지한다. head를 96개로 늘린 결정이 토큰당 연산에서 결코 작지 않다는 뜻이다.
  2. “같은 총량을 DeepSeek-V3 폭으로”를 누르면 같은 355B 안에 층이 30개 남짓밖에 들어가지 않는다. 층 하나가 무거워지기 때문이다. GLM-4.5는 반대로 층을 늘리려고 expert 하나의 폭(ded_e 1536)과 hidden(5120)을 줄였다.
  3. head 수를 바꾸면 “heads ÷ (d/128)“이 움직인다. 보통은 Hdh≈dH d_h \approx d로 두어 이 값이 1 근처인데, GLM-4.5는 2.4다. 보고서는 head를 늘려도 학습 손실은 좋아지지 않았지만 MMLU·BBH 같은 추론 벤치마크는 꾸준히 좋아졌다고 쓴다. 손실 곡선만 보고 구조를 고르면 놓치는 효과라는 주장이다.

Attention과 routing의 세부

  • GQA + partial RoPE. KV head 8개로 KV cache를 줄이고(추론 최적화), RoPE는 head 차원의 일부에만 건다. 32K로 늘릴 때 RoPE base를 10,000에서 1,000,000으로 바꾼다(§2.4).
  • QK-Norm. query와 key를 정규화해 attention logit 범위를 안정시킨다(GLM-4.5만, Air는 없음).
  • sigmoid gate + loss-free 부하 균형. DeepSeek-V3의 방식이다. 토큰 utu_t와 expert 중심 eie_i의 친화도 si,t=σ(ut⊤ei)s_{i,t}=\sigma(u_t^\top e_i)에 expert별 bias bib_i를 선택에만 더해 top-kk를 고르고, 가중치는 bias 없는 ss로 정규화한다.
Kt=TopK⁡i(si,t+bi, k),gi,t=si,t∑j∈Ktsj,t (i∈Kt),bi←bi+γ sign⁡(cˉ−ci)\mathcal{K}_t=\operatorname{TopK}_i\big(s_{i,t}+b_i,\ k\big),\qquad g_{i,t}=\frac{s_{i,t}}{\sum_{j\in\mathcal{K}_t}s_{j,t}}\ (i\in\mathcal{K}_t),\qquad b_i \leftarrow b_i+\gamma\,\operatorname{sign}(\bar c-c_i)

cic_i는 배치에서 expert ii가 받은 토큰 수, cˉ\bar c는 평균이다. 너무 많이 받은 expert는 bias가 내려가 덜 뽑힌다. 손실에 항을 더하지 않으니 gradient를 왜곡하지 않는다. GLM-4.5는 γ=0.001\gamma=0.001로 처음 15T 토큰을 학습한 뒤 γ=0\gamma=0으로 bias를 고정했다. 시퀀스 하나 안에서 극단적으로 쏠리는 것만 막도록 가중치 10−410^{-4}의 sequence-level 보조 손실을 함께 쓴다.

  • MTP 층. MoE 층 하나를 MTP(Multi-Token Prediction) 층으로 붙여 학습 신호를 더하고 추론 때 speculative decoding의 draft로 쓴다. MTP 손실 가중치 λ\lambda는 15T까지 0.3, 이후 0.1이다.

데이터

사전학습은 두 단계, mid-training은 세 단계다(보고서 Fig. 3). 아래 그림은 그 다섯 단계와 보고서가 밝힌 학습률·batch·sequence 길이 일정을 한 축에 놓았다. GLM-5 버튼은 다음 레슨에서 볼 후속작의 일정이다.

단계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).

Pre-training corpus (§2.2).

  • Web: mostly English and Chinese pages. As in Nemotron-CC, pages are bucketed by quality score; higher buckets are up-sampled and the lowest discarded. The top bucket is seen more than 3.2 epochs. Many template-generated look-alike pages had high scores and survived MinHash, so embedding-based SemDedup was added.
  • Multilingual: own crawl + FineWeb-2, up-sampled by a classifier of educational value.
  • Code: GitHub and other hosts. After rule-based filtering, language-specific quality models sort files into high / medium / low; high is up-sampled, low dropped. Fill-In-the-Middle on all source code. Code-related web pages are found by HTML code tags or a FastText classifier, graded the same way, and re-parsed with a format-preserving parser.
  • Maths & science: an LLM scores the share of educational maths/science content, a small classifier imitates that score over the whole corpus, and documents above a threshold are up-sampled.

Stage 1 is mostly general web text; stage 2 up-samples GitHub code and coding / maths / science web pages. Pre-training at 4K does not use best-fit packing — random truncation is treated as good data augmentation. Mid-training does use best-fit packing so that reasoning traces and repository code are not cut.

Mid-training (§2.3). It differs from pre-training by using medium-sized domain data (instruction data included) instead of a huge general corpus.

StageDataLengthTokens
Repo-level codefiles of one repository concatenated + model-filtered issues, PRs and commits in one context, commits as diffs32K500B
Synthetic reasoningmaths, science and coding-contest questions and answers from the web and books, with solutions synthesised by a reasoning model32K500B
Long context & agentup-sampled long documents + large-scale synthetic agent trajectories128K100B

Repository-level training is a prerequisite for SWE tasks: reading an issue, moving across several files and producing a diff becomes part of the pre-training distribution. Synthetic reasoning data makes the long CoT of post-training familiar in advance. Agent trajectories are already seen once at 128K before any RL.

Post-training data. SFT happens twice. The cold-start SFT of the expert stage uses a small set with long CoT responses. The Overall SFT of the unified stage trains on millions of samples generated by the experts (reasoning, general chat, agent, long-context understanding) at up to 128K. The report names three tricks on the data side:

  • Rejection sampling: ① drop repetitive, too short, truncated or malformed samples ② verify answers where objective ③ filter subjective answers with a reward model ④ for tool calls, check protocol compliance and that the expected terminal state is reached.
  • Hard prompts + response scaling: removing the bottom 50% of prompts by response length improved maths and science by 2–4% with half the data; generating four responses per remaining hard prompt added another 1–2%.
  • Automatic agentic SFT data: collect agent frameworks, real APIs and MCP servers and let LLMs build or simulate tools → synthesise tasks (single- and multi-step tool calls) → generate trajectories with existing LLMs (using an LLM as a user simulator for multi-turn) → keep only trajectories that several judge agents confirm as complete.

Function-call template: no escaping for code

In agent models, code inside tool arguments is common. Writing arguments as JSON forces an escape character for every quote, backslash and newline, and the model must generate them exactly. GLM-4.5 proposes a template that wraps keys and values in XML-like special-token tags so code can be written verbatim (Fig. 4), and reports no loss in execution performance.

사전학습 corpus (§2.2).

  • 웹: 대부분 영어·중국어 웹 문서. Nemotron-CC처럼 품질 점수 bucket으로 나눠 높은 bucket을 up-sample하고 가장 낮은 bucket을 버린다. 최고 bucket은 사전학습 중 3.2 epoch 넘게 반복된다. 템플릿으로 자동 생성되어 점수만 높은 비슷한 페이지가 많았는데, MinHash로는 안 지워져 문서 임베딩 기반 SemDedup을 추가로 돌렸다.
  • 다국어: 자체 crawl + FineWeb-2. 교육적 가치를 보는 품질 분류기로 up-sample.
  • 코드: GitHub 등에서 수집. 규칙 필터 뒤 언어별 품질 모델로 상·중·하 3등급, 상은 up-sample, 하는 제외. 모든 소스 코드에 Fill-In-the-Middle 목적함수. 코드 관련 웹 문서는 HTML code 태그나 FastText 분류기로 1차 선별 후 같은 품질 분류, 그리고 코드 형식을 보존하는 전용 parser로 다시 파싱.
  • 수학·과학: LLM으로 “수학·과학 교육 내용 비율” 점수를 매기고 그것을 흉내 내는 작은 분류기로 corpus 전체에 점수를 매겨 임계값 이상을 up-sample.

1단계는 주로 웹 일반 문서, 2단계는 GitHub 코드와 코딩·수학·과학 웹 문서를 up-sample한다. 사전학습은 4K 길이에서 best-fit packing을 쓰지 않는다. 문서를 무작위로 자르는 것이 사전학습에는 좋은 데이터 증강이라는 판단이다. 반대로 mid-training에서는 추론 과정이나 repo 코드가 중간에 잘리지 않도록 best-fit packing을 쓴다.

mid-training (§2.3). 대규모 일반 문서 대신 중간 크기의 도메인 데이터(instruction 데이터 포함)를 쓴다는 점에서 사전학습과 다르다.

단계데이터길이토큰
Repo-level 코드같은 repo 파일을 이어 붙임 + 모델로 거른 issue·PR·commit을 한 문맥에, commit은 diff 형식32K500B
합성 추론웹·책에서 모은 수학·과학·코딩 대회 문제와 답, 추론 모델로 풀이 과정 합성32K500B
긴 문맥 & Agent긴 문서 up-sample + 대규모 합성 agent 궤적128K100B

repo 단위 학습은 SWE 과제의 전제다. issue를 읽고, 관련 파일 여러 개를 오가며, diff를 내는 일이 사전학습 분포 안에 들어온다. 합성 추론 데이터는 사후학습의 long CoT를 미리 익숙하게 만든다. agent 궤적도 RL 이전에 이미 128K 문맥에서 한 번 학습된다.

사후학습 데이터. SFT는 두 번 한다. expert 단계의 cold-start SFT는 긴 CoT 응답을 가진 소량 데이터다. 통합 단계의 Overall SFT는 expert들이 생성한 수백만 샘플(추론·일반 대화·agent·긴 문맥 이해)을 최대 128K로 학습한다. 데이터 쪽에서 보고서가 밝힌 요령은 셋이다.

  • rejection sampling: ① 반복·너무 짧음·잘림·형식 위반 제거 ② 객관식 답은 정답 검증 ③ 주관 질문은 reward model로 필터 ④ tool 호출은 프로토콜 준수와 기대한 종료 상태 도달을 확인.
  • 어려운 프롬프트 + response scaling: 응답 길이 기준 하위 50% 프롬프트를 지우자 데이터가 절반인데도 수학·과학이 2–4% 올랐고, 남은 어려운 프롬프트마다 응답을 4개씩 만들자 1–2% 더 올랐다.
  • agentic SFT 자동 구축: agent 프레임워크·실제 API·MCP 서버를 모으고 LLM으로 도구를 만들거나 시뮬레이션 → 과제 합성(단일·다단계 tool 호출) → 기존 LLM으로 궤적 생성(LLM을 user simulator로 써서 멀티턴화) → 여러 judge agent가 완료를 확인한 궤적만 남김.

Function call 템플릿: 코드를 escape하지 않기

agent 모델에서 tool 인자에 코드가 들어가는 일은 흔하다. JSON으로 인자를 쓰면 따옴표·역슬래시·줄바꿈마다 escape 문자가 붙고, 모델은 그것을 정확히 생성해야 한다. GLM-4.5는 키와 값을 XML 비슷한 특수 토큰 태그로 감싸 코드를 원문 그대로 쓰는 템플릿을 제안했다(Fig. 4). 실행 성능은 떨어지지 않았다고 보고한다.

JSON tool call
GLM-4.5 XML 템플릿template
JSON escape 문자chars –XML escape 문자chars –JSON 길이 / XML 길이JSON length / XML length –
코드를 고쳐 보면 따옴표·역슬래시·줄바꿈 하나마다 JSON 쪽에는 \가 붙는다. 인자를 문자열로 한 번 더 감싸는 API 형식에서는 역슬래시가 다시 이스케이프되어 개수가 몇 배로 는다. 모델은 이 문자들을 한 토큰씩 정확히 생성해야 한다. GLM-4.5는 키와 값을 <arg_key>·<arg_value> 특수 토큰 태그로 감싸 코드를 원문 그대로 쓰게 했다(보고서 Fig. 4). 실행 성능은 유지하면서 escape를 줄였다고 보고한다. Edit the code: every quote, backslash and newline gets a \ on the JSON side. In API formats that wrap the arguments in a string once more, the backslashes are escaped again and the count multiplies. The model has to generate each of these characters exactly, token by token. GLM-4.5 wraps keys and values in <arg_key> / <arg_value> special-token tags so code is written verbatim (report Fig. 4), and reports that this reduces escaping without hurting function-call execution.

Training

Pre-training recipe (§2.4)

  • Optimizer: Muon (except word embeddings, biases and RMSNorm weights), 5 Newton–Schulz steps, momentum μ=0.95\mu=0.95, update RMS scaled to 0.2. In the Moonlight form, for a matrix W∈Rm×nW\in\mathbb{R}^{m\times n}:
Mt=μMt−1+∇WL,Ot=NS⁡5(Mt)≈UV⊤,W←W−η(0.2max⁡(m,n)  Ot+λW)M_t=\mu M_{t-1}+\nabla_W\mathcal{L},\qquad O_t=\operatorname{NS}_5(M_t)\approx U V^\top,\qquad W\leftarrow W-\eta\big(0.2\sqrt{\max(m,n)}\;O_t+\lambda W\big)

OtO_t is the momentum matrix with all singular values pushed to about 1, and 0.2max⁡(m,n)0.2\sqrt{\max(m,n)} scales its RMS to the AdamW level (0.2). The report says Muon converges faster and tolerates larger batches (optimizers).

  • Learning rate: cosine, not WSD. After warm-up, cosine decay from 2.5×10−42.5\times10^{-4} to 2.5×10−52.5\times10^{-5} by the end of mid-training. In early experiments warmup-stable-decay scored lower on SimpleQA and MMLU, which the team read as underfitting in the stable phase.
  • Batch warm-up: 16M → 64M tokens over the first 500B tokens, then constant. Weight decay 0.1, no dropout.
  • Length: 4,096 in pre-training, 32,768 → 131,072 in mid-training.

Post-training: expert iteration and merging

학습

사전학습 recipe (§2.4)

  • 옵티마이저: Muon(word embedding, bias, RMSNorm 가중치 제외). Newton–Schulz 5회, momentum μ=0.95\mu=0.95, update RMS를 0.2로 맞춘다. Moonlight 형식으로 쓰면 행렬 W∈Rm×nW\in\mathbb{R}^{m\times n}에 대해
Mt=μMt−1+∇WL,Ot=NS⁡5(Mt)≈UV⊤,W←W−η(0.2max⁡(m,n)  Ot+λW)M_t=\mu M_{t-1}+\nabla_W\mathcal{L},\qquad O_t=\operatorname{NS}_5(M_t)\approx U V^\top,\qquad W\leftarrow W-\eta\big(0.2\sqrt{\max(m,n)}\;O_t+\lambda W\big)

이다. OtO_t는 momentum 행렬의 특이값을 모두 1 근처로 편 직교 행렬이고, 0.2max⁡(m,n)0.2\sqrt{\max(m,n)}은 그 update의 RMS를 AdamW 수준(0.2)에 맞추는 계수다. Muon이 수렴을 빠르게 하고 더 큰 batch를 견딘다고 보고한다(옵티마이저).

  • 학습률: WSD가 아니라 cosine. warm-up 후 2.5×10−42.5\times10^{-4}에서 mid-training 끝까지 2.5×10−52.5\times10^{-5}로 cosine 감쇠. 초기 실험에서 WSD(warmup-stable-decay)는 SimpleQA·MMLU가 낮았고, 이를 stable 구간의 underfitting으로 해석했다.
  • batch warm-up: 첫 500B 토큰 동안 16M → 64M 토큰으로 늘리고 이후 고정. weight decay 0.1, dropout 없음.
  • 길이: 사전학습 4,096, mid-training에서 32,768 → 131,072.

사후학습: expert 반복과 통합

경로 보기Trace
Stage 1 · Expert Training
Base (mid-training 끝) → cold-start SFT
소량의 긴 CoT 데이터
Base (end of mid-training) → cold-start SFT
small long-CoT set
expert RL
Reasoning expert
수학·과학·코드 RLVR
Reasoning expert
math · science · code RLVR
Agent expert
web search · SWE RL ⟲ self-distill
General expert
RM + RLAIF + 규칙
General expert
RM + RLAIF + rules
rejection sampling
정답 검증
반복·잘림·형식 위반 제거
answer verification
drop repetitive / truncated / malformed
tool 프로토콜 · 종료 상태
judge agent 다수가 완료 확인
tool protocol · terminal state
several judge agents confirm completion
reward model 필터
주관적 질문
reward-model filter
subjective questions
Stage 2 · Unified Training
Overall SFT (self-distillation)
수백만 샘플 · 최대 128K
thinking / direct 데이터 균형
Overall SFT (self-distillation)
millions of samples · up to 128K
balanced thinking / direct data
GLM-4.5
hybrid: thinking ↔ direct
버튼을 눌러 능력 하나가 어디서 길러지고(expert RL), 어떤 기준으로 걸러지고(rejection sampling), 어떻게 하나의 모델로 합쳐지는지(self-distillation SFT) 따라가 본다. 각 expert는 같은 base에서 cold-start SFT로 시작한다. Agent의 ⟲는 "RL → RL 모델의 응답으로 cold-start 데이터 교체 → 더 나은 SFT 모델에서 다시 RL"을 반복하는 iterative distillation이다. 보고서는 RL 기법(§3.2–3.4)이 Stage 2 이후에도 다시 적용되는지, 어떤 순서인지는 그림으로 명시하지 않는다. Press a button to follow one capability: where it is grown (expert RL), how it is filtered (rejection sampling), and how it is merged into one model (self-distillation SFT). Every expert starts from the same base with a cold-start SFT. The ⟲ on the agent expert is iterative distillation: RL → replace the cold-start data with the RL model's responses → RL again from the better SFT model. The report does not spell out whether (or in which order) the RL techniques of §3.2–3.4 are applied again after Stage 2.

Stage 1 (Expert Training) builds Reasoning, Agent and General-chat experts separately from the same base. Each starts with cold-start SFT and is grown by RL in its domain. Stage 2 (Unified Training) filters the experts’ data by rejection sampling and fine-tunes one model on it. Domains that need no thought process (chit-chat, for instance) get responses without one, reasoning domains get long CoT, and balancing the two gives hybrid reasoning: one model with both a thinking mode and an immediate-answer mode.

This contrasts with “mix every reward into one RL run”. The domains differ too much in output length, convergence speed, reward type and infrastructure, so optimising them separately and merging by SFT is easier to manage. The price is that there is no guarantee each expert’s peak survives the merge. GLM-5 revisits this with on-policy distillation (next lesson).

Reasoning RL (§3.2)

The objective is GRPO without the KL term:

J(θ)=Ex,{yi}i=1G∼πold[1Z∑i=1G∑t=1∣yi∣min⁡(ρi,tA^i, clip⁡(ρi,t,1−ε,1+ε)A^i)],A^i=ri−mean⁡(r)std⁡(r)J(\theta)=\mathbb{E}_{x,\{y_i\}_{i=1}^G\sim\pi_{\text{old}}}\Bigg[\frac{1}{Z}\sum_{i=1}^{G}\sum_{t=1}^{|y_i|}\min\Big(\rho_{i,t}\hat A_i,\ \operatorname{clip}(\rho_{i,t},1-\varepsilon,1+\varepsilon)\hat A_i\Big)\Bigg],\qquad \hat A_i=\frac{r_i-\operatorname{mean}(r)}{\operatorname{std}(r)}

ZZ is G∣yi∣G|y_i| (sequence-mean) or ∑j∣yj∣\sum_j|y_j| (token-weighted mean) depending on the aggregation. For code RL the latter converged much faster (Fig. 7 left; for why, see the length bias in the RLVR lesson). The report gives no clip range ε\varepsilon, group size or learning rate, and all ablation curves in this section come from a smaller experimental model.

Four techniques sit on top:

  1. Two-stage difficulty curriculum. Data that is too hard early, or too easy late, produces groups with identical rewards and no gradient. Stage 1 uses moderate difficulty (16 samples per prompt); stage 2 switches to extremely hard problems with pass@8 = 0 but pass@512 > 0 (512 samples per prompt), all from a pool with verified answers. More below.
  2. Single-stage RL at 64K. Multi-stage RL that grows the maximum length 16K → 32K → 48K → 64K (as in DeepScaleR) forces short outputs on a model that SFT already taught to write 64K responses; it “unlearns” long outputs and never recovers. Running at 64K from the start was better (Fig. 6).
  3. Dynamic sampling temperature. When the average reward plateaus, treat it as convergence and raise the temperature — to the largest value whose validation performance stays within 1% of the current best, checked over a range of temperatures.
  4. Code and science RL. Token-weighted mean loss for code. For science, using only expert-verified multiple-choice questions clearly beat mixed-quality data on GPQA-Diamond (Fig. 7 right).

Agentic RL (§3.3)

Two targets, web search and SWE, both automatically verifiable. Web-search questions are synthesised by multi-hop reasoning over knowledge graphs and by humans selecting and obfuscating content from several pages. SWE tasks come from GitHub PRs and issues with executable unit tests, run in an isolated distributed sandbox.

The objective is a policy gradient with the group mean as baseline. The report writes the abbreviated form Ex[1K∑i(r(x,yi)−rˉ(x))]\mathbb{E}_x\big[\frac1K\sum_i(r(x,y_i)-\bar r(x))\big]; as a gradient it is

∇θJ=Ex[1K∑i=1K(r(x,yi)−rˉ(x))∑t∈M(yi)∇θlog⁡πθ(yi,t∣x,yi,<t)],rˉ(x)=1K∑jr(x,yj)\nabla_\theta J=\mathbb{E}_x\Bigg[\frac{1}{K}\sum_{i=1}^{K}\big(r(x,y_i)-\bar r(x)\big)\sum_{t\in\mathcal{M}(y_i)}\nabla_\theta\log\pi_\theta(y_{i,t}\mid x,y_{i,<t})\Bigg],\qquad \bar r(x)=\frac1K\sum_{j}r(x,y_j)

where M(yi)\mathcal{M}(y_i) are the positions of model-generated tokens; environment tokens such as tool results are excluded from the loss (the trajectory mask of Agent RL). Reward design is simple:

  • Outcome reward: final-answer accuracy for web search, passing tests for SWE, as the reward of the whole trajectory.
  • Process format penalty: if a tool call is malformed during generation, the rollout stops there with reward 0.
  • Iterative distillation: agent RL is slow, so once RL reaches a step budget or plateaus, the cold-start SFT data is replaced with the RL model’s responses to make a better SFT model, and RL continues from it on harder tasks.
  • Test-time scaling via interaction turns: BrowseComp accuracy rises smoothly with more interaction turns (test-time compute), almost linearly on a log axis (Fig. 8).

The report adds that RL on web search and SWE generalised to other tasks such as general tool use and Terminal-Bench.

General RL (§3.4)

Rule-based feedback, human feedback (RLHF) and model feedback (RLAIF) are combined.

  • Holistic RL: about 5,000 prompts over 7 primary, 33 secondary and 139 tertiary categories; a reward model trained on human preferences combined with AI feedback using different rubrics depending on whether the prompt has a ground-truth answer.
  • Instruction-following RL: a taxonomy of 7 major and 151 minor constraint types; rules + RM + critique model. Thanks to this hybrid feedback, SysBench-ISR rose with the reward for about 1,000 steps without clear signs of reward hacking (Fig. 9).
  • Function-calling RL: step-wise rule rewards and end-to-end multi-turn rewards. The step-wise reward is strict:
rt=1[FormatCorrect(at)∧Match(at,at∗)]r_t=\mathbb{1}\big[\texttt{FormatCorrect}(a_t)\wedge\texttt{Match}(a_t,a_t^\ast)\big]

The name, the parameters and every field must match the gold call at∗a_t^\ast exactly. The end-to-end reward is 1 only if the whole trajectory is well-formed and the task is completed according to environment rules or an LLM judge; it uses tasks synthesised from MCP servers, runnable environments such as AgentGym, and multi-turn tasks with an LLM-simulated user.

  • Pathology RL: language mixing, excessive repetition and format errors occur in under 1% of outputs, so penalising them inside general RL is sample-inefficient. A final RL pass uses a dataset of prompts likely to trigger them.

RL infrastructure: slime (§3.5)

slime is Zhipu’s open RL framework: Megatron for training, SGLang + router for rollout, and a data buffer between them.

  • Synchronous colocated vs asynchronous disaggregated. For reasoning RL (maths, code) a synchronous design with training and inference on the same GPUs plus dynamic sampling leaves the fewest GPUs idle. For agent tasks such as SWE, rollouts are long and interact with complex environments, so rollout and training GPUs are separated and run asynchronously. Ray’s scheduling lets one system support both.
  • FP8 rollouts. Training in BF16, rollout in FP8: at every policy update the parameters are quantised block-wise to FP8 online before being sent to the rollout engines (also a source of train–inference mismatch).
  • Agent-oriented design. High-concurrency Docker runtimes give each task an isolated environment, and heterogeneous agent frameworks are connected through an HTTP endpoint + a central data pool. Most frameworks produce rollouts as message lists, which go straight into the pool; training pulls from it through task-specific filters and dynamic sampling.

Key methods in depth

1. When a group carries signal, and the two-stage curriculum

With binary rewards and pass rate pp, a group of GG samples has identical rewards (all 0 or all 1) with probability pG+(1−p)Gp^G+(1-p)^G, and then every GRPO advantage is zero. The probability of a useful group is

Psignal(p;G)=1−pG−(1−p)GP_{\text{signal}}(p;G)=1-p^G-(1-p)^G

As the model improves, stage-1 data (moderate difficulty) drifts towards p→1p\to1 and PsignalP_{\text{signal}} falls. Why not just add hard problems? At p=0.002p=0.002 and G=16G=16, Psignal≈0.03P_{\text{signal}}\approx0.03: nearly every group is discarded. So in stage 2 GLM-4.5 raises the samples per prompt to 512: at p=0.002p=0.002, G=512G=512, Psignal≈0.64P_{\text{signal}}\approx 0.64.

As a function of the pass rate, the selection rule “pass@8 = 0 and pass@512 > 0” picks a problem with probability

Pselect(p)=(1−p)8(1−(1−p)512)P_{\text{select}}(p)=(1-p)^8\big(1-(1-p)^{512}\big)

— a filter for p≪1/8p\ll 1/8 but p≳1/512p\gtrsim 1/512, problems the current model almost never, but sometimes, solves.

Stage 1 (Expert Training) 은 Reasoning, Agent, General chat 세 expert를 같은 base에서 따로 만든다. 각자 cold-start SFT로 시작해 해당 영역 RL로 키운다. Stage 2 (Unified Training) 은 expert들이 만든 데이터를 rejection sampling으로 걸러 하나의 모델에 SFT한다. 사고 과정이 필요 없는 영역(잡담 등)은 사고 없는 응답을, 추론 영역은 긴 CoT를 넣어 균형을 맞춤으로써 hybrid reasoning, 즉 thinking 모드와 즉답 모드를 한 모델이 갖게 된다.

이 구조는 “하나의 RL 실행에 모든 보상을 섞는다”와 대비된다. 영역마다 RL의 성질(출력 길이, 수렴 속도, 보상 종류, 인프라)이 너무 달라서, 따로 최적화한 뒤 SFT로 합치는 편이 다루기 쉽다. 대가는 합치는 과정에서 각 expert의 정점이 그대로 보존된다는 보장이 없다는 것이다. GLM-5가 이 문제를 on-policy distillation으로 다시 푼다(다음 레슨).

추론 RL (Reasoning RL, §3.2)

목적함수는 GRPO에서 KL 항을 뺀 형태다.

J(θ)=Ex,{yi}i=1G∼πold[1Z∑i=1G∑t=1∣yi∣min⁡(ρi,tA^i, clip⁡(ρi,t,1−ε,1+ε)A^i)],A^i=ri−mean⁡(r)std⁡(r)J(\theta)=\mathbb{E}_{x,\{y_i\}_{i=1}^G\sim\pi_{\text{old}}}\Bigg[\frac{1}{Z}\sum_{i=1}^{G}\sum_{t=1}^{|y_i|}\min\Big(\rho_{i,t}\hat A_i,\ \operatorname{clip}(\rho_{i,t},1-\varepsilon,1+\varepsilon)\hat A_i\Big)\Bigg],\qquad \hat A_i=\frac{r_i-\operatorname{mean}(r)}{\operatorname{std}(r)}

ZZ는 집계 방식에 따라 G∣yi∣G|y_i|(sequence-mean) 또는 ∑j∣yj∣\sum_j|y_j|(token-weighted mean)다. 코드 RL에서는 후자가 훨씬 빨리 수렴했다고 보고한다(Fig. 7 왼쪽; 이유는 RLVR 레슨의 길이 편향). 보고서는 clip 범위 ε\varepsilon, group 크기, 학습률은 밝히지 않는다. 이 절의 ablation 곡선은 모두 더 작은 실험 모델의 것이다.

그 위에 네 가지가 얹힌다.

  1. 2단계 난이도 curriculum. 학습 초반엔 너무 어려운 데이터가, 후반엔 너무 쉬운 데이터가 모든 보상이 같은 그룹을 만들어 gradient를 없앤다. 그래서 1단계는 중간 난이도(프롬프트당 16 샘플), 2단계는 pass@8 = 0이지만 pass@512 > 0인 극단적으로 어려운 문제(프롬프트당 512 샘플)로 바꾼다. 2단계 문제는 모두 정답이 검증된 풀에서만 가져온다. 아래 “깊게 보기”에서 자세히 본다.
  2. 64K에서 단일 단계 RL. DeepScaleR처럼 최대 길이를 16K → 32K → 48K → 64K로 늘려 가는 다단계 RL은, SFT로 이미 64K 응답에 익숙한 모델에게 짧은 길이를 강요해 긴 응답 능력을 “잊게” 만들고 그 손실이 회복되지 않았다. 처음부터 64K로 하는 편이 나았다(Fig. 6).
  3. 동적 sampling temperature. 평균 보상이 정체되면 수렴 구간으로 보고 temperature를 올린다. 단, 검증셋에서 여러 temperature를 평가해 성능이 현재 최적보다 1% 넘게 떨어지지 않는 최대값을 다음 구간의 temperature로 쓴다.
  4. 코드·과학 RL. 코드는 token-weighted mean 손실. 과학은 전문가가 검증한 객관식 문제만 쓰는 것이 품질이 섞인 데이터보다 GPQA-Diamond에서 확실히 좋았다(Fig. 7 오른쪽).

에이전트 RL (Agentic RL, §3.3)

대상은 web search와 SWE 두 가지다. 둘 다 결과를 자동으로 검증할 수 있다. web search는 지식 그래프 위 multi-hop 추론으로 질문을 자동 합성하고, 여러 웹 페이지 내용을 사람이 골라 난독화해 만든다. SWE는 GitHub PR·issue와 실행 가능한 unit test로 과제를 만들고 격리된 분산 sandbox에서 돌린다.

목적함수는 group 평균을 baseline으로 쓰는 정책 경사다. 보고서는 advantage만 적은 축약형 Ex[1K∑i(r(x,yi)−rˉ(x))]\mathbb{E}_x\big[\frac1K\sum_i(r(x,y_i)-\bar r(x))\big]로 쓰는데, gradient로 풀면

∇θJ=Ex[1K∑i=1K(r(x,yi)−rˉ(x))∑t∈M(yi)∇θlog⁡πθ(yi,t∣x,yi,<t)],rˉ(x)=1K∑jr(x,yj)\nabla_\theta J=\mathbb{E}_x\Bigg[\frac{1}{K}\sum_{i=1}^{K}\big(r(x,y_i)-\bar r(x)\big)\sum_{t\in\mathcal{M}(y_i)}\nabla_\theta\log\pi_\theta(y_{i,t}\mid x,y_{i,<t})\Bigg],\qquad \bar r(x)=\frac1K\sum_{j}r(x,y_j)

이고, M(yi)\mathcal{M}(y_i)는 모델이 생성한 토큰의 위치다. tool 결과 같은 환경 토큰은 손실에서 뺀다(Agent RL의 trajectory mask). 보상 설계는 단순하다.

  • 결과 보상: web search는 최종 답 정확도, SWE는 테스트 통과를 궤적 전체의 보상으로.
  • process format penalty: 궤적 생성 중 tool 호출 형식이 틀리면 그 자리에서 멈추고 보상 0.
  • iterative distillation: agent RL은 오래 걸리므로, RL이 일정 step에 이르거나 정체되면 RL 모델의 응답으로 cold-start SFT 데이터를 교체해 더 나은 SFT 모델을 만들고, 그 위에서 더 어려운 과제로 RL을 이어간다.
  • 상호작용 횟수로 test-time scaling: BrowseComp 정확도가 상호작용 턴(=test-time compute)을 늘리는 만큼 매끄럽게 오른다(Fig. 8, log 축에서 거의 직선).

보고서는 web search와 SWE에 대한 RL이 일반 tool 사용이나 Terminal-Bench 같은 다른 과제로도 일반화되었다고 쓴다.

일반 RL (General RL, §3.4)

규칙 기반 피드백, 사람 피드백(RLHF), 모델 피드백(RLAIF)을 섞는다.

  • Holistic RL: 7개 대분류·33개 중분류·139개 소분류에 걸친 약 5,000개 프롬프트. 사람 선호로 학습한 RM과, 정답 유무에 따라 다른 rubric을 쓰는 AI 피드백을 합친다.
  • Instruction following RL: 7개 대분류·151개 소분류의 제약 taxonomy. 규칙 검증 + RM + critique 모델의 혼합 피드백 덕에 약 1,000 step까지 reward hacking의 뚜렷한 징후 없이 SysBench-ISR이 보상과 함께 올랐다(Fig. 9).
  • Function calling RL: 단계별 규칙 보상과 end-to-end 멀티턴 보상 두 종류. 단계별 보상은 엄격하다.
rt=1[FormatCorrect(at)∧Match(at,at∗)]r_t=\mathbb{1}\big[\texttt{FormatCorrect}(a_t)\wedge\texttt{Match}(a_t,a_t^\ast)\big]

이름·인자·모든 필드가 정답 호출 at∗a_t^\ast와 정확히 같아야 1이다. end-to-end 보상은 전체 궤적의 형식이 맞고 환경 규칙이나 LLM judge가 판단한 과제 완료일 때만 1이다. 후자는 MCP 서버 기반 합성 과제와 AgentGym 같은 실행 환경, LLM이 흉내 내는 user와의 멀티턴 과제를 쓴다.

  • Pathology RL: 언어 섞임, 과도한 반복, 형식 오류는 출력의 1% 미만이라 일반 RL에서 벌하면 표본 효율이 나쁘다. 이런 병리를 잘 일으키는 프롬프트만 모은 데이터셋으로 마지막에 따로 RL한다.

RL 인프라: slime (§3.5)

slime은 Megatron(학습), SGLang + router(rollout), 둘을 잇는 data buffer로 이루어진 Zhipu의 공개 RL 프레임워크다.

  • 동기 colocated vs 비동기 disaggregated. 수학·코드 같은 추론 RL은 학습·추론 엔진을 같은 GPU에 두는 동기 방식에 dynamic sampling을 더하는 편이 GPU 유휴가 적다. SWE 같은 agent 과제는 rollout이 길고 환경과의 상호작용이 복잡해, rollout GPU와 학습 GPU를 분리하고 비동기로 돌린다. Ray의 자원 스케줄링으로 둘을 같은 시스템에서 지원한다.
  • FP8 rollout. 학습은 BF16, rollout은 FP8. 매 정책 갱신마다 파라미터를 온라인으로 block 단위 FP8 양자화해 rollout 엔진에 보낸다(학습–추론 불일치의 원천이기도 하다).
  • agent용 설계. 과제마다 격리된 Docker 런타임을 고동시성으로 띄우고, 다양한 agent 프레임워크를 HTTP endpoint + 중앙 data pool로 연결한다. 대부분의 프레임워크가 message-list 형식으로 rollout을 내므로 그대로 pool에 쌓고, 학습은 그 pool에서 과제별 필터와 dynamic sampling을 거쳐 데이터를 가져간다.

핵심 method 깊게 보기

1. 그룹에 신호가 있을 확률과 2단계 curriculum

이진 보상에서 정답률이 pp인 문제로 GG개를 뽑으면, 그룹이 전부 같은 보상(전부 0 또는 전부 1)일 확률은 pG+(1−p)Gp^G+(1-p)^G이고 그때 GRPO advantage는 모두 0이다. 신호가 있을 확률은

Psignal(p;G)=1−pG−(1−p)GP_{\text{signal}}(p;G)=1-p^G-(1-p)^G

이다. 1단계 데이터(중간 난이도)는 모델이 좋아질수록 p→1p\to1로 밀려 PsignalP_{\text{signal}}이 줄어든다. 그렇다면 어려운 문제를 넣으면 되는가? 정답률이 p=0.002p=0.002인 문제에서 G=16G=16이면 Psignal≈0.03P_{\text{signal}}\approx0.03이다. 거의 모든 그룹이 버려진다. 그래서 GLM-4.5는 2단계에서 샘플 수를 512로 올린다. p=0.002p=0.002, G=512G=512이면 Psignal≈0.64P_{\text{signal}}\approx 0.64다.

선별 조건 “pass@8 = 0 그리고 pass@512 > 0”을 정답률의 함수로 쓰면 그 문제가 뽑힐 확률은

Pselect(p)=(1−p)8(1−(1−p)512)P_{\text{select}}(p)=(1-p)^8\big(1-(1-p)^{512}\big)

이다. p≪1/8p\ll 1/8이면서 p≳1/512p\gtrsim 1/512인 구간, 즉 현재 모델이 거의 못 풀지만 아주 가끔은 푸는 문제를 고르는 필터다.

중간 난이도 풀: 신호 있는 그룹moderate pool: groups with signal – 극난도 풀: 신호 있는 그룹extreme pool: groups with signal – rollout 1,000개당 신호 그룹signal groups per 1,000 rollouts –
가로축은 문제 하나의 현재 정답률 p다(logit 축: 0과 1 근처를 모두 펼쳐 보이도록 log(p/(1−p))로 그렸다). 곡선은 G개를 뽑았을 때 그룹에 0과 1이 섞여 gradient가 생길 확률 1 − pG − (1−p)G, 주황 면은 2단계 선별 조건 "pass@8 = 0 그리고 pass@512 > 0"을 통과할 확률 (1−p)8(1 − (1−p)512)이다. 아래 띠는 두 문제 풀의 정답률 분포(가상의 예). t를 오른쪽으로 끌면 모델이 좋아져 중간 난이도 풀이 p≈1 쪽으로 밀리고 전부 정답인 그룹이 늘어난다(파랑 비율 하락). 이때 극난도 풀은 G=16으로는 거의 전부 0점이지만 G=512로 뽑으면 신호가 난다. 대신 프롬프트당 rollout이 32배이므로 rollout당 효율도 함께 봐야 한다. The x-axis is the current pass rate p of one problem (a logit axis, log(p/(1−p)), so both ends near 0 and 1 are visible). The curves give the probability that a group of G samples mixes 0s and 1s and therefore produces a gradient, 1 − pG − (1−p)G; the orange area is the probability that a problem passes the stage-2 filter "pass@8 = 0 and pass@512 > 0", (1−p)8(1 − (1−p)512). The strips below show the pass-rate distributions of two problem pools (an illustrative example). Drag t to the right: the model improves, the moderate pool moves towards p≈1 and all-correct groups take over (the blue share drops). The extreme pool gives almost only all-zero groups at G=16 but real signal at G=512 — at 32× the rollouts per prompt, so also look at the efficiency per rollout.

One more thing to read off the figure: the signal groups per 1,000 rollouts are far fewer in the extreme pool (G=512). For the same rollout budget, moderate problems produce more gradient. The value of stage 2 is not the amount of signal but its kind: a “stronger solution strategy” that moderate problems cannot distinguish is rewarded only on extreme problems. The toy below shows this.

확인 문제Check yourself

If the problems selected for stage 2 (pass@8 = 0, pass@512 > 0) were trained with 16 samples per prompt, as in stage 1, what is the most likely result?

By definition these problems were never solved in 8 tries. At pass rates of roughly p≈0.002p\approx 0.002–0.050.05, the probability that a group of 16 is all zero, (1−p)16(1-p)^{16}, is 0.45–0.97. Signal requires larger groups, which is why GLM-4.5 drew 512 samples per prompt in stage 2.

A toy RLVR run reproduces the shape of Fig. 5. The policy is a distribution over six solution strategies of different skill. After stage 1 on moderate problems we continue with (A) the same data, (B) extreme problems that pass the selection rule with G=512, or (C) the same extreme problems with G=16. All three spend 512 rollouts per step.

NumPy Two-stage difficulty curriculum (toy)
import numpy as np

SKILL  = np.array([0.10, 0.30, 0.50, 0.70, 0.85, 0.95])   # skill of each solution strategy
THETA0 = np.array([1.0, 1.5, 1.5, 0.5, -1.0, -2.0])       # base policy prefers weak strategies
sig = lambda z: 1 / (1 + np.exp(-z))

def pi_of(th):
    e = np.exp(th - th.max()); return e / e.sum()

def solve_p(d):                                  # (B, S): success prob of strategy s on difficulty d
    return sig(25 * (SKILL[None, :] - d[:, None]))

def rl_step(th, rng, d, G, lr):
    """GRPO (no KL): update strategy logits with group-normalised advantages."""
    pi, B = pi_of(th), len(d)
    s = np.minimum(np.searchsorted(np.cumsum(pi), rng.random((B, G))), len(th) - 1)
    r = (rng.random((B, G)) < solve_p(d)[np.arange(B)[:, None], s]).astype(float)
    std = r.std(1, keepdims=True)
    A = (r - r.mean(1, keepdims=True)) / (std + 1e-6)
    grad = (A[..., None] * (np.eye(len(th))[s] - pi)).sum((0, 1)) / (B * G)
    return th + lr * grad, (std[:, 0] == 0).mean()          # new θ, zero-variance share

def moderate(rng, B):                            # moderate-difficulty pool
    return rng.uniform(0.30, 0.74, B)

def extreme(rng, th, n):                         # keep only pass@8 = 0 and pass@512 > 0
    out, pi = [], pi_of(th)
    while len(out) < n:
        d = rng.uniform(0.80, 0.99, 64)
        p = solve_p(d) @ pi                      # current policy's pass rate
        ok = (rng.binomial(8, p) == 0) & (rng.binomial(512, p) > 0)
        out += list(d[ok])
    return np.array(out[:n])

rng = np.random.default_rng(0)
D_eval = rng.uniform(0.65, 0.97, 400)            # a hard, "AIME-like" eval set
acc = lambda th: float((solve_p(D_eval) @ pi_of(th)).mean())

th = THETA0.copy()
for _ in range(100):                             # stage 1: moderate, G=16, 32 prompts
    th, _ = rl_step(th, rng, moderate(rng, 32), 16, 0.5)
print(f"after stage 1: eval accuracy {acc(th):.3f}, policy {np.round(pi_of(th), 3)}")

arms = {"A moderate G=16 x32": th.copy(), "B extreme G=512 x1": th.copy(), "C extreme G=16 x32": th.copy()}
rngs = {k: np.random.default_rng(1) for k in arms}
print("\nstep  " + "  ".join(f"{k:>19s}" for k in arms) + "   (eval accuracy / zero-var share)")
for step in range(1, 201):
    zv = {}
    for k in arms:
        r_ = rngs[k]
        if k.startswith("A"):   d, G = moderate(r_, 32), 16
        elif k.startswith("B"): d, G = extreme(r_, arms[k], 1), 512
        else:                   d, G = extreme(r_, arms[k], 32), 16
        arms[k], zv[k] = rl_step(arms[k], r_, d, G, 1.0)
    if step % 40 == 0:
        print(f"{step:4d}  " + "  ".join(f"{acc(arms[k]):11.3f} / {zv[k]:4.2f}" for k in arms))
print("\nfinal policy of B", np.round(pi_of(arms["B extreme G=512 x1"]), 3))
 

A stops at its post-stage-1 level: the policy has converged on the 0.70 strategy, and on moderate problems the 0.85 and 0.95 strategies rarely get a chance to look better. C uses the same problems and the same rollout budget, yet more than 80% of its groups are all-zero and it learns almost nothing for about 150 steps before it finally starts. B catches the rare successes of strong strategies among 512 samples and moves to the 0.95 strategy within about 100 steps (its zero-var share is 0). That matches Fig. 5: AIME’24 Avg@32 was 81.8% at the end of stage 1; the run that switched reached 83.4%, the one that did not plateaued. B needs tens of steps to take off because the 0.85 and 0.95 strategies were already down to about 0.1% probability after stage 1. This is why hard problems help little once entropy has collapsed — the problem dynamic temperature targets.

2. Dynamic sampling temperature

As RL proceeds the policy sharpens (entropy falls), so samples become less diverse at the same temperature; a fixed temperature under-explores late in training. GLM-4.5’s rule has two parts: when the average reward plateaus it is time to raise the temperature, and how far is decided on a validation set:

Tnext=max⁡{T : Acc⁡val(T) ≥ max⁡T′Acc⁡val(T′)−δ},δ=1%T_{\text{next}}=\max\Big\{T\ :\ \operatorname{Acc}_{\text{val}}(T)\ \ge\ \max_{T'}\operatorname{Acc}_{\text{val}}(T')-\delta\Big\},\qquad \delta=1\%

The report does not say whether “no more than 1% drop” means percentage points or a relative 1%; the figure uses points.

그림의 숫자에서 하나 더 읽을 것이 있다. rollout 1,000개당 신호 그룹 수는 극난도 풀(G=512) 쪽이 훨씬 적다. 같은 rollout 예산이라면 중간 난이도 문제가 gradient를 더 많이 만든다. 2단계의 가치는 신호의 양이 아니라 종류에 있다. 중간 난이도 문제로는 구분되지 않는 “더 강한 풀이 전략”이 극난도 문제에서만 보상을 받는다. 아래 장난감에서 그것을 확인한다.

확인 문제Check yourself

2단계용으로 고른 문제(pass@8 = 0, pass@512 > 0)를 1단계와 같은 프롬프트당 16 샘플로 학습하면 가장 가능성이 높은 결과는?

이 문제들은 정의상 8번 뽑아 한 번도 못 맞힌 문제다. 정답률이 p≈0.002p\approx 0.002–0.050.05 수준이면 G=16G=16에서 그룹이 전부 0일 확률 (1−p)16(1-p)^{16}이 0.45–0.97이다. 신호를 얻으려면 그룹을 키워야 하고, 그래서 GLM-4.5는 2단계에서 프롬프트당 512개를 뽑았다.

장난감 RLVR로 Fig. 5의 모양을 재현해 본다. 정책은 실력이 다른 여섯 가지 풀이 전략 위의 분포다. 1단계에서 중간 난이도 문제로 학습한 뒤, (A) 같은 데이터로 계속, (B) 선별 조건을 통과한 극난도 문제로 G=512, (C) 같은 극난도 문제를 G=16으로 학습한다. 세 갈래 모두 step당 rollout 512개로 예산이 같다.

NumPy 2단계 난이도 curriculum 장난감
import numpy as np

SKILL  = np.array([0.10, 0.30, 0.50, 0.70, 0.85, 0.95])   # 풀이 전략별 실력
THETA0 = np.array([1.0, 1.5, 1.5, 0.5, -1.0, -2.0])       # base 정책: 약한 전략 선호
sig = lambda z: 1 / (1 + np.exp(-z))

def pi_of(th):
    e = np.exp(th - th.max()); return e / e.sum()

def solve_p(d):                                  # (B, S): 문제 난이도 d, 전략 s의 정답 확률
    return sig(25 * (SKILL[None, :] - d[:, None]))

def rl_step(th, rng, d, G, lr):
    """GRPO (KL 없음): 그룹 정규화 advantage로 전략 logit을 갱신."""
    pi, B = pi_of(th), len(d)
    s = np.minimum(np.searchsorted(np.cumsum(pi), rng.random((B, G))), len(th) - 1)
    r = (rng.random((B, G)) < solve_p(d)[np.arange(B)[:, None], s]).astype(float)
    std = r.std(1, keepdims=True)
    A = (r - r.mean(1, keepdims=True)) / (std + 1e-6)
    grad = (A[..., None] * (np.eye(len(th))[s] - pi)).sum((0, 1)) / (B * G)
    return th + lr * grad, (std[:, 0] == 0).mean()          # 갱신된 θ, zero-variance 비율

def moderate(rng, B):                            # 중간 난이도 풀
    return rng.uniform(0.30, 0.74, B)

def extreme(rng, th, n):                         # pass@8 = 0 이고 pass@512 > 0 인 문제만
    out, pi = [], pi_of(th)
    while len(out) < n:
        d = rng.uniform(0.80, 0.99, 64)
        p = solve_p(d) @ pi                      # 현재 정책의 정답률
        ok = (rng.binomial(8, p) == 0) & (rng.binomial(512, p) > 0)
        out += list(d[ok])
    return np.array(out[:n])

rng = np.random.default_rng(0)
D_eval = rng.uniform(0.65, 0.97, 400)            # "AIME 같은" 어려운 평가셋
acc = lambda th: float((solve_p(D_eval) @ pi_of(th)).mean())

th = THETA0.copy()
for _ in range(100):                             # 1단계: 중간 난이도, G=16, 프롬프트 32개
    th, _ = rl_step(th, rng, moderate(rng, 32), 16, 0.5)
print(f"1단계 후 평가 정확도 {acc(th):.3f}, 정책 {np.round(pi_of(th), 3)}")

arms = {"A 중간 G=16 x32": th.copy(), "B 극난 G=512 x1": th.copy(), "C 극난 G=16 x32": th.copy()}
rngs = {k: np.random.default_rng(1) for k in arms}
print("\nstep  " + "  ".join(f"{k:>17s}" for k in arms) + "   (평가 정확도 / zero-var 비율)")
for step in range(1, 201):
    zv = {}
    for k in arms:
        r_ = rngs[k]
        if k.startswith("A"):   d, G = moderate(r_, 32), 16
        elif k.startswith("B"): d, G = extreme(r_, arms[k], 1), 512
        else:                   d, G = extreme(r_, arms[k], 32), 16
        arms[k], zv[k] = rl_step(arms[k], r_, d, G, 1.0)
    if step % 40 == 0:
        print(f"{step:4d}  " + "  ".join(f"{acc(arms[k]):9.3f} / {zv[k]:4.2f}" for k in arms))
print("\nB 최종 정책", np.round(pi_of(arms["B 극난 G=512 x1"]), 3))
 

A는 1단계 직후 수준에서 멈춘다. 정책이 실력 0.70 전략으로 수렴했고, 중간 난이도 문제에서는 0.85·0.95 전략이 0.70보다 나을 기회가 거의 없다. C는 같은 문제, 같은 rollout 예산인데도 그룹의 80% 이상이 전부 0점이라 150 step 가까이 거의 배우지 못하다가 뒤늦게 출발한다. B는 512개 중 드물게 나오는 강한 전략의 성공을 붙잡아 100 step 안팎에서 0.95 전략으로 옮겨 간다(B의 zero-var 비율은 0이다). 보고서 Fig. 5에서 1단계 끝 81.8%였던 AIME’24 Avg@32가 2단계로 바꾼 쪽은 83.4%까지 오르고, 바꾸지 않은 쪽은 정체한 것과 같은 모양이다. 장난감에서 B가 출발하는 데 수십 step이 걸리는 것은 0.85·0.95 전략의 확률이 1단계에서 이미 0.1% 수준으로 줄었기 때문이다. 이것이 entropy가 무너진 뒤에는 어려운 문제를 넣어도 탐색이 잘 안 되는 이유이고, 아래 동적 temperature가 겨냥하는 문제다.

2. 동적 sampling temperature

RL이 진행되면 정책이 뾰족해져(entropy 감소) 같은 temperature에서도 샘플 다양성이 줄어든다. 고정 temperature는 후반에 탐색이 부족해진다. GLM-4.5의 규칙은 두 부분이다. 평균 보상이 정체되면(수렴 구간) temperature를 올릴 때가 된 것이고, 얼마나 올릴지는 검증셋으로 정한다.

Tnext=max⁡{T : Acc⁡val(T) ≥ max⁡T′Acc⁡val(T′)−δ},δ=1%T_{\text{next}}=\max\Big\{T\ :\ \operatorname{Acc}_{\text{val}}(T)\ \ge\ \max_{T'}\operatorname{Acc}_{\text{val}}(T')-\delta\Big\},\qquad \delta=1\%

보고서의 “1% 넘게 떨어지지 않는”이 퍼센트 포인트인지 상대 1%인지는 명시되지 않았다. 아래 그림은 포인트로 해석했다.

최적best T –선택된chosen T* –정확도accuracy(T*) – entropy: T* – / T=1 –
가상의 검증셋(문제 300개, 후보 답 12개)에서 정책의 logit 크기가 학습과 함께 커지는(=분포가 뾰족해지는) 장난감이다. entropy가 너무 낮은 sampling은 반복·퇴화로 정답률이 떨어지는 항을 넣어 최적 T가 내부에 생기게 했다. 왼쪽은 sampling temperature T별 검증 정확도, 세로 점선이 규칙으로 고른 T* = "정확도가 최적보다 δ 포인트 넘게 떨어지지 않는 최대 T"다. t를 끌면 곡선의 평평한 구간이 넓어져 T*가 오른쪽으로 간다. 오른쪽 그림은 t 전체에 걸친 T*(빨강)와, 그 T*에서의 entropy(초록 실선) 대 T=1 고정일 때 entropy(초록 점선)다. 고정 temperature는 학습 후반에 탐색이 말라 버리지만, 규칙은 entropy를 일정 수준에서 붙잡는다. A toy validation set (300 problems, 12 candidate answers each) whose logits grow in scale as training proceeds (the policy sharpens). Sampling at very low entropy is penalised (repetition, degenerate loops), which gives an interior optimal T. Left: validation accuracy versus sampling temperature T; the dashed line is the rule's choice T* = "the largest T whose accuracy is within δ points of the best". Drag t: the flat part of the curve widens and T* moves right. Right: T* over the whole run (red), the entropy at that T* (solid green) versus the entropy at a fixed T=1 (dashed green). A fixed temperature lets exploration dry up late in training; the rule holds the entropy roughly constant.

If sharpening were pure scaling of all logits by cc, then softmax⁡(cz/T)\operatorname{softmax}(cz/T) depends only on T/cT/c: the accuracy curve stretches horizontally by cc, the rule’s T∗T^\ast scales by cc, and the entropy at T∗T^\ast stays about the same throughout training. The rule is therefore a device that keeps the sampling entropy roughly constant at almost no cost in validation accuracy. It belongs to the same family as the temperature adjustment in Polaris (report reference [2]).

3. What the loss looks like: agent trajectories, format penalty, token aggregation

Finally, the agentic RL loss at token level. A trajectory mixes model and environment tokens; a malformed tool call stops it with reward 0. We compare token-weighted and sequence-mean aggregation.

NumPy Loss weights of agent trajectories: environment mask, format penalty, aggregation
import numpy as np

# a trajectory = [(kind, n_tokens)]; kind: 'gen' (model), 'obs' (tool result), 'bad' (malformed tool call)
trajs = [
    [("gen", 120), ("obs", 800), ("gen", 60), ("obs", 300), ("gen", 40)],   # success
    [("gen", 200), ("obs", 900), ("gen", 150)],                              # failure (tests fail)
    [("gen", 90), ("bad", 30), ("obs", 500), ("gen", 400)],                  # format error -> halted
    [("gen", 300), ("obs", 1200), ("gen", 250), ("obs", 700), ("gen", 80)],  # success
]
outcome = np.array([1.0, 0.0, 1.0, 1.0])   # environment outcome (no. 3 would have succeeded)

def rollout_view(traj):
    """On a malformed call keep tokens up to it and give reward 0 (process format penalty)."""
    kept, halted = [], False
    for kind, n in traj:
        kept.append((kind, n))
        if kind == "bad":
            halted = True
            break
    mask = np.concatenate([np.full(n, kind != "obs", float) for kind, n in kept])  # drop env tokens
    return mask, halted

masks, rewards = [], []
for tr, r in zip(trajs, outcome):
    m, halted = rollout_view(tr)
    masks.append(m); rewards.append(0.0 if halted else r)
rewards = np.array(rewards)
A = rewards - rewards.mean()                      # the report's form: r - mean(r), no std
print("rewards", rewards, " advantage", np.round(A, 3))

n_gen = np.array([m.sum() for m in masks]); n_all = np.array([len(m) for m in masks])
print("model tokens / all tokens:", n_gen.astype(int), "/", n_all)

K = len(masks)
w_seq = A / (K * n_gen)                           # sequence-mean: token mean per trajectory
w_tok = A / n_gen.sum()                           # token-weighted mean: over all model tokens
for name, w in [("sequence-mean", w_seq), ("token-weighted", w_tok)]:
    print(f"{name:15s} per-token coef {np.round(w * 1e3, 3)} (x1e-3) | per-trajectory total {np.round(w * n_gen, 3)}")
print("\nNote: with sequence-mean a token of the long failure (no. 2) is penalised",
      f"{abs(w_seq[1]) / abs(w_seq[2]):.2f}x as much as a token of the short malformed trajectory.")
 

With the token-weighted mean every model token gets a coefficient of the same size, and a trajectory’s total influence grows with the number of tokens it generated. With sequence-mean every trajectory gets the same total and the per-token coefficient shrinks as 1/∣yi∣1/|y_i|. That is why the report found token-weighted loss converging faster for code RL and suppressing “overly simplistic or repetitive base-case samples”.

PyTorch PyTorch: GLM-4.5-style RL loss (no KL, token-weighted, environment mask) 로컬에서 실행run locally (pip install torch)
import torch

def glm45_rl_loss(logp, old_logp, rewards, gen_mask, group_size,
                  eps_low=0.2, eps_high=0.2, std_norm=True, agg="token"):
    """
    logp, old_logp: (N, T) per-token log π_θ, log π_old   (N = B * group_size)
    rewards:        (N,)   outcome reward (already 0 for trajectories halted by a format error)
    gen_mask:       (N, T) 1 for model-generated tokens, 0 for prompt / tool results / padding
    The report does not give ε or the group size; defaults are placeholders.
    """
    r = rewards.view(-1, group_size)
    adv = r - r.mean(dim=1, keepdim=True)
    if std_norm:                                   # Reasoning RL (GRPO); the agentic form is r - mean, no std
        adv = adv / (r.std(dim=1, keepdim=True) + 1e-6)
    adv = adv.view(-1, 1)                          # same advantage for every token of a trajectory

    ratio = torch.exp(logp - old_logp)
    surr = torch.minimum(ratio * adv, ratio.clamp(1 - eps_low, 1 + eps_high) * adv)
    m = gen_mask.float()
    if agg == "token":                             # token-weighted mean (code RL)
        return -(surr * m).sum() / m.sum().clamp(min=1)
    # sequence-mean: token mean per trajectory, then mean
    return -((surr * m).sum(1) / m.sum(1).clamp(min=1)).mean()

def format_penalty(tool_calls_ok: torch.Tensor, outcome: torch.Tensor):
    """tool_calls_ok: (N,) whether every tool call in the trajectory was well-formed; any failure -> 0."""
    return outcome * tool_calls_ok.float()
 

Results

Twelve ARC benchmarks

The report claims third place overall (second on agentic tasks) on 12 benchmarks: agentic (TAU-bench, BFCL V3, BrowseComp), reasoning (MMLU-Pro, AIME 24, MATH-500, SciCode, GPQA, HLE, LiveCodeBench) and coding (SWE-bench Verified, Terminal-Bench) (Fig. 1, as of July 28, 2025).

정책의 logit 전체가 cc배 커지는 순수한 sharpening이라면 softmax⁡(cz/T)\operatorname{softmax}(cz/T)는 T/cT/c의 함수이므로 정확도 곡선이 가로로 cc배 늘어나고, 규칙이 고른 T∗T^\ast도 cc배가 된다. 그러면 T∗T^\ast에서의 entropy는 학습 내내 거의 같다. 규칙은 결국 “검증 정확도를 거의 잃지 않는 한도에서 sampling entropy를 일정하게 유지” 하는 장치다. Polaris(보고서 참고문헌 [2])의 temperature 조정과 같은 계열이다.

3. 손실의 실제 모양: agent 궤적, 형식 벌점, 토큰 집계

마지막으로 agentic RL 손실을 토큰 단위로 써 본다. 궤적은 모델 토큰과 환경 토큰이 섞여 있고, 형식이 틀린 tool 호출이 나오면 거기서 잘리고 보상이 0이다. 집계는 token-weighted mean과 sequence-mean을 비교한다.

NumPy agent 궤적의 손실 가중치: 환경 토큰 mask, 형식 벌점, 집계 방식
import numpy as np

# 궤적 = [(종류, 토큰 수)], 종류: 'gen'(모델 생성), 'obs'(tool 결과), 'bad'(형식 오류 tool 호출)
trajs = [
    [("gen", 120), ("obs", 800), ("gen", 60), ("obs", 300), ("gen", 40)],   # 성공
    [("gen", 200), ("obs", 900), ("gen", 150)],                              # 실패 (테스트 미통과)
    [("gen", 90), ("bad", 30), ("obs", 500), ("gen", 400)],                  # 형식 오류 → 중단
    [("gen", 300), ("obs", 1200), ("gen", 250), ("obs", 700), ("gen", 80)],  # 성공
]
outcome = np.array([1.0, 0.0, 1.0, 1.0])   # 환경이 준 결과 (3번은 원래 성공했을 궤적이라 가정)

def rollout_view(traj):
    """형식 오류가 나오면 그 토큰까지만 남기고 보상 0 (process format penalty)."""
    kept, halted = [], False
    for kind, n in traj:
        kept.append((kind, n))
        if kind == "bad":
            halted = True
            break
    mask = np.concatenate([np.full(n, kind != "obs", float) for kind, n in kept])  # 환경 토큰 제외
    return mask, halted

masks, rewards = [], []
for tr, r in zip(trajs, outcome):
    m, halted = rollout_view(tr)
    masks.append(m); rewards.append(0.0 if halted else r)
rewards = np.array(rewards)
A = rewards - rewards.mean()                      # 보고서 식: r - mean(r), std 정규화 없음
print("보상", rewards, " advantage", np.round(A, 3))

n_gen = np.array([m.sum() for m in masks]); n_all = np.array([len(m) for m in masks])
print("모델 토큰 / 전체 토큰:", n_gen.astype(int), "/", n_all)

K = len(masks)
w_seq = A / (K * n_gen)                           # sequence-mean: 궤적마다 토큰 평균
w_tok = A / n_gen.sum()                           # token-weighted mean: 그룹의 모델 토큰 전체로 평균
for name, w in [("sequence-mean", w_seq), ("token-weighted", w_tok)]:
    print(f"{name:15s} 토큰당 계수 {np.round(w * 1e3, 3)} (x1e-3) | 궤적 총합 {np.round(w * n_gen, 3)}")
print("\n관찰: sequence-mean에서는 긴 실패 궤적(2번)의 토큰 하나가 받는 벌이",
      f"{abs(w_seq[1]) / abs(w_seq[2]):.2f}배로 짧은 형식 오류 궤적보다 작다.")
 

token-weighted mean에서는 모든 모델 토큰이 같은 크기의 계수를 받고, 궤적 하나의 총 영향은 생성한 토큰 수에 비례한다. sequence-mean에서는 궤적마다 총합이 같고 토큰당 계수가 1/∣yi∣1/|y_i|로 작아진다. 보고서가 코드 RL에서 token-weighted가 수렴이 빠르고 “지나치게 단순하거나 반복적인 base case 샘플”을 억제했다고 쓴 것은 이 차이 때문이다.

PyTorch PyTorch: GLM-4.5 스타일 RL 손실 (KL 없음, token-weighted, 환경 토큰 mask) 로컬에서 실행run locally (pip install torch)
import torch

def glm45_rl_loss(logp, old_logp, rewards, gen_mask, group_size,
                  eps_low=0.2, eps_high=0.2, std_norm=True, agg="token"):
    """
    logp, old_logp: (N, T) 각 토큰의 log π_θ, log π_old   (N = B * group_size)
    rewards:        (N,)   결과 보상 (형식 오류로 중단된 궤적은 이미 0)
    gen_mask:       (N, T) 모델이 생성한 토큰 = 1, 프롬프트·tool 결과·padding = 0
    보고서는 ε 값과 group 크기를 밝히지 않는다. 기본값은 자리표시자.
    """
    r = rewards.view(-1, group_size)
    adv = r - r.mean(dim=1, keepdim=True)
    if std_norm:                                   # Reasoning RL (GRPO). agentic 식은 std 없이 r - mean
        adv = adv / (r.std(dim=1, keepdim=True) + 1e-6)
    adv = adv.view(-1, 1)                          # 궤적의 모든 토큰에 같은 advantage

    ratio = torch.exp(logp - old_logp)
    surr = torch.minimum(ratio * adv, ratio.clamp(1 - eps_low, 1 + eps_high) * adv)
    m = gen_mask.float()
    if agg == "token":                             # token-weighted mean (코드 RL)
        return -(surr * m).sum() / m.sum().clamp(min=1)
    # sequence-mean: 궤적마다 토큰 평균 후 평균
    return -((surr * m).sum(1) / m.sum(1).clamp(min=1)).mean()

def format_penalty(tool_calls_ok: torch.Tensor, outcome: torch.Tensor):
    """tool_calls_ok: (N,) 궤적의 모든 tool 호출이 형식에 맞았는지. 하나라도 틀리면 보상 0."""
    return outcome * tool_calls_ok.float()
 

실험 결과

ARC 벤치마크 12종

보고서는 agentic(TAU-bench, BFCL V3, BrowseComp), 추론(MMLU-Pro, AIME 24, MATH-500, SciCode, GPQA, HLE, LiveCodeBench), 코딩(SWE-bench Verified, Terminal-Bench) 12개로 종합 3위(agentic 2위)라고 주장한다(Fig. 1, 2025년 7월 28일 기준).

출처Source: GLM-4.5 report, Tables 3–5
분야와 벤치마크를 바꿔 보면 같은 모델이라도 어디서 앞서고 어디서 뒤지는지가 바로 보인다. 색 막대가 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.

What to read:

  • Strong on agentic tasks, weaker on knowledge and top-end reasoning. BFCL V3 is the best in the comparison (77.8) and TAU-bench is at Claude Sonnet 4’s level. HLE (14.4) and GPQA (79.1) are clearly below o3, Gemini 2.5 Pro and Grok 4.
  • o3 dominates BrowseComp (49.7); GLM-4.5 (26.4) is near o4-mini (28.3) but above Claude Opus 4 (18.8).
  • SWE-bench Verified 64.2 uses OpenHands v0.34.0, at most 100 iterations, 128K context and temperature 0.6. The table does not say whether the other models were measured with the same harness.

Base model (Table 2, excerpt)

Qwen3-235B-A22BDeepSeek-V3Kimi K2GLM-4.5
MMLU (EM)87.887.287.886.1
BBH (EM)88.988.488.786.2
SimpleQA (EM)–26.635.330.0
EvalPlus (Pass@1)77.665.680.378.1
LiveCodeBench-Base–24.626.328.1
GSM8K (EM)94.487.692.179.4
MATH (EM)71.862.670.261.0

At the base-model stage GLM-4.5 matches or beats the others on code but is clearly lower on GSM8K and MATH. Reaching 91.0 on AIME 24 after post-training suggests that much of its reasoning comes after mid-training (synthetic reasoning data, expert RL). GLM-4.5-Base is “the last pre-training checkpoint, not trained on instruction data”, scored with an internal evaluation framework.

Ablations behind the methods

Experiment (smaller model)ComparisonResultSource
Two-stage curriculumstage 2 on extreme problems (512 samples) vs staying on moderate ones (16 samples)AIME’24 Avg@32: 81.8% → 83.4% vs plateauFig. 5
Output lengthsingle stage at 64K vs 16K→32K→48K→64K83.4% vs 80.6%Fig. 6
Code RL losstoken-weighted vs sequence-meanLiveCodeBench 46.5% at ≈1,750 steps vs 46.3% at ≈2,550 stepsFig. 7 left
Science RL dataexpert-verified multiple choice only vs mixed qualitybest GPQA 65.8% vs 62.9%Fig. 7 right
SFT prompt selectiondrop bottom 50% by response lengthmaths & science +2–4% (half the data)§3.1
Response scalingfour responses per hard promptanother +1–2%§3.1

Human evaluations

  • CC-Bench (52 coding tasks on Claude Code, experts interacting over several rounds): GLM-4.5 vs Claude Sonnet 4 wins 40.4% / ties 9.6% / loses 50.0%; vs Kimi K2 53.9 / 17.3 / 28.8; vs Qwen3-Coder 80.8 / 7.7 / 11.5. Tool-call success is 90.6% for GLM-4.5, above Claude Sonnet 4’s 89.5% (Figs. 12–13).
  • General chat (660 real prompts, 0–10 scores by one evaluator in random order): English 8.66 vs DeepSeek-R1-0528 8.62 vs Kimi K2 8.13 (Table 8).
  • SafetyBench average 89.9, close to Kimi K2 (90.5) and GPT-4.1 (89.7); weakest on Unfairness & Bias (77.4) (Table 7).

Reading critically

  • The ablations are not on GLM-4.5. All curves in §3.2 come from a “smaller experimental model” of undisclosed size. The architecture claims about depth and head count have no table.
  • RL hyper-parameters are missing. No clip range, group size (beyond the 16/512 of the curriculum), learning rate or step count, and nothing on what replaced the KL term for stability. To reproduce, read the slime code and the GLM-5 report (next lesson, where ε values finally appear).
  • The merge is under-specified. No ratio of thinking to direct data in the Overall SFT, no per-expert weights, no statement of whether RL is run again after merging and in which order, and no numbers on how much of each expert survives the merge.
  • No data mixture. Stage totals (15T / 7T / 500B / 500B / 100B) are given, but not the web / code / maths / multilingual proportions.
  • Evaluation settings differ. TAU-bench uses a user-simulator prompt modified by the GLM team (Fig. 11). HLE is graded by GPT-4o, AIME is Avg@32, GPQA Avg@8. Whether competitor numbers were re-measured under the same settings or copied from public reports is not always clear. CC-Bench and the chat evaluation are internal and human-in-the-loop, hard to reproduce (trajectories are public).
  • Contamination. There is no decontamination section. Building new logic problems (Table 11) is a partial answer.
확인 문제Check yourself

Why did GLM-4.5 run single-stage RL at 64K from the start instead of growing the output length 16K → 32K → 48K → 64K?

SFT had already taught 64K-length responses, so RL with a shorter maximum length penalises long responses through truncation and the average output length drops. The report says this caused an irreversible performance loss that the final 64K stage could not recover (Fig. 6: 80.6% vs 83.4%). A length curriculum is a remedy for starting from a short model; it may not fit when the starting point is already a long-CoT model.

Summary

  • GLM-4.5 is a 355B/32B MoE built narrower and deeper than DeepSeek-V3 and Kimi K2 (hidden 5120, 89 MoE layers, expert FFN 1536) with 96 heads, justified by internal observations on reasoning benchmarks.
  • After pre-training (15T + 7T at 4K), mid-training (repo code 500B and synthetic reasoning 500B at 32K, long context & agent 100B at 128K) loads the ingredients post-training will need. Optimizer Muon, cosine learning rate.
  • Post-training grows Reasoning, Agent and General experts separately with RL and fine-tunes one hybrid-thinking model on their rejection-sampled outputs.
  • Reasoning RL is KL-free GRPO plus a two-stage difficulty curriculum (pass@8=0, pass@512>0, 512 samples), single-stage 64K, dynamic temperature and token-weighted loss — all ways to keep reward variance inside groups.
  • Agentic RL uses outcome rewards with zero reward on malformed tool calls, environment-token masking and an RL ↔ self-distillation loop; slime runs reasoning RL synchronously colocated and agent RL asynchronously disaggregated.

읽을 점:

  • agentic은 강하고 지식·최상위 추론은 약하다. BFCL V3는 비교군 최고(77.8), TAU-bench는 Claude Sonnet 4 수준이다. 반면 HLE(14.4)·GPQA(79.1)는 o3·Gemini 2.5 Pro·Grok 4보다 확연히 낮다.
  • BrowseComp은 o3가 압도적(49.7)이고 GLM-4.5(26.4)는 o4-mini(28.3) 근처다. 그래도 Claude Opus 4(18.8)보다는 높다.
  • SWE-bench Verified 64.2는 OpenHands v0.34.0, 최대 100 iteration, 128K 문맥, temperature 0.6 설정이다. 다른 모델의 점수가 같은 harness에서 측정된 것인지는 표에 표시되어 있지 않다.

Base 모델 (Table 2, 일부)

Qwen3-235B-A22BDeepSeek-V3Kimi K2GLM-4.5
MMLU (EM)87.887.287.886.1
BBH (EM)88.988.488.786.2
SimpleQA (EM)–26.635.330.0
EvalPlus (Pass@1)77.665.680.378.1
LiveCodeBench-Base–24.626.328.1
GSM8K (EM)94.487.692.179.4
MATH (EM)71.862.670.261.0

base 모델 단계에서 GLM-4.5는 코드는 비교군과 비슷하거나 낫지만 GSM8K·MATH는 눈에 띄게 낮다. 사후학습 후 AIME 24 91.0이 나온다는 것은 추론 능력의 상당 부분이 mid-training 이후(합성 추론 데이터, expert RL)에서 온다는 뜻으로 읽힌다. GLM-4.5-Base는 “instruction 데이터로 학습하지 않은 사전학습 마지막 체크포인트”이고, 점수는 내부 평가 프레임워크로 냈다.

방법을 뒷받침하는 ablation

실험 (작은 실험 모델)비교결과출처
2단계 curriculum2단계에서 극난도(512 샘플) vs 중간 난이도 유지(16 샘플)AIME’24 Avg@32: 81.8% → 83.4% vs 정체Fig. 5
출력 길이64K 단일 단계 vs 16K→32K→48K→64K83.4% vs 80.6%Fig. 6
코드 RL 손실token-weighted vs sequence-meanLiveCodeBench 46.5%에 약 1,750 step vs 46.3%에 약 2,550 stepFig. 7 왼쪽
과학 RL 데이터전문가 검증 객관식만 vs 품질 혼합GPQA 최고 65.8% vs 62.9%Fig. 7 오른쪽
SFT 프롬프트 선별응답 길이 하위 50% 제거수학·과학 +2–4% (데이터 절반)§3.1
response scaling어려운 프롬프트마다 응답 4개추가 +1–2%§3.1

사람이 본 평가

  • CC-Bench (Claude Code 위 52개 코딩 과제, 전문가가 여러 라운드 상호작용): GLM-4.5 대 Claude Sonnet 4는 승 40.4% / 무 9.6% / 패 50.0%, 대 Kimi K2는 53.9 / 17.3 / 28.8, 대 Qwen3-Coder는 80.8 / 7.7 / 11.5. tool 호출 성공률은 GLM-4.5 90.6%로 Claude Sonnet 4(89.5%)보다 높다(Fig. 12–13).
  • 일반 대화 (660개 실제 프롬프트, 0–10점, 한 평가자가 무작위 순서로 채점): 영어 8.66 vs DeepSeek-R1-0528 8.62 vs Kimi K2 8.13 (Table 8).
  • SafetyBench 평균 89.9로 Kimi K2(90.5)·GPT-4.1(89.7)과 비슷하고, Unfairness & Bias(77.4)가 가장 약하다(Table 7).

비판적으로 읽기

  • ablation이 GLM-4.5가 아니다. §3.2의 곡선은 모두 “더 작은 실험 모델”의 것이고 그 크기는 밝히지 않는다. 깊이·head 수에 대한 구조 주장은 표 없이 서술뿐이다.
  • RL 하이퍼파라미터가 없다. clip 범위, group 크기(curriculum의 16/512 외), 학습률, step 수, KL을 뺀 대신 무엇으로 안정성을 지켰는지 나오지 않는다. 재현하려면 slime 코드와 GLM-5 보고서(다음 레슨, 여기에 처음으로 ε\varepsilon 값이 나온다)를 함께 봐야 한다.
  • expert 통합의 세부가 비어 있다. Overall SFT에서 thinking/direct 데이터 비율, expert별 비중, 통합 후 RL을 다시 했는지와 그 순서를 그림으로 명시하지 않는다. 통합 과정에서 각 expert 능력이 얼마나 보존되었는지도 수치가 없다.
  • 데이터 구성비가 없다. 15T/7T/500B/500B/100B라는 단계별 총량은 있지만 웹·코드·수학·다국어의 혼합비는 없다.
  • 평가 설정 차이. TAU-bench는 GLM 팀이 고친 user simulator 프롬프트(Fig. 11)를 썼다. HLE는 GPT-4o 채점, AIME는 Avg@32, GPQA는 Avg@8이다. 비교 모델 점수가 같은 설정에서 다시 잰 것인지, 공개 수치를 가져온 것인지는 표마다 명확하지 않다. CC-Bench와 일반 대화 평가는 사람이 상호작용하거나 채점하는 내부 평가라 재현이 어렵다(궤적은 공개).
  • 오염 점검. 별도의 decontamination 절이 없다. 새 논리 문제(Table 11)를 직접 만든 것은 이 걱정에 대한 부분적인 대응이다.
확인 문제Check yourself

GLM-4.5가 출력 길이를 16K→32K→48K→64K로 늘려 가는 다단계 RL 대신 처음부터 64K 단일 단계 RL을 택한 이유로 보고서가 든 것은?

SFT가 이미 64K 길이의 응답을 학습시켰기 때문에, 짧은 최대 길이로 RL을 하면 잘림 때문에 긴 응답이 벌을 받고 평균 출력 길이가 줄어든다. 보고서는 이것이 되돌리기 어려운 성능 하락을 만들었고 마지막 64K 단계에서도 회복되지 않았다고 쓴다(Fig. 6: 80.6% vs 83.4%). 다단계 길이 curriculum은 짧은 모델에서 시작할 때의 처방이고, 출발점이 이미 긴 CoT 모델이면 맞지 않을 수 있다.

정리

  • GLM-4.5는 355B/32B MoE로, DeepSeek-V3·Kimi K2보다 좁고 깊게(hidden 5120, 89 MoE 층, expert FFN 1536) 만들고 head를 96개로 늘렸다. 근거는 추론 벤치마크에서의 내부 관찰이다.
  • 사전학습(15T + 7T, 4K) 뒤 mid-training(repo 코드 500B·합성 추론 500B @32K, 긴 문맥·agent 100B @128K)으로 사후학습이 쓸 능력의 재료를 미리 넣는다. 옵티마이저는 Muon, 학습률은 cosine.
  • 사후학습은 Reasoning·Agent·General expert를 따로 RL로 키우고 rejection sampling한 출력으로 하나의 hybrid thinking 모델을 SFT한다.
  • Reasoning RL은 KL 없는 GRPO 위에 2단계 난이도 curriculum(pass@8=0, pass@512>0 + 512 샘플), 64K 단일 단계, 동적 temperature, token-weighted 손실을 얹었다. 모두 그룹 안의 보상 분산을 지키는 장치다.
  • Agentic RL은 결과 보상 + 형식 오류 즉시 0점, 환경 토큰 mask, RL ↔ self-distillation 반복이다. 인프라 slime은 추론 RL은 동기 colocated, agent RL은 비동기 disaggregated로 돌린다.

더 읽을거리Further reading