GLM-5.4: Toward Generalized Coding with Our First Loop Transformer

algorithm blog-glm-5-4
loop-transformerweight-tyingcontinued-trainingkv-cachetest-time-compute

GLM-5.4 — Loop Transformer at 750B via Continued Training #

1. TL;DR #

GLM-5.4 converts a pre-trained GLM-5 base into a Loop Transformer: 28 middle layers re-execute for 2 weight-shared iterations, buying 2T–3T-class reasoning at a fixed parameter count. Three fixes — gated residual writes, hybrid KV sharing, sparse-index reuse — make the extra loop nearly free at 750B/1M context.

2. Q1 / Q2 / Q3 #

Q1 — 痛点 (problem) #

Z.ai separates two capability axes: memory-intensive tasks reward more parameters, while reasoning-intensive tasks reward more effective compute. The target workloads — large-scale software engineering, cybersecurity, 3D modeling, physical control — are ultra-long-chain reasoning: they demand following multi-step causal chains while preserving global logical consistency. Stacking parameters and memorizing more data does not close this gap, because the bottleneck is sequential compute depth, not stored knowledge. The naive remedy (train a 2T–3T dense/MoE model) is prohibitively expensive to train and serve.

Q2 — 方法 (method) #

Add depth without adding parameters by looping a weight-tied block. Formally, let the shared loop block be a function $f_\theta$ applied to the residual-stream hidden state $h$. A standard stack applies $f$ once; the Loop Transformer applies the same $f_\theta$ for $T$ iterations, refining $h$ in place:

$$h^{(t)} = h^{(t-1)} + g^{(t)} \odot f_\theta\!\left(h^{(t-1)}\right), \quad t = 1 \dots T$$

with $T=2$ and $g^{(t)}$ a learned per-token gate for iteration $t$. The decisive engineering choice is not to train looped-from-scratch (which underperforms an unshared model at equal pre-training compute) but to adapt an already pre-trained base into looped form via continued training, lifting the intelligence ceiling for ~10% extra compute.

The 核心技术壁垒 (single hardest-to-replicate insight): making the loop free to serve. A naive loop multiplies both KV-cache memory and sparse-attention indexing by $T$. GLM-5.4 collapses that overhead — the second loop reuses the first loop's sparse KV selection plus one sliding window of fresh KV, and reuses the first loop's attention indices verbatim — so an added loop costs one sliding window, not a full context cache. This co-design is what lets looping survive at 750B parameters and 1M context, where the baseline cost would otherwise roughly double.

Q3 — 结果 (results) #

3. 架构 / 方法图 #

No published architecture figure is embeddable; the mechanism is redrawn below.

Loop placement in the stack — the base model keeps its early and late layers single-pass; only a 28-layer middle block is wrapped in a 2-iteration loop:

flowchart TB IN[Input embeddings] --> EARLY[Early layers · single pass] EARLY --> L0{Loop block · 28 layers · weight-tied} L0 -->|iteration 1: build global context| L0 L0 -->|iteration 2: refine from pass-1 state| LATE[Late layers · single pass] LATE --> OUT[LM head]

Per-iteration gated residual write — each iteration's candidate update is scaled by an independent per-token gate before it rejoins the residual stream, keeping activation norms in-distribution for downstream layers:

flowchart LR H0["h(t-1)"] --> F["f_theta — shared block"] F --> CAND["candidate update"] G["per-token gate g(t)"] --> MUL["⊙"] CAND --> MUL MUL --> ADD["+"] H0 --> ADD ADD --> H1["h(t)"]

The learned gate behavior is the subtle part: iteration 1 writes conservatively (small gate) to stabilize scale while assembling global context; iteration 2 opens the gates for a full refinement write; and on harder tokens iteration 1 writes more aggressively, so difficult predictions extract more from the second pass.

Hybrid KV cache — the second loop attends to two overlapping KV streams: the sparse KV selected in pass 1 (shared, global) plus its own sliding-window KV (local, fresh):

flowchart TB P1[Loop 1 sparse KV selection] -->|shared| ATTN[Loop 2 attention] P1 -->|indices reused verbatim| ATTN SW[Loop 2 sliding-window KV] -->|local, fresh| ATTN ATTN --> OUT2[refined hidden state]

4. 作者证明 #

无形式化作者证明 — 仅实证. The blog states no convergence theorem, variance bound, or formal proposition; all support is empirical (iso-parameter ablation + deployment numbers). The six verification checks are therefore applied to the mechanism claims and the equation's physical meaning rather than to a theorem.

Notation

SymbolMeaning
$f_\theta$the weight-tied loop block (28 layers, shared across iterations)
$h^{(t)}$residual-stream hidden state after loop iteration $t$
$g^{(t)}$per-token, per-iteration gate controlling write magnitude
$T$number of loop iterations ($T=2$ for GLM-5.4)
$\odot$element-wise (per-token) scaling

方程物理意义. $h^{(t)} = h^{(t-1)} + g^{(t)} \odot f_\theta(h^{(t-1)})$ is a gated residual recurrence: re-applying one parameter set deepens the effective computation graph without new weights, and the gate makes each write a controllable step so re-entry does not push activations out of the distribution the downstream single-pass layers expect.

Six checks

  1. Parameter-count invariance — because $f_\theta$ is reused, $T$ iterations add 0 parameters; "2T–3T-class intelligence at fixed params" is consistent with the weight-tying definition. ✅ internally consistent.
  2. Scale stability — the stated failure mode (overwriting hidden states blows up activation norm across iterations) is exactly what an ungated $h^{(t)} = f_\theta(h^{(t-1)})$ recurrence would do; the gate $g^{(t)}$ is the correct lever. ✅ mechanism matches failure.
  3. Memory accounting — naive loop ⇒ KV ×$T$; hybrid design ⇒ shared sparse KV + one sliding window per extra loop. The claimed sub-linear memory growth follows only if the sliding window ≪ full context. ✅ holds for long context, where the design is pitched.
  4. Index-reuse validity — reusing loop-1 sparse-attention indices in loop 2 is justified only if the attended-set is stable across iterations; the blog backs this with "nearly identical to recomputing indices." ⚠️ empirical, not proven.
  5. Compute-overhead claim — "~10% more total training compute" for continued adaptation is plausible given the loop is applied to a middle block during continued training, not full pre-training. ⚠️ not independently verifiable from the post.
  6. Token-length reduction — the 10–14% shorter outputs are attributed to reasoning shifting into loop depth; this is a correlational claim, consistent but not causally isolated. ⚠️ empirical.
  7. A desirable missing guarantee: a bound relating loop count $T$ to effective-depth gain, or a stability condition on $g^{(t)}$ that provably keeps $\lVert h^{(t)} \rVert$ bounded.

    5. 实验与数据 #

    No result figures were extractable; the load-bearing numbers are tabulated from the post.

    Iso-parameter controlled ablation (the central evidence). The comparison fixes parameter count and architecture, varying only looped vs. unshared, at the 30B scale that mirrors the 750B base:

    FactorSetting
    Base scale30B (same architecture family as 750B base)
    Parameter countidentical across arms
    Extra training compute~10%
    Eval protocolafter 200K long-context SFT, thinking mode on
    Outcomelooped arm shows clear gains, largest in math / scientific reasoning / long-context

    This design is what makes the claim credible: holding parameters constant isolates effective compute as the manipulated variable, so the gain cannot be attributed to more memory capacity.

    Efficiency table.

    MetricValueNote
    Avg. output length−10% to −14%GPQA-Diamond, MMLU-Pro, etc.; mostly shorter CoT
    Throughput (off-peak)up to 200 tok/smodel ↔ infra co-design
    Throughput (peak)70–80 tok/sunder load
    Added serving cost vs GLM-5.3"well under control" at 1M ctxfrom hybrid KV + index reuse

    Scaling-validity ladder. The loop was validated progressively at 1B → 4B → 30B → 750B before the flagship, establishing that the architecture holds across two orders of magnitude of scale rather than at a single lucky operating point.

    6. 论证链 #

    #StepSupports
    1Target tasks are ultra-long-chain reasoning, bottlenecked by sequential compute depth, not stored knowledge.motivates depth over width
    2More effective compute = more depth; weight-tying adds depth at zero parameter cost.justifies the loop
    3Looped-from-scratch underperforms unshared at equal pre-train compute ⇒ instead adapt a pre-trained base via continued training.justifies the continued-training recipe
    4Re-entering a middle block ungated blows up activation norms ⇒ add per-token per-iteration gates for proportional writes.justifies gated progressive updates
    5Naive loop multiplies KV and indexing by $T$ ⇒ share loop-1 sparse KV + add one sliding window, and reuse loop-1 indices.justifies hybrid KV + index reuse
    6Iso-parameter 30B ablation shows accuracy gains + 10–14% shorter outputs for ~10% extra compute.validates the whole construction empirically
    7Memory/index savings + fused kernels keep 750B/1M-context serving at 70–200 tok/s.shows the design is deployable, not just accurate

    7. 实现 cross-reference #

    [实现未公开] — GLM-5.4 is a product blog; no code, config, or file-level artifacts are released. Open weights are "planned after safety hardening" and the API is "coming soon," so there is nothing to cite at file:line granularity yet.

    核心技术壁垒 (dedicated). The hardest piece to reproduce is not the loop itself — Universal Transformer (2018) and recent recurrent-depth work already established weight-shared depth — but making an extra loop serving-free at 750B and 1M context. That requires the full stack to compose: (a) sparse attention in the base model, (b) cross-loop sparse-KV sharing so the second pass does not re-cache context, (c) verbatim reuse of the first loop's attention indices so indexing cost is zero, and (d) fused kernels that remove the fragmented intermediate reads/writes a loop would otherwise amplify. Any team can tie weights; few can make the second pass cost one sliding window instead of a second full forward.

    关键实现细节 (easy-to-miss tricks).

    1. The gate schedule is learned, not fixed — iteration 1 writes conservatively and iteration 2 fully, and the step size adapts to token difficulty (harder tokens get a more aggressive first-pass write). A naive re-implementation that uses a single scalar or constant gate would lose the stability and the difficulty-adaptive refinement.
    2. Index reuse, not recomputation — the second loop reuses the first indexer's output; the post reports this is near-identical to recomputing per pass, so the "obvious correct" per-pass recomputation is wasted work. This is the detail that converts the sparse-attention loop from a 2× indexing cost into zero.