What Is GLM-5.4 Loop Transformer: 28 Layers Looped for 2 Rounds and 5 Key Mechanisms for Improving Reasoning Without Adding Parameters

What Is GLM-5.4 Loop Transformer: 28 Layers Looped for 2 Rounds and 5 Key Mechanisms for Improving Reasoning Without Adding Parameters

Summary: This article explains how the Loop Transformer used in GLM-5.4 increases effective computational depth without changing the parameter count, and what this approach actually means for reasoning scores, output length, and serving cost.

Bottom line up front: GLM-5.4’s Loop Transformer lets a single 28-layer computational block share one set of weights, feeds the output of that block back into the same block for another pass, and runs two passes in total. As a result, the parameter count stays the same while the effective depth increases, and the second pass can keep refining the reasoning on top of the hidden states the first pass has already organized. It can improve reasoning, but only under three conditions:

  • Continue training from an already pretrained GLM-5-series base model rather than training from scratch;
  • Use per-token gating to control how much each pass writes;
  • Use cross-pass KV caching and index reuse to keep memory and compute overhead in check.

In the 30B same-parameter ablation published by Zhipu, the loop group improved its score on all 5 tasks, including AIME25 and GPQA-Diamond, while average output length dropped at the same time. The cost is that the loop group’s total training compute is about 10% higher, and inference compute per token also increases.

glm-5-4-loop-transformer-explained-en-image-0


GLM-5.4 Loop Transformer Knowledge Map

glm-5-4-loop-transformer-explained-en-image-1

Figure caption: The article progresses through four layers. Section 1 explains how Loop Transformer works, Section 2 explains what engineering designs GLM-5.4 introduced to make looping usable, Section 3 uses same-parameter experiments and a cost ledger to test whether “improving reasoning without adding parameters” holds, and Sections 4 and 5 provide actionable verification methods and common questions.

Article Index

We recommend starting with Section 1. Section 1 draws the distinction between the two concepts of “weights” and “compute,” which is the foundation for understanding the rest of the article. Section 2 builds on that to explain why simply executing the same layers repeatedly causes problems, and which type of problem each of the three designs—gating, caching, and indexing—solves. Section 3 returns to the core question in the title, using 30B ablation data and two illustrative worked examples to explain the benefits and costs. Section 4 is for developers, covering how to measure output length and latency on the same task. Section 5 can be consulted as needed.

Loop Transformer To Know Glossary

Term Concise explanation
Loop / Recurrent Depth The same group of layers is executed repeatedly using the same set of weights, increasing effective depth without increasing that group’s weights
Hidden state h The intermediate vector passed between layers; each loop iteration reads it in and updates it
Residual stream The channel through which each layer in a Transformer adds its increment back to the main representation; gating controls how much of the increment is written
KV cache The keys and values attention saves for already-processed positions; one of the main sources of GPU memory usage in long contexts
Sparse attention indexer First selects a small number of relevant historical positions for the current position, then performs attention computation on them
Ablation study A controlled experiment that changes only one factor (here, whether to loop) and observes how the results change

1 What Loop Transformer Is

1.1 Independent weight stacking vs. Loop Transformer shared weights

Each layer of a Transformer takes a set of intermediate vectors as input and outputs new vectors. Attention lets positions exchange contextual information, and the remaining transformations further process these representations. In a conventional independent weight stack, adding another set of layers increases both the weights you can store and train, along with the computation per forward pass—the two grow in lockstep.

Loop Transformer’s approach keeps only one set of weights and feeds the output of that layer block back into the same computational block for another pass, after which the representation from the two rounds continues into subsequent layers. This decouples parameter count from computational depth: effective depth increases while the recurrent block still holds only one shared copy of the weights. That’s what “no added parameters” in the title means. What you add is computation, not capability for free.

1.2 Looking at GLM-5.4’s two-round computation through the equations

Let the layer block be F and the weights be θ. The first round computes h₁ = Fθ(h₀), and the second round uses h₁ to compute h₂ = Fθ(h₁). The two inputs are the initial hidden state and the updated hidden state respectively, so the same θ produces different updates.

According to the design released by Zhipu, the recurrent block contains 28 layers and runs for two rounds. Originally, one pass means 28 layer applications; after two rounds it contributes 56, an increase of 28. This number only describes the notion of that block being scheduled repeatedly. The full network also includes the remaining layers, cross-round control, and other processing. Real deployment requires counting whole-network FLOPs, and you’d also need to account item by item for attention, expert routing, caching, indexing, and hardware execution specifics.

glm-5-4-loop-transformer-explained-en-image-2

Figure note: the two structures perform the same number of layer applications on this 28-layer block; the difference is how many copies of trainable weights exist. The independent scheme has two sets of weights, while the loop scheme has only one, relying on the changing input state h₁ to produce different updates.

1.3 Why the second round of Loop Transformer helps

Multi-step reasoning usually needs to first organize facts and constraints, then revise the next step based on the organized representation. A geometry problem makes a useful analogy: the first round forms the object layout and reference positions, and the second round continues processing occlusion and local relationships on top of the existing contextual representation. Note that this is only an analogy to aid understanding; the public material describes iteration over hidden vectors, and the specific semantics of each round’s vectors would need separate experimental verification.

It’s also worth distinguishing two computational paths. Deeper forward computation happens inside the model, where every token gets an extra round of computation; autoregressive generation of many thinking tokens, by contrast, writes the reasoning process into the output. What you can measure from the outside is output length and results—which is why Section 3 looks at changes in output length.


2 How GLM-5.4 Implements the Loop Transformer

2.1 Research Precedents for the Loop Transformer

Loop depth isn’t something GLM-5.4 came up with first—there are three main strands of related research:

  • Universal Transformers (2018 preprint): Combines self-attention with repeated execution across depth, and explores mechanisms for dynamic per-position stopping.
  • Deep looped models by Geiping et al. (2025): Scales test-time compute by adding internal iterations, showing that a single set of weights can carry out multiple latent computations.
  • Restructuring pretrained models: Modifies the architecture of an already-pretrained model, then gradually increases the number of loops during training.

These works respectively provide precedents for weight reuse, variable inference depth, and retrofitting existing base models. For their specific stopping strategies, scale, and training procedures, refer to the original papers. The design confirmed in Zhipu’s release is a fixed 28 layers with two rounds.

2.2 GLM-5.4: Adapting a Pretrained Base

Zhipu didn’t train a looped model from scratch. Instead, they continued training on an already pretrained GLM-5 series base. That choice came out of their experiments: weight reuse improved parameter efficiency, but when training from scratch with the same pretraining compute, an independent-weight version performed better. The pretrained weights gave the architecture work a starting point, and continued training let the existing layers adapt to the new state distribution introduced by looping.

The base size given in the release is about 750B, with validation covering four tiers: 1B, 4B, 30B, and 750B. The company suggests that in the future, positions of different difficulty could use different numbers of rounds. The difficulty adjustment already shown in the release materials is write magnitude—that is, the gating in the next section.

2.3 Per-Token Gating in Loop Transformer

If you directly overwrite the old state with the vectors produced at each round, Zhipu observed that the activation norm keeps rising with repeated updates, and the distribution read by later layers drifts away from what the original base expects. GLM-5.4’s approach is to set an independent, per-token gate for each round, letting candidate changes enter the residual stream in proportion.

The company observed behavior across two rounds:

  • The first round mostly makes gentle updates, focusing on building global context; at positions where prediction is harder, it also increases the write.
  • The second round further refines the first round’s state, writing back with a larger magnitude.

So “how many rounds to execute” and “how much to write each round” are two independent control variables. Gating changes how the two computations update the state; the number of computation rounds itself stays the same.

2.4 GLM-5.4’s Cross-Turn KV Cache Design

A naive approach would store the keys and values for the full sequence separately for each turn, which sharply increases memory pressure with long contexts. In the second turn, GLM-5.4 reads from two sources at the same time:

  • Global information: uses the sparse key-values selected in the first turn;
  • Local information: keeps the newly computed keys and values from the second turn in a sliding window.

The two streams can cover the same position. This lets the second turn retrieve first-turn information from farther positions while also reading the latest state nearby, with new cache growth capped at the window size. The release page doesn’t disclose the window length, nor does it list absolute measured memory usage for each hardware configuration.

glm-5-4-loop-transformer-explained-en-image-3

Figure note: The cache added in the second turn covers only positions within the window, while distant information reuses the sparse key-values selected in the first turn. The window length is undisclosed; the diagram only illustrates the relative relationship.

2.5 Index Reuse, Kernel Fusion, and the Loop Transformer Cost Ledger

Sparse attention has to pick out the relevant positions before it can compute anything. In its second pass, GLM-5.4 reuses the first pass’s indexer results directly, and the official report says this performs about the same as recomputing the index from scratch. What gets saved is just that one extra round of position filtering: the selected positions still need attention computation, and the transformations inside the loop block still run as usual. Server-side kernel fusion, meanwhile, cuts down the repeated reads and writes of intermediate tensors, easing the hardware overhead of running the block again and again.

Breaking the cost down into a ledger makes it easier to see which line each engineering optimization actually moves:

Cost item What looping changes GLM-5.4’s corresponding measure Public information
Weight footprint The loop block stores only one copy of the weights Shared weights Disclosed
KV cache The second pass needs new keys and values Sparse global reuse + sliding window Window length not disclosed
Index computation The second pass would otherwise re-filter positions Reuse first-pass index results Roughly on par with recomputation
Intermediate tensor reads/writes Repeated execution adds intermediate reads and writes Server-side kernel fusion No quantified figures given
Remaining network compute The loop block’s transformations run twice Cannot be avoided Requires whole-network accounting

3 Why Loop Transformer Improves Reasoning Without Adding Parameters

3.1 GLM-5.4’s 30B Same-Parameter Ablation

Zhipu published a set of 30B architecture ablations, and this model shares the same architecture as the 750B base. The two groups have identical parameter counts, while the loop group’s total training compute is roughly 10% higher. According to the figure caption, both models went through 200K long-context supervised fine-tuning, and thinking was enabled during evaluation. The data in the table below comes from Zhipu’s ablation notes [1]; the length changes follow the individual figures in the original chart.

Task Baseline score Loop group score Score change Avg. output length change Length reduction
AIME25 19.17 30.42 +11.25 −635 tokens ~2%
GPQA-Diamond 47.58 56.26 +8.68 −2,473 tokens 11.7%
AA-LCR 40.33 47.67 +7.34 −539 tokens 9.7%
MMLU-Pro 71.65 75.05 +3.40 −863 tokens 14.9%
IFBench 50.20 53.47 +3.27 −763 tokens 13.0%

glm-5-4-loop-transformer-explained-en-image-4

Figure note: scores rise on all five tasks, with AIME25 improving the most (+11.25) but showing the smallest length reduction (~2%); GPQA-Diamond gains 8.68 points while length drops by nearly 12%. These are Zhipu’s self-reported same-parameter comparisons. If you want to check a similar difference on your own tasks, you can compare output length and results across models on the same set of questions using APIYI at apiyi.com.

This data supports a limited conclusion: under the same parameter budget, adding effective depth can raise scores on selected tasks, and output length also drops on some of them. The score and length changes don’t move in sync, and average text length is still affected by prompts, decoding parameters, and thinking settings.

3.2 Keep Training Costs and Inference Costs Separate

The roughly 10% figure is the total compute difference between the two 30B variants during the training phase, and you can’t directly convert it into inference cost. Inference needs its own accounting: input prefill, the decode cost per token, and the number of tokens generated. Here’s a purely illustrative example, with units and numbers all made up:

Approach Tokens generated Decode cost per token Total decode cost
Baseline 1,000 1.00 1,000
Looped version (+10% per token) 880 1.10 968
Looped version (+20% per token) 880 1.20 1,056

The example shows that a shorter output can offset part of the internal compute increase, but which one ends up cheaper depends on the per-token increase and how much the output shrinks. Real deployments also have to factor in input and tool calls; this table isolates decode as the only variable.

3.3 Memory Footprint of a Loop Transformer

Let’s do another round of memory assumptions: the context has one million positions, and the second round only keeps independent keys and values for the most recent ten thousand positions. Compared with “adding keys and values for the entire sequence,” the number of newly added positions drops from one million to ten thousand. This ratio only reflects the storage scope of the newly added cache; the key/value dimensionality, precision, runtime implementation, and the first-round cache all affect total memory. The ten thousand figure is hypothetical — Zhipu only stated publicly that it uses a sliding window, without giving the length.

3.4 Where Shared Loops and Independent Deepening Apply

Comparison dimension Independent weight deepening Shared-weight loop (GLM-5.4)
Trainable weights One set per layer group Only one set in the loop block
Source of different updates Different weights State, context, and gating signals after iteration
Training from scratch (same pretraining compute) Performed better in Zhipu’s experiments Higher parameter efficiency, weaker performance
Backbone modification Requires adding new weights Reuses already trained weights and continues training
Better-suited task structure Needs to store more independent information Reasoning with repeatable iterative steps

Shared computation is well suited to structures that express “the same step performed repeatedly.” When you need to store large amounts of mutually independent knowledge, simply increasing depth runs into a different kind of constraint. The paper’s distinction between reasoning and memory is a structural analysis, and its scope shifts with the task and training conditions [6].


4 How to Validate Loop Transformer’s Impact at the API Layer

You can’t observe the internal loop from the outside, but you can measure the outcomes it affects: output token count, latency, and answer quality. Zhipu reports a serving throughput on the product side of up to 200 token/s off-peak and around 70–80 token/s at peak; these numbers depend on runtime load and service integration [1]. To attribute a performance change to a particular mechanism, you need to hold the input budget and reasoning level constant for the same task, and record output token count and quality.

4.1 A Minimal Measurement Example

The code below sends a reasoning question through the OpenAI-compatible API and records the output token count along with the total elapsed time:

from openai import OpenAI
import time

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.apiyi.com/v1"  # APIYI OpenAI-compatible endpoint
)
MODEL = "your-model-name"  # use the exact name listed for the model in the APIYI console

start = time.time()
resp = client.chat.completions.create(
    model=MODEL,
    messages=[{"role": "user", "content": "3×3×3 立方体表面涂色后切开,两面有色的小块有几个?"}],
)
print(resp.choices[0].message.content)
print("输出 token:", resp.usage.completion_tokens, "耗时:", round(time.time() - start, 2), "s")
View the full measurement code (streaming TTFT + multi-model multi-run comparison)
import time
import csv
from statistics import mean
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.apiyi.com/v1"
)

MODELS = ["model-a", "model-b"]  # replace with the model names you want to compare
PROMPTS = [
    "3×3×3 立方体表面涂色后切开,两面有色的小块有几个?",
    "甲比乙大 4 岁,5 年后两人年龄和为 40,求甲现在的年龄。",
]
RUNS = 3  # number of repetitions per question, to smooth out variance


def measure(model: str, prompt: str) -> dict:
    """Streaming request that records time-to-first-token, total elapsed time, and output token count separately"""
    start = time.time()
    first_token_at = None
    text = []
    usage = None
    stream = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": prompt}],
        stream=True,
        stream_options={"include_usage": True},
    )
    for chunk in stream:
        if chunk.usage:
            usage = chunk.usage
        if chunk.choices and chunk.choices[0].delta.content:
            if first_token_at is None:
                first_token_at = time.time()
            text.append(chunk.choices[0].delta.content)
    end = time.time()
    out_tokens = usage.completion_tokens if usage else None
    gen_time = end - (first_token_at or start)
    return {
        "ttft": round((first_token_at or end) - start, 3),
        "total": round(end - start, 3),
        "out_tokens": out_tokens,
        "tok_per_s": round(out_tokens / gen_time, 1) if out_tokens and gen_time > 0 else None,
        "answer": "".join(text)[:200],
    }


rows = []
for model in MODELS:
    for prompt in PROMPTS:
        results = [measure(model, prompt) for _ in range(RUNS)]
        rows.append({
            "model": model,
            "prompt": prompt[:20],
            "avg_ttft": round(mean(r["ttft"] for r in results), 3),
            "avg_total": round(mean(r["total"] for r in results), 3),
            "avg_out_tokens": round(mean(r["out_tokens"] or 0 for r in results)),
            "sample_answer": results[0]["answer"],
        })

with open("loop_eval.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=rows[0].keys())
    writer.writeheader()
    writer.writerows(rows)

for r in rows:
    print(r)

Quick-start tip: APIYI apiyi.com offers an OpenAI-compatible API, so one API key is all you need to switch between multiple models. New users get free trial credits — a good way to get the measurement script above running on a small sample set first, then scale up from there.

4.2 Checklist for Validating Loop Transformer

  1. Hold variables fixed: Use the same prompt, the same thinking level and input budget, and keep decoding parameters like temperature consistent.
  2. Split the timing: For coding tasks, break total time into first response, model output, tool execution, and subsequent rounds.
  3. Track quality and length together: Looking only at token count hides answer accuracy; looking only at score hides cost.
  4. Average across multiple runs: Service throughput varies with peak and off-peak load, so single-run results fluctuate a lot.

5 Common Questions About GLM-5.4 Loop Transformer

Q1: Does Loop Transformer add parameters?

The loop block holds only one set of weights, so the parameter count stays the same. What increases is the compute per token: GLM-5.4’s 28-layer block runs two rounds, so layer applications go from 28 to 56.

Q2: How is this different from having the model output more thinking tokens?

Looping means computing the hidden vector for one more round inside the model; thinking tokens mean writing the reasoning process into the output. The 30B ablation shows that while the loop group’s score rose, average output length fell—the two paths can coexist and affect each other.

Q3: If looping saves parameters, why not train from scratch?

Zhipu’s experiments found that, under the same pretraining compute, training from scratch with independent weights performs better. Looping has more of an edge when adapting an already-trained base, so GLM-5.4 chose to continue training on the GLM-5 series base.

Q4: Is inference always cheaper or always more expensive?

Both cases can happen, depending on how the per-token compute increase compares with the drop in output length—see the worked example in 3.2. We recommend measuring token counts and latency on APIYI apiyi.com with your own real tasks, and using the measured results to decide.

Q5: How can developers start testing quickly?

Register at APIYI apiyi.com to get an API key, set `base_url` to `https://api.apiyi.com/v1`, and run the script from Section 4 directly. For the specific model names available, refer to the console list.

Q6: What gaps remain in the public information?

Sliding window length, measured memory usage on each hardware configuration, and the quantified benefit of kernel fusion are all undisclosed. Among public experiments, the strongest evidence centers on the 30B same-parameter comparison group.


To judge whether GLM-5.4’s Loop Transformer is valuable for your business, you can test it like this: pick a batch of real tasks that involve multi-step reasoning, fix the prompt and thinking level, and record answer accuracy, output token count, and total time together. If scores improve while total token cost stays flat or drops, loop depth is worth it in your scenario; if the tasks mainly rely on knowledge recall, the gains may be limited. You can run this kind of controlled test through the unified interface at APIYI apiyi.com—switching models only requires changing the model name.

References

  1. Zhipu Loop technical documentation (including 30B ablation and deployment notes): zhipuai.cn/zh/research/164
  2. Z.ai GLM-5.4 launch blog: z.ai/blog/glm-5.4
  3. Zhipu Open Platform GLM-5.4 architecture overview: docs.bigmodel.cn/cn/guide/models/glm-5.4
  4. Universal Transformers original paper: arxiv.org/abs/1807.03819
  5. Deep recurrent language model paper: arxiv.org/abs/2502.05171
  6. Recurrent reasoning comparison paper: arxiv.org/abs/2502.17416
  7. Retrofitting pretrained models with recurrence: arxiv.org/abs/2511.07384
  8. ZCode reasoning effort documentation: zcode.z.ai/cn/docs/agents

Author: APIYI Technical Team
Technical discussion: Feel free to visit the APIYI homepage at apiyi.com to get in touch with us. More integration docs are available in the docs.apiyi.com documentation center.

Related Articles

Similar Posts