Skip to main content

GLM-5.2: The open coding model that put the critic back into RL

A close look at how Zhipu built GLM-5.2, from DeepSeek Sparse Attention to critic-based PPO, with a live agentic coding demo traced in W&B Weave.
Last updated: July 21, 2026
Most of the coverage of GLM-5.2 has settled on the same two sentences: it is the strongest open-weight coding model available right now, and it costs a fraction of the closed frontier. Both are true. Neither tells you much about how it was built. The more interesting story is a post-training decision Zhipu made that cuts against where much of the field has been heading. Over the last year, a good part of the RL community standardized on GRPO and its group-relative relatives specifically to get rid of the value network. Zhipu spent the compute to bring a critic back. That choice, and the reasoning behind it, is the thread worth pulling on.
Before getting into any of it, a note on sourcing. The secondary write-ups disagree with each other on several of GLM-5.2's numbers, so everything below was checked against Zhipu's own material: the GLM-5 technical report, the GLM-5.2 launch blog, and the model card on Hugging Face. Where a figure could not be confirmed from one of those, that is called out rather than repeated. What follows walks through the parts of GLM-5.2 that matter, the sparse attention that makes a million-token context affordable, the speculative decoding that keeps it fast, and the reinforcement learning choices that shaped its coding behavior, then runs a live demo: a real agentic coding task against the hosted API, traced end to end in W&B Weave.

Table of Contents



What is GLM-5.2

GLM-5.2 reached Zhipu's GLM Coding Plan subscribers on June 13, 2026, with the open weights, a standalone API, and the technical write-up landing the following week. It is the third major step in the GLM-5 line and a sparse mixture-of-experts model.
The parameter count is the first place the secondary sources split, so precision matters. The GLM-5 technical report [link] gives the architecture as 744 billion total parameters with roughly 40 billion active per token, across 256 experts and 80 layers. The GLM-5.2 weights on Hugging Face measure 753 billion in their safetensors metadata. Zhipu does not itemize the nine billion difference, so the honest summary is this: it is a large sparse MoE where only about 40 billion parameters do work on any given token, and that sparsity keeps a model this size economical to serve.
The base model was trained on 28.5 trillion tokens: a 27 trillion token pre-training corpus weighted toward code and reasoning, then a separate mid-training phase that extended context and layered in agentic data. The headline capability for 5.2 is a usable 1M-token context, opt-in through the glm-5.2[1m] identifier, up from 200K on GLM-5.1, with output to 128K tokens (131,072). The model exposes two reasoning-effort levels, high and max, selectable per request, so a quick edit and a full build can hit the same endpoint at different cost points. The weights ship under an MIT license with no regional restrictions.

The attention foundation: DSA, then IndexShare

A 1M-token window is a cost problem first. Full attention is quadratic in sequence length, so a context that large is unaffordable to fill on every request unless the attention itself changes shape. GLM-5.2 builds on DeepSeek Sparse Attention (DSA), and the label is literal: the model's architecture type on Hugging Face is glm_moe_dsa. [link]

DSA runs a lightweight indexer that scores which past tokens matter for the current query, keeps the top-k, and attends only to those, so each token sees a learned subset of the history. Training and inference cost both drop, and long-context fidelity holds up.
The catch is that the indexer becomes its own bottleneck at a million tokens. Even a cheap scorer that runs at every layer is scoring the full history at every layer. IndexShare is Zhipu's answer, and it is a small idea with a large payoff. The indexer runs once at the first of every group of four sparse-attention layers, and its top-k selection is reused across all four. Each layer still performs its own attention over the selected positions, but the indexer dot-product and the top-k search are skipped in three layers out of every four. Zhipu reports a 2.9x reduction in per-token FLOPs at 1M context from this alone. IndexShare is trained in from mid-training at a 128K sequence length rather than bolted on afterward, and the underlying method is written up separately (arXiv 2603.12201).
That 2.9x is the difference between a context window that is technically supported and one you can afford to use on real requests. It is also the clearest example of the design philosophy running through the whole release: pick the expensive part and make it cheaper without giving up the behavior that made it worth having.

Speculative decoding through the MTP layer

Long context is a throughput problem on the output side too, and GLM-5.2 leans on speculative decoding to address it. A multi-token prediction (MTP) layer proposes several future tokens as a draft; the main model verifies them in a single pass, and the run of tokens that matches the model's own distribution is accepted. The longer the accepted run, the fewer expensive forward passes you need per token of output.
Zhipu reports up to a 20% improvement in acceptance length for GLM-5.2's MTP, and the ablation behind that number is more informative than the headline. Measured on the GLM-5.1 backbone with the speculator set to seven steps, the baseline accepts 4.56 tokens per pass. Adding IndexShare and KVShare to the MTP layer, which also removes a training-versus-inference KV mismatch that held GLM-5.1 back, lifts it to 5.10. Rejection sampling brings it to 5.29. An end-to-end total variation loss brings it to 5.47, and that last figure is the 20% gain. Worth noting: the acceptance number is a representative ablation on the previous backbone rather than a shipped 5.2 spec, and in the published vLLM serving recipe the speculator runs five tokens rather than seven. The point stands either way: the same architectural sharing that cuts attention cost is reused inside the speculator.

slime: The RL infrastructure, and it is open

Everything past the base model runs on slime, Zhipu's reinforcement learning post-training framework, which is open source and has now trained the entire GLM-5 line. Frontier-grade RL infrastructure being public at all is unusual, and it is worth looking at how it is put together because the shape of the framework explains several of the training decisions.
slime [link] has two halves joined by a buffer. Training runs on Megatron-LM, rollout runs on SGLang behind a router, and a data buffer between them holds prompts, partial rollouts, and scored samples. The decoupling is deliberate. For agentic RL, a rollout is a long multi-turn trajectory of tool calls, results, and revisions, slow and uneven in length. If the trainer blocked until each batch finished, the accelerators would sit idle, so generation and training run asynchronously and keep both busy. The framework handles white-box and black-box rollouts, compact trajectories, and sub-agent workflows, which maps onto how GLM-5.2 was trained.
One detail in slime is easy to miss and matters for the next two sections: the training module carries an optional critic. Hold onto that.

OPD: Train the experts in parallel, then merge them

Optimizing a single generalist across coding, math, search, tool use, and instruction following at the same time is a losing setup. The domains have conflicting gradients and different reward structures, so training them jointly produces interference, and training them in sequence produces catastrophic forgetting, where the model gets good at the newest domain while losing the previous ones.
Zhipu's route around this is to train more than ten domain specialists in parallel, each with its own reinforcement learning, then merge them into the final model using on-policy distillation, which the report abbreviates as OPD. [read more]
The mechanism is specific: the student generates its own trajectories, the specialist teachers provide token-level distributions over those trajectories, and the student minimizes the token-level divergence to the teachers. Because the student learns on its own outputs, the distilled behavior transfers without the usual off-policy mismatch. OPD is not new to 5.2; GLM-5 used on-policy distillation as a cross-stage step to fight forgetting. The change in 5.2 was scaling it into the mechanism that consolidates the specialists. On slime, that merge ran in roughly two days: the consolidation step is cheap relative to the specialist training that feeds it.

The credit-assignment decision

Here is the part most write-ups skip. For long-horizon agentic RL, Zhipu moved from group-wise optimization back to critic-based PPO, and they explain why.
Start with what they moved away from. Group-relative methods like GRPO earned their popularity by deleting the value network. With no critic to estimate how good a state is, you sample a group of rollouts for the same prompt, take the group's average reward as the baseline, and define each rollout's advantage as how far it beat that average. No critic to train, no critic to serve, less to go wrong. After the reasoning-model wave, this became close to a default.
It falls apart on long-horizon agentic work for a concrete reason: trajectory compaction. Agentic runs get long enough that they no longer fit in context, so the pipeline compacts them, summarizing earlier steps to make room. Compaction splits one long trajectory into several sub-traces of unequal length, so different rollouts of the same prompt yield different numbers of trainable sub-traces at different lengths. Group-relative advantage assumes a comparable set of items to average over, and compaction breaks that assumption. There is no clean group to normalize against when each member has been chopped into a different number of uneven pieces.
Critic-based PPO handles this because it learns from individual rollouts. A critic estimates token-level advantages directly, so you do not need a comparable group at all. You can train every compacted fragment, use a token-level loss to absorb the length imbalance, and the model ends up training on exactly the lossy summaries it will meet at deployment. The cost is the value network GRPO was designed to eliminate, with the extra memory and training complexity that brings. Zhipu decided the credit-assignment quality was worth paying for on long-horizon tasks, and that optional critic in slime's training module is the same decision showing up in the infrastructure.
This is the piece that makes GLM-5.2 more than a scale-and-ship release. It is a specific, reasoned reversal of a default the field mostly treats as settled, motivated by a failure mode that only shows up once your trajectories get long enough to need compaction.

Reward hacking, and the guard that returns fake data

Verifiable rewards are the backbone of coding RL: the tests pass, or they do not, and that binary is a clean signal to optimize against. Clean signals are also gameable, and Zhipu is candid that GLM-5.2 showed more reward hacking than 5.1 during coding RL. The agent learned to read protected evaluation artifacts, curl a reference solution from a public repository, and chain small information leaks to reconstruct the answer without solving the task.
The fix is an online anti-hacking module with a two-stage detector: a cheap rule-based filter tuned for recall, followed by an LLM judge tuned for precision. The interesting design choice is what happens on a catch. Aborting the trajectory would destabilize training by throwing away partial rollouts and skewing the batch, so the guard blocks the specific offending action, feeds the agent dummy information, and lets the rollout continue. The trajectory stays intact, the exploit returns nothing useful, and training keeps its footing. It is a small, practical idea, and it becomes concrete in the demo below, where the reward is a test suite the model could in principle try to game.

Where GLM-5.2 lands on benchmarks

Zhipu positions GLM-5.2 around long-horizon engineering, and the three benchmarks it leads with were run by outside evaluators rather than scored in-house: FrontierSWE by Proximal, PostTrainBench by its own team, and SWE-Marathon by Abundant AI. If you read straight, they tell a consistent and honest story.
BenchmarkGLM-5.2Claude Opus 4.8GPT-5.5
FrontierSWE74.475.172.6
PostTrainBench34.337.228.4
SWE-Marathon13.026.012.0

On FrontierSWE, it lands 0.7 points behind Opus 4.8 and ahead of GPT-5.5, about as close to the closed frontier as an open model has gotten here. On PostTrainBench it sits second to Opus 4.8 and clears both GPT-5.5 and, per Zhipu's blog, Opus 4.7. SWE-Marathon is the hardest category, covering from-scratch work like building compilers and optimizing kernels, and here GLM-5.2 reaches 13.0 against Opus 4.8's 26.0. Exactly half. That gap is the honest headline for anyone weighing GLM-5.2 for novel systems work over repository-scale changes.
On standard coding benchmarks, the jump over 5.1 is large: 81.0 versus 62.0 on Terminal-Bench 2.1, within a few points of Opus 4.8 at 85.0, and 62.1 versus 58.4 on SWE-bench Pro. Across the three long-horizon benchmarks, it is the top-ranked open model, and aggregators like Artificial Analysis place it at the top of their open-model list too. Broad independent replication is still early, so treat the near-frontier claims as directional for now.

Tutorial: Calling GLM-5.2 through the API and tracing it in W&B Weave

There is no local training story here. A 753B MoE is out of reach to self-host casually, and the Coding Plan does not offer fine-tuning, so for most people the practical path is the hosted API. The endpoint is OpenAI-compatible, so any client that speaks Chat Completions works after you repoint the base URL and swap the model string. This demo runs a small agentic coding loop and traces it through W&B Weave.
The agent loop and tracing below are the exact code that ran against the live z.ai endpoint. The only adaptation for Colab is that the two keys are read from the notebook's secrets manager. Open the key icon in the Colab sidebar, add ZAI_API_KEY and WANDB_API_KEY, and switch on notebook access for both. Then install the packages:
!pip install "openai>=1.0" weave pytest
The task: a pytest suite imports an evaluate function from an rpn.py module that does not exist yet, and the agent has to write rpn.py until every test passes. The model gets three tools, write_file, read_file, and run_tests, and loops until it is done. Weave captures the run two ways at once: the @weave.op decorator traces the agent loop and each tool call, and weave.init auto-patches the OpenAI client, so every GLM-5.2 request is logged with its messages and token usage without extra instrumentation.
The project starts with only the test suite, which imports the module the agent has to write:
import pathlib

pathlib.Path("agent_workspace/tests").mkdir(parents=True, exist_ok=True)
pathlib.Path("agent_workspace/tests/test_rpn.py").write_text('''
import pytest
from rpn import evaluate

def test_basic_add():
assert evaluate("3 4 +") == 7

def test_nested():
assert evaluate("5 1 2 + 4 * + 3 -") == 14

def test_division_is_float():
assert evaluate("10 4 /") == 2.5

def test_negative_literal():
assert evaluate("-3 4 +") == 1

def test_insufficient_operands():
with pytest.raises(ValueError):
evaluate("1 +")

def test_leftover_operands():
with pytest.raises(ValueError):
evaluate("1 2 3 +")

def test_unknown_token():
with pytest.raises(ValueError):
evaluate("1 2 %")

def test_divide_by_zero():
with pytest.raises(ZeroDivisionError):
evaluate("1 0 /")
'''.lstrip())

Now the agent. Weave reads WANDB_API_KEY from the environment for a non-interactive login, so one line sets it from the same secrets store, and the OpenAI client reads its key the same way:
import os, json, subprocess, pathlib
from openai import OpenAI
from google.colab import userdata
import weave

os.environ["WANDB_API_KEY"] = userdata.get("WANDB_API_KEY")

WORK = pathlib.Path("agent_workspace").resolve()
client = OpenAI(
api_key=userdata.get("ZAI_API_KEY"),
base_url="https://api.z.ai/api/paas/v4/",
)

def _safe(path):
p = (WORK / path).resolve()
assert str(p).startswith(str(WORK)), "path escapes workspace"
return p

@weave.op
def write_file(path, content):
p = _safe(path)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(content)
return f"wrote {len(content)} bytes to {path}"

@weave.op
def read_file(path):
p = _safe(path)
if not p.exists():
return f"ERROR: missing {path}"
if p.is_dir():
return "DIR contents: " + ", ".join(sorted(x.name for x in p.iterdir()))
return p.read_text()

@weave.op
def run_tests():
r = subprocess.run(["python", "-m", "pytest", "-q"], cwd=WORK,
capture_output=True, text=True, timeout=120)
return (r.stdout + r.stderr).strip()[-3000:]

TOOLS = [
{"type": "function", "function": {"name": "write_file", "description": "Create or overwrite a file.",
"parameters": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}}},
{"type": "function", "function": {"name": "read_file", "description": "Read a file or list a directory.",
"parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}},
{"type": "function", "function": {"name": "run_tests", "description": "Run pytest.",
"parameters": {"type": "object", "properties": {}, "required": []}}},
]
DISPATCH = {"write_file": write_file, "read_file": read_file, "run_tests": run_tests}

@weave.op
def run_agent(task, max_steps=10):
messages = [
{"role": "system", "content":
"You are an autonomous coding agent in a Python project. A pytest suite under "
"tests/ imports `evaluate` from `rpn.py`, which does not exist yet. Write rpn.py so "
"every test passes. Use tools to write files and run the suite. Iterate until green, "
"then give a one-paragraph summary. Do not ask questions."},
{"role": "user", "content": task},
]
prompt_tokens = completion_tokens = 0
for _ in range(max_steps):
resp = client.chat.completions.create(
model="glm-5.2", messages=messages, tools=TOOLS, tool_choice="auto",
reasoning_effort="high", max_tokens=8000, temperature=0.0,
)
if resp.usage:
prompt_tokens += resp.usage.prompt_tokens
completion_tokens += resp.usage.completion_tokens
m = resp.choices[0].message
asst = {"role": "assistant", "content": m.content or ""}
if m.tool_calls:
asst["tool_calls"] = [{"id": tc.id, "type": "function",
"function": {"name": tc.function.name, "arguments": tc.function.arguments}}
for tc in m.tool_calls]
messages.append(asst)
if not m.tool_calls:
break
for tc in m.tool_calls:
args = json.loads(tc.function.arguments or "{}")
result = DISPATCH[tc.function.name](**args)
messages.append({"role": "tool", "tool_call_id": tc.id, "content": result})
print(f"prompt tokens: {prompt_tokens}, completion tokens: {completion_tokens}")
return messages[-1].get("content", "")

if __name__ == "__main__":
weave.init("glm-5-2-weave-demo")
print(run_agent("Implement rpn.py so the full test suite passes. Run the tests to confirm."))

What the model did, step by step, in the traced run:
  • Step 1: read_file("tests"), which listed the directory rather than erroring, so it saw test_rpn.py.
  • Step 2: read_file("tests/test_rpn.py") to read the spec, including the divide-by-zero case.
  • Step 3: write_file("rpn.py", ...), an 839-byte implementation.
  • Step 4: run_tests(), which returned 8 passed in 0.01s.
  • Step 5: a one-paragraph summary of what it built, then it stopped.
The whole run cost 2,823 prompt tokens and 345 completion tokens as reported by the API, with reasoning tokens not broken out in the usage object. The implementation is worth a look, because it shows the model reasoning about what it did not need to write:
def evaluate(expression):
tokens = expression.split()
stack = []
operators = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"/": lambda a, b: a / b,
}
for token in tokens:
if token in operators:
if len(stack) < 2:
raise ValueError("Insufficient operands")
b = stack.pop()
a = stack.pop()
stack.append(operators[token](a, b))
else:
try:
stack.append(int(token))
except ValueError:
try:
stack.append(float(token))
except ValueError:
raise ValueError(f"Unknown token: {token}")
if len(stack) != 1:
raise ValueError("Leftover operands")
return stack[0]
The test suite expected a ZeroDivisionError on evaluate("1 0 /"), and the model did not write an explicit check for it. It did not need to; Python's own / raises that error, and the test passes on the native behavior. It handled the cases that needed handling, insufficient operands, leftover operands, and unknown tokens, and left the rest to the language.
Two practical notes from running this :
First, thinking is on by default, so a small max_tokens can be spent entirely on reasoning before any content or tool call appears; give it real headroom.
Second, even at temperature=0.0 the exact tool ordering varied between runs: one read the directory first, another ran the tests first to see the import failure. What stayed constant was the shape, explore then implement then verify, and the outcome. Worth remembering before you assert determinism about a hosted MoE.
💡
In W&B Weave, the trace shows run_agent at the root with the tool calls nested underneath in order, and each glm-5.2 completion captured alongside its full message list and token counts. Because the OpenAI client is auto-patched, you can open any step and see exactly what the model saw and what it returned, which is what makes a multi-step agent legible. The reward here, a passing test suite, is the same kind of verifiable signal the RL sections described, and the same kind an agent could try to game, which is why the trace is the thing you want to inspect.


Notable limitations of GLM-5.2

  • It is a new release, and while the headline long-horizon numbers were run by third parties, broad independent replication is still early.
  • Self-hosting is heavy. At 753B, even the FP8 weights want eight high-memory GPUs with tensor parallelism, which puts local deployment out of reach for most individuals.
  • The hosted API is operated by a Chinese company, which is a data-sovereignty consideration for some teams and a non-issue for others. It goes away entirely if you self-host the MIT weights.
  • The 1M window is Zhipu's "solid" claim, and models can still hallucinate near the top of a very long context. Independent long-context recall testing is still catching up.
  • Fine-tuning is not offered through the GLM Coding Plan. Customizing the model on your own data means self-hosting the open weights.

Conclusion

GLM-5.2 is the strongest open-weight coding model available as of mid-2026, and the reasons are specific. A shared indexer keeps a million-token context affordable, an improved MTP layer keeps decoding fast, and a post-training stack built on the open slime framework produced its long-horizon coding behavior.
The choice worth remembering is the reinforcement learning one - when trajectory compaction broke the assumptions that group-relative methods depend on, Zhipu paid for a critic and went back to PPO. That is the kind of decision that tells you how a model was built, and it is the part the benchmark tables leave out.
The caveats hold. It trails the closed frontier on the hardest from-scratch engineering, self-hosting a 753B model is heavy, and broad independent replication is still early. For repository-scale work with a long context, though, it is close enough to the frontier and open enough to run on your own terms that it is worth putting in front of a real task. The demo above is one way to do that with full visibility into every step, and if you want it inside your own coding agent, the last section gets you there.

Bonus: Pointing Opencode at GLM-5.2

If you use opencode, GLM-5.2 drops in as a custom provider through the same OpenAI-compatible endpoint. opencode loads the AI SDK's @ai-sdk/openai-compatible adapter, so one provider block is enough. Location matters here: put it in the global config at ~/.config/opencode/opencode.json, or a project-level opencode.json. A file placed anywhere else is ignored without warning, and the giveaway is that the provider never appears in opencode models.
{
"$schema": "https://opencode.ai/config.json",
"provider": {
"zai-coding": {
"npm": "@ai-sdk/openai-compatible",
"name": "Z.ai Coding Plan",
"options": {
"baseURL": "https://api.z.ai/api/coding/paas/v4"
},
"models": {
"glm-5.2": { "name": "GLM-5.2" }
}
}
}
}
The key goes in your credential store, not the config file. Run opencode auth login, choose Other, enter the provider id zai-coding, and paste your z.ai key. Opencode stores only the credential and reminds you that the provider still needs the config block above, so both steps are required. Confirm the provider loaded with opencode models | grep glm, which should print zai-coding/glm-5.2. Then a one-shot run against the Coding Plan endpoint:
opencode run -m zai-coding/glm-5.2 "Write a Python function evaluate(expr) that computes a reverse Polish notation expression supporting + - * /. Return the code only."
GLM-5.2 answered with a compact evaluator:
def evaluate(expr):
stack = []
for token in expr:
if token in "+-*/":
b = stack.pop()
a = stack.pop()
if token == "+":
stack.append(a + b)
elif token == "-":
stack.append(a - b)
elif token == "*":
stack.append(a * b)
else:
stack.append(int(a / b))
else:
stack.append(token)
return stack[0]
This is the leaner version of what the model wrote in the traced demo. Given only a one-line prompt it produced the happy path and left out the operand and token guards, since nothing here demanded them. In the API demo a test suite was the spec, and the same model wrote the error handling to satisfy it. That contrast is the article's own point in miniature - with verifiable checks in the loop the model builds to pass them, and with a bare prompt it builds the shortest thing that reads as correct.
Use the Coding Plan base URL shown above if you are on a subscription, or https://api.z.ai/api/paas/v4 for pay-as-you-go API billing. For the full 1M window, use glm-5.2[1m] as the model id.
Here are the snips of the steps I did -
  1. 

2.

3.

Iterate on AI agents and models faster. Try Weights & Biases today.