Skip to content
SurogateSurogateDocs
↑↓ to move↵ to openesc to close

Tiny GLM-5.3-Flash

This example lets you exercise the full GLM-5.3-Flash training path on one GPU without downloading the real model. First create a deterministic, randomly initialized 2.34M-parameter checkpoint locally, then train it:

bash
python examples/sft/glm/create_dummy.py --output models/dummy-glm-5.3-flash --index-topk 32
surogate sft examples/sft/glm/dummy-full.yaml
surogate sft examples/sft/glm/dummy-lora.yaml

Run these from the repository root. The generator needs Transformers with glm5_next support, PyTorch, tokenizers and safetensors. It downloads no model or tokenizer and won’t overwrite a nonempty directory. Training uses one NVIDIA GPU; pick a free device with CUDA_VISIBLE_DEVICES.

The model keeps the released architecture’s 3-KDA/1-MLA cycle across eight layers, three leading dense MLPs, four routed experts with top-2 selection, a shared expert, four residual streams and 20 Sinkhorn iterations. Hidden width is 128, KDA has two 32-wide heads, and MLA has two 64-wide heads. A byte-level tokenizer and tiny vision tower make the checkpoint loadable with Transformers. The examples train on text only. The random weights and bundled dataset are for checking the implementation, not for model quality, and this fixture tells you nothing about the memory the 320B model needs.

The byte tokenizer includes GLM’s reasoning/tool control tokens and the released chat template, copied from zai-org/GLM-5.3-Flash-BF16 revision a5b45eb41df6402735dedc900be14a42e8d5e538 under its MIT license. It renders actual tool schemas, calls and observations. Tool prompts need a longer context than the short SFT examples use.

To test a tool call, execution, token-preserving second turn, reward, native policy scoring and GRPO adapter update:

bash
CUDA_VISIBLE_DEVICES=7 pytest tests/grpo/test_tool_protocol_gpu.py --slow -q -k glm

This test creates its own 2,048-token dummy fixture. Sampling is scripted so that random weights still call tools; the logits, log probabilities, loss masks, gradients and optimizer update are real. It checks integration, not how well an agent learns. Function tools work across all the supported GRPO families; see agentic rollouts.

The checkpoint uses the released tensor names, separate Q/K/V convolution weights and separate expert projections, so it goes through the real importer. Native tests compare forward outputs with Transformers and check CUDA derivatives against autograd:

bash
pytest tests/test_glm5_next_dsl.py -q
CUDA_VISIBLE_DEVICES=0 pytest tests/train/test_glm5_training.py tests/train/test_kda_triton.py tests/train/test_glm_dsa.py -q

The shared-policy GRPO check generates tokens, scores them, updates the adapter, and verifies that serving keeps the same base allocation. It uses the local dummy checkpoint and needs no reward environment or external inference service:

bash
CUDA_VISIBLE_DEVICES=0 SUROGATE_SHARED_MODEL="$PWD/models/dummy-glm-5.3-flash" \
SUROGATE_SHARED_GRAPHS=1 SUROGATE_SHARED_TOKENS=120 \
pytest tests/grpo/test_shared_model_gpu.py --slow -q

The same test file also builds its own random sparse fixture and checks 248-token rollouts against packed training scores before and after real updates, with one or two training rows, greedy and seeded sampled generation, CUDA graphs, and non-default LoRA scaling. These cases don’t need SUROGATE_SHARED_MODEL; select them with -k glm_long_rollout.

For the 2,040-token diagnostic, create a separate checkpoint with a larger context:

bash
python examples/sft/glm/create_dummy.py --output models/dummy-glm-long \
--index-topk 32 --max-sequence-length 2048
CUDA_VISIBLE_DEVICES=7 surogate sft examples/sft/glm/dummy-long-context.yaml
CUDA_VISIBLE_DEVICES=0 SUROGATE_SHARED_MODEL="$PWD/models/dummy-glm-long" \
SUROGATE_SHARED_GRAPHS=1 SUROGATE_SHARED_BATCH=2 \
SUROGATE_SHARED_SEQ_LEN=2048 SUROGATE_SHARED_TOKENS=2040 \
pytest tests/grpo/test_shared_model_gpu.py --slow -q -k generation_scoring

On GPU 7 (RTX 5090), the 2,040-token diagnostic matched training log probabilities within 3.9e-7 before and after adapter updates. That validates the tiny random checkpoint at that context length; it says nothing about full-checkpoint throughput or memory.

The long-context SFT config sets long_context: true, which tiles the dense, routed and shared expert MLPs. GLM’s clamps and LoRA contributions survive tile recomputation. The indexer also reuses its score scratch across 128-query tiles on its own. See long-context memory for buffer sizes and the remaining costs. The native MLP regression checks full training and LoRA with packing, gradient accumulation, recomputation and CUDA graph settings:

bash
CUDA_VISIBLE_DEVICES=7 pytest tests/train/test_glm_long_context.py -q

Native-colocate uses the trainer’s model. GLM prefills each prompt once and keeps FP32 KDA state, convolution history, pooled indexer keys and normalized MLA latents across decode calls. Concurrent requests share batched projection/MLP execution but keep separate page tables and recurrent states. Completed requests return cache pages to the pool; any adapter or base-weight change invalidates all sessions. Training and serving share the base and adapter allocations, including when training uses CUDA graphs. The frozen reference policy excludes LoRA updates. Use BF16 adapters with the MoE layers. This fixture fits one GPU; the full checkpoint’s base weights must still fit whatever training topology you choose.

Text training supports sequences longer than index_topk (32 with the command above, 256 by default in the generator, 2048 in the released checkpoint). Native Triton DSA kernels normalize and pool keys, score and select pools, expand selected token indices, and run sparse attention forward/backward. They live in surogate/kernels/triton/glm_dsa.py and are registered through the JIT manifest compiler. As in the Transformers reference, the indexer is frozen. Packed samples reset convolution, recurrence and pooling, and sparse indices never cross document boundaries. Tests lower top-k to eight so the small fixture exercises sparse selection in both full and LoRA training.

Current limits:

  • BF16 model activations, normalized ungrouped routing, and a full indexer on each MLA layer. Pool size must be a power of two and divide index_topk. Both tail selection settings are supported. Context is limited by the configured maximum sequence length and available memory.
  • Indexer score scratch is bounded to O(B * min(T, 128) * ceil(T / pool_size)) FP32 elements during training/prefill. Keys and selected token indices still scale with context length. Each query scans all pools, and top-k uses sorting rather than a tuned radix-selection kernel.
  • long_context: true tiles dense, routed and shared expert MLPs in resident BF16 training with ep_size: 1. With CPU weight streaming or expert parallelism, experts run the ordinary way. Permutations, residual streams, selected attention indices and KDA states still consume sequence-dependent memory.
  • Native-colocate requires one GPU with resident unquantized base weights and BF16 LoRA adapters. Continuous batching and prompt caching are automatic; cached prompts are cleared after policy updates. See the single-GPU GRPO guide for memory and concurrency settings.
  • Native-colocate keeps rollout and scoring log-probabilities consistent, which can make training slower than ordinary SFT. Set doc_masking: true.
  • Indexer auxiliary training, vision training, MTP training and sequence-chunked pipeline state carry are not supported yet. Full expert-weight training requires ep_size: 1. Native exports contain the text-training weights, not a complete multimodal checkpoint.

BF16 training uses the vendored FLA 0.5.2 chunked KDA kernels in surogate/kernels/triton/fla_kda. The trainer compiles and caches 19 KDA kernel manifests, and the C++ runtime launches them directly, so you don’t need the flash-linear-attention package installed. The upstream MIT license and pinned revision ship with the vendored copy.

The integrated path supports forward/backward, Q/K normalization, GLM’s bounded per-channel decay, packed documents, CUDA graph replay, recomputation, full training, LoRA and native-colocate. Forward intermediates are recomputed in backward and scratch storage is reused between layers. Head dimensions 8, 16, 32, 64 and 128 are covered by GPU tests; the dummy model uses 32. doc_masking: false uses the CUDA reference path for training KDA. Isolated FP32 KDA tests also use that reference; the complete DSA model requires BF16 activations. Fragmented packing uses more temporary state memory, because each document needs its own chunk states.

To reproduce the numerical and native kernel timing comparison:

bash
CUDA_VISIBLE_DEVICES=0 python benchmarks/bench_glm_kda.py --length 256 --dim 128

On an RTX 5090, [B,T,H,D]=[1,256,2,128] gave a maximum BF16 output difference of 0.000031 and gradient relative RMS differences below 5e-6 against the CUDA reference. CUDA graph replay with FP32 chunk intermediates measured:

KDA operationCUDA referenceFLA chunk forwardFLA rollout-parity forward
Forward4.10 ms0.181 ms0.258 ms
Forward + backward174.0 ms1.247 ms1.324 ms

These timings include GPU document metadata preparation and backward recomputation, exclude compilation, and use about 5.67 MiB of temporary KDA storage. They measure isolated KDA kernels, not full-model training speedups or the additional cost of fixed-reduction GEMMs. The recurrent forward processes tokens sequentially, so its cost grows with document length. Both forward modes use the FLA chunk backward.

Next: long-context memory explains the tiling these configs rely on, and the single-GPU GRPO guide shows how to run RL on the same checkpoint.