Architecture
~9 min readUpdated: November 2026

GLM-5.4 Loop Transformer Architecture for Coding Agents

GLM-5.4 Loop Transformer Architecture — 750B Recurrent Depth, Gated Progressive Updates, and Hybrid KV Cache for Autonomous Agents

GLM-5.4 establishes the first production 750B Loop Transformer architecture for autonomous engineering agents. By looping 28 weight-shared layers across multiple iterations, it achieves 2T-3T parameter reasoning depth without expanding static memory footprints. Featuring Gated Progressive Updates, Hybrid KV Cache sharing, and fused CUDA kernels sustaining up to 200 tokens/sec, GLM-5.4 cuts chain-of-thought token overhead by 13.8% while matching top frontier coding models. Smoke Monkey Harness and Canvas orchestrate GLM-5.4 across Model Context Protocol (MCP) toolchains with zero telemetry leakage.

Technical Review: Smoke Monkey Core Architecture Team
Tested on Node.js 18+ & BunTypeScript 5.x
Quick Answer & Executive Definition

GLM-5.4 Loop Transformer Architecture for Coding Agents: GLM-5.4 establishes the first production 750B Loop Transformer architecture for autonomous engineering agents. By looping 28 weight-shared layers across multiple iterations, it achieves 2T-3T parameter reasoning depth without expanding static memory footprints. Featuring Gated Progressive Updates, Hybrid KV Cache sharing, and fused CUDA kernels sustaining up to 200 tokens/sec, GLM-5.4 cuts chain-of-thought token overhead by 13.8% while matching top frontier coding models. Smoke Monkey Harness and Canvas orchestrate GLM-5.4 across Model Context Protocol (MCP) toolchains with zero telemetry leakage. Designed as a zero-dependency, open-source TypeScript architecture under the MIT License with native Model Context Protocol (MCP) support and deterministic phase state machines.

Key Architectural Takeaways
Quick Implementation Exampleglm-5-4-coding-agent.ts
glm-5-4-coding-agent.tstypescript
import { createAgent } from '@smoke-monkey/harness';
// Initialize sovereign autonomous engineering agent powered by GLM-5.4 Loop Transformer
const agent = createAgent({
agentId: 'glm-loop-architect',
provider: 'custom',
baseUrl: 'http://localhost:8000/v1',
model: 'zhipu/glm-5.4-FP8',
workspacePath: process.cwd(),
permissions: {
read_file: 'allow',
write_file: 'allow',
run_command: 'ask',
},
sampling: {
temperature: 0.2,
top_p: 0.95,
max_tokens: 32768,
extra_body: {
chat_template_kwargs: {
reasoning_effort: 'high',
loop_iterations: 2,
},
},
},
tools: [
{
name: 'ast_code_analyzer',
description: 'Parses multi-file AST trees to extract type definitions and dependency graphs',
parameters: {
type: 'object',
properties: {
targetFiles: { type: 'array', items: { type: 'string' }, description: 'Repository files to inspect' },
symbolQuery: { type: 'string', description: 'Exported symbol or interface identifier' },
},
required: ['targetFiles', 'symbolQuery'],
},
handler: async ({ targetFiles, symbolQuery }) => {
return { matchedSymbols: [symbolQuery], referencesFound: 18, scope: 'workspace' };
},
},
{
name: 'execute_cargo_verify',
description: 'Executes compiler checks and integration tests for low-level system modules',
parameters: {
type: 'object',
properties: {
testFilter: { type: 'string', description: 'Cargo test filter string' },
},
required: ['testFilter'],
},
handler: async ({ testFilter }) => {
return { exitCode: 0, status: 'pass', output: 'test result: ok. 48 passed; 0 failed;' };
},
},
],
});
// Execute autonomous verification and refactoring loop
const execution = await agent.run(
'Refactor async task worker pool, eliminate mutex lock contention, and verify test passes'
);
console.log('Execution Completed:', execution.summary);
Video Guides

Watch: Related Video Guides

GLM-5.4 is The Best Open Coding Model Yet! (My Early Access Review)

New GLM 5.1 & ZCODE GLM AGENT: As Good as OPUS 4.6? | Free Agent & Cheap Model

GLM-5.4 Loop Transformer Architecture: 750B Recurrent Depth & Weight Sharing

GLM-5.4 is a 750-billion parameter foundation model built on the Loop Transformer architecture, looping 28 weight-shared transformer layers across two iterations to attain 2T-3T parameter reasoning depth without scaling static weight counts. By continuing pre-training on an existing base rather than training from scratch, GLM-5.4 elevates coding intelligence ceilings at nominal compute overhead.

Architectural Breakdown: Looping 28 Layers at 750B Scale

Standard Transformer architectures execute each layer exactly once per forward pass. While scaling depth increases model capacity, adding unique physical layers linearly inflates memory bandwidth requirements and static VRAM footprint. In contrast, GLM-5.4 adapts a pre-trained 750B parameter base model into a Loop Transformer through continued pre-training. A designated middle block of 28 layers executes across two consecutive iterations, allowing hidden state representations to undergo iterative deductive refinement.

Unlike historical approaches such as the 2018 Universal Transformer—which suffered severe compute inefficiency when trained from scratch—GLM-5.4 leverages continued post-pretraining on an already converged foundation model. This raises the intelligence ceiling with only ~10% additional total training compute.

text
Forward Pass Execution Flow:
[Input Embeddings] 
       ↓
[Layers 1-16: Base Feedforward & Early Attention]
       ↓
[Layers 17-44: Shared Recurrent Block — Pass 1 (Global Context & Conservative Gates)]
       ↓
[Layers 17-44: Shared Recurrent Block — Pass 2 (Deep Refinement & Sliding Window KV)]
       ↓
[Layers 45-64: Downstream Synthesis & Unlooped Projections]
       ↓
[Vocabulary Logits]

Gated Progressive Updates: Stabilizing Recurrent Activations

When hidden states are passed repeatedly through identical transformer layers, naive recurrent overwrites trigger exponential activation norm expansion. Unlooped downstream layers subsequently receive out-of-distribution representations, causing severe numerical instability and gradient explosion.

GLM-5.4 solves activation explosion via Gated Progressive Updates. Independent per-token learned gating vectors dynamically scale residual updates across iterations:

  1. Pass 1 (Context Formulation): Gating values remain conservative ($g_t^{(1)} \approx 0.15 - 0.35$), stabilizing dynamic range while establishing broad context across the sequence.
  2. Pass 2 (State Refinement): Gating values open ($g_t^{(2)} \to 1.0$), writing full candidate updates into the residual stream to refine syntax, edge cases, and multi-file dependencies.
  3. Entropy-Adaptive Step Sizing: On complex or ambiguous tokens (such as compiler constraint checks or formal mathematical proofs), the gates open aggressively on the first pass, allocating more dynamic compute to high-difficulty prediction steps.

Hybrid KV Cache: Global Sharing with Local Sliding Windows

In standard attention mechanisms, maintaining independent Key-Value (KV) caches for multiple loop iterations multiplies memory requirements by the loop count ($N_{\text{loop}} \times$). At sequence lengths of 1,000,000 tokens, full KV duplication would render 750B serving commercially infeasible.

GLM-5.4 implements a Hybrid KV Cache Architecture:

  • Global KV Reuse: The second loop iteration directly reuses the sparse global Key and Value vectors computed during the first iteration.
  • Independent Sliding Window: The second pass maintains an isolated, compact local sliding window ($W = 1024$ tokens) for newly updated tokens.
  • Sparse Index Sharing: The sparse attention indexer executes exclusively on pass 1. Pass 2 inherits the identical index selection map at zero re-indexing cost.

By restricting auxiliary cache allocation to a 1024-token sliding window, GLM-5.4 restricts KV memory growth to negligible levels across 1M context windows.

Zero Parameter Growth with 2x Computational Depth

GLM-5.4 preserves the exact static parameter count of its 750B base model while running 28 middle layers twice, effectively doubling reasoning depth per token without increasing model weight storage.

Empirical Benchmarks: Iso-Parameter Ablations & Implicit Loop Reasoning

Empirical ablations across 1B, 4B, 30B, and 750B configurations demonstrate that GLM-5.4's looped architecture concentrates performance gains in multi-step deductive domains like software engineering and formal mathematics. By trading explicit chain-of-thought tokens for implicit hidden-state iterations, GLM-5.4 reduces generation length by 13.8% while matching 2T-3T parameter frontier models on SWE-bench.

Controlled Iso-Parameter Evaluation (30B & 750B Scale)

Zhipu AI conducted controlled iso-parameter ablations comparing unlooped baseline models against looped variants with identical parameter counts and only ~10% additional training compute. Evaluated across long-context software engineering and formal reasoning benchmarks, looped models demonstrated superior execution precision:

BenchmarkMetric / FocusGLM-5.3 (Dense 750B)GLM-5.4 (Looped 750B)Claude 3.7 SonnetDeepSeek R1 (671B)GPT-4.5
SWE-bench Verified% Resolved (Pass@1)65.8%76.4%70.3%79.8%68.2%
HumanEval PlusPass@1 (Python)88.4%93.6%92.1%92.8%89.5%
MBPP PlusPass@1 (Python)85.2%91.2%90.4%90.7%87.1%
Aider Polyglot% Diff Edit Pass71.3%82.5%78.4%83.1%74.9%
GPQA Diamond0-shot Accuracy68.2%77.9%75.2%79.1%71.4%
MMLU-Pro5-shot Accuracy78.9%84.7%83.5%84.0%81.2%
Avg. CoT Token CountThinking Token Length3,840 tokens3,310 tokens (-13.8%)4,200 tokens4,650 tokens3,920 tokens

Implicit Reasoning vs. Explicit Token Bloat

In standard reasoning models (such as DeepSeek R1 and OpenAI o1/o3), intermediate self-reflection is forced out into the sequence as explicit token generation, inflating latency, token pricing, and context consumption. In GLM-5.4, the 28-layer recurrent loop performs self-correction directly within latent vector space.

On benchmarks like GPQA Diamond and MMLU-Pro, average output length drops by 10–14%. The model performs deductive backtracking and candidate hypothesis pruning across its recurrent forward passes before emitting its first token.

Reasoning Shift to Latent Space

GLM-5.4 shifts preliminary hypothesis testing into recurrent hidden layers, eliminating intermediate chain-of-thought slop while accelerating generation speed.

Production Serving Infrastructure: Fused Kernels & Sub-Second Latency

GLM-5.4 sustains 200 tokens/sec during off-peak windows and maintains 70–80 tokens/sec under maximum peak concurrency. Deploying multi-pass looped architectures at 750B scale requires systems-level kernel fusion across attention projections, dynamic gate scaling, and sliding-window KV updates to eliminate PCIe and HBM memory transfer bottlenecks.

Systems-Level Kernel Fusion

In naive implementations, looping middle layers forces the GPU execution pipeline to dump intermediate activations back to high-bandwidth memory (HBM) at the boundary of each iteration. This causes severe memory bus saturation and thermal throttling.

To resolve this, GLM-5.4 serving infrastructure uses custom fused CUDA and Triton kernels:

  • Fused Loop Attention: Computes cross-loop attention and local sliding-window attention in a single SRAM tile pass.
  • In-Register Gated Residual Addition: Multiplies candidate state updates by gate coefficients and accumulates directly in vector registers without intermediate DRAM writes.
  • Zero-Copy Index Inheritance: Reuses precomputed sparsity indices directly from L2 cache.

Hardware Footprint & Precision Quantizations

Quantization FormatTotal Parameter WeightMinimum Required VRAMRecommended Production ClusterGeneration Throughput
FP8 (E4M3/E5M2)750 GB~780 GB8x NVIDIA H100 (80GB SXM5)180–200 tokens/sec
INT4 / MXFP4385 GB~410 GB8x NVIDIA A100 (80GB) / 4x H10090–120 tokens/sec
AngelSlim GGUF Q4_K_M392 GB~420 GB2x Apple Mac Studio M3/M4 Ultra (192GB)18–24 tokens/sec

Production vLLM Deployment Script

Deploy GLM-5.4 in production with 8-way Tensor Parallelism, Loop Transformer support, and sliding-window cache persistence:

bash
docker run --gpus all \
  -p 8000:8000 \
  --ipc=host \
  vllm/vllm-openai:glm-5.4 zhipu/glm-5.4-FP8 \
    --tensor-parallel-size 8 \
    --loop-iterations 2 \
    --loop-layers 28 \
    --enable-sliding-window-kv \
    --sliding-window-size 1024 \
    --tool-call-parser glm_v5 \
    --reasoning-parser glm_v5 \
    --enable-auto-tool-choice \
    --port 8000 \
    --served-model-name glm-5.4

Verification via OpenAI-Compatible API Request

bash
curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "glm-5.4",
    "messages": [
      {"role": "user", "content": "Analyze memory alignment constraints in this SIMD ring buffer."}
    ],
    "temperature": 0.2,
    "top_p": 0.95,
    "extra_body": {"chat_template_kwargs": {"reasoning_effort": "high"}}
  }'

Smoke Monkey Harness Integration: Sovereign Autonomous Coding Loop

Smoke Monkey Harness connects directly to GLM-5.4 through standardized OpenAI-compatible APIs, driving a deterministic 6-phase engineering state machine: Explore, Plan, Edit, Verify, Recover, and Complete. By coupling GLM-5.4's latent loop reasoning with AST chunk replacements and isolated shell execution, Smoke Monkey delivers sovereign software engineering without cloud lock-in.

Multi-Agent Spatial Orchestration in Smoke Monkey Canvas

When orchestrated inside Smoke Monkey Canvas, GLM-5.4 instances operate as specialized autonomous developers across an infinite spatial board. A lead architect agent parses repository tickets, scaffolds architectural blueprints, and delegates sub-tasks to specialized GLM-5.4 worker nodes (backend API implementation, frontend UI rendering, database migration, and fuzz testing).

Every file modification undergoes immediate syntax validation via compiler tooling. If a unit test fails or a TypeScript type check emits an error, the agent transitions into the Recover phase, analyzing compiler diagnostics and self-healing code in sub-second cycles without human intervention.

Deterministic Safety Gates

Smoke Monkey Harness sandboxes all bash execution and git operations with granular per-tool permission rules, ensuring zero unauthorized filesystem modifications.

Google Search Questions & Answers

Frequently Asked Questions

Q:How does the Loop Transformer architecture in GLM-5.4 differ from standard recurrent neural networks?

Unlike classical recurrent networks that iterate over input time steps, GLM-5.4 iterates over internal computational depth across a fixed sequence of tokens. A middle block of 28 weight-shared transformer layers executes two forward passes, refining hidden state activations progressively without expanding static parameter memory.

Q:Why does GLM-5.4 require 10–14% fewer reasoning tokens than models of similar intelligence?

GLM-5.4 executes part of its deductive reasoning within the implicit recurrent depth of its 28-layer loop rather than outputting explicit chain-of-thought tokens. This latent self-correction prunes flawed hypotheses internally, producing concise and accurate code solutions in fewer generated tokens.

Q:How does the Hybrid KV Cache avoid doubling VRAM consumption during looped execution?

The second loop iteration directly reuses the global Key-Value tensors and sparse attention indices precomputed during pass 1. Pass 2 only maintains an independent local sliding window of 1024 tokens for updated representations, keeping auxiliary KV cache overhead to negligible levels even across 1,000,000-token context windows.

Q:What are the exact VRAM and hardware requirements to deploy GLM-5.4 in production?

In native FP8 precision, GLM-5.4 requires approximately 780 GB of VRAM, running on an 8x NVIDIA H100 (80GB) cluster at 180–200 tokens/sec. Under INT4/MXFP4 quantization, the footprint compresses to ~410 GB, deployable on an 8x A100 (80GB) node. Apple Silicon Macs with 192GB unified memory can serve quantized Q4_K_M GGUF checkpoints at 18–24 tokens/sec.

Q:How does Smoke Monkey Harness integrate GLM-5.4 with Model Context Protocol (MCP) tools?

Smoke Monkey Harness connects to GLM-5.4 via vLLM using the glm_v5 tool-call parser. The harness serializes MCP schemas into structured JSON function signatures, monitors the model reasoning tokens, validates tool parameters locally, and executes system commands with strict human-in-the-loop permission sandboxing.

Related Alternatives & Comparisons

Related Architecture Guides

View all guides

Build with Smoke Monkey Harness

Zero dependencies. 24 built-in tools. Human-in-the-loop safety. 100% open source under the MIT License.

npm install smoke-monkey-harness