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

Long Context Training

Set long_context: true to cut MLP activation memory during training and policy scoring, so longer sequences fit on the same GPU. Tokens pass through the up/gate projection, SwiGLU and down projection in tiles. The backward pass recomputes each tile and uses it right away, accumulating weight and LoRA gradients across tiles.

yaml
sequence_len: 32768
long_context: true
recompute: true
per_device_train_batch_size: 1
lora_dropout: 0

Pick a sequence length that fits the model’s context limit and your memory. The same options work for SFT and GRPO. See the local GLM example for a small checkpoint that can exercise this path on one GPU.

An MLP processes each token independently, so it can run on a few tokens at a time. Tiling reduces its intermediate storage from O(B*T*intermediate_size) to O(min(B*T, hidden_size)*intermediate_size). Inputs, outputs and residual streams still cover the full sequence. The compiler excludes tile intermediates from full-sequence activation arenas and saved tensors.

For example, one BF16 intermediate buffer with width 11,008, hidden size 4,096 and batch size one uses:

TokensOrdinary bufferTiled buffer
2,04843 MiB43 MiB
32,768688 MiB86 MiB
131,0722,752 MiB86 MiB

The fused up/gate projection is twice this size; SwiGLU has the size shown. These are single buffer sizes, not total training memory. Backward also needs tile gradients and, for GLM, unclamped projection values.

Tiling trades extra kernel launches and backward recomputation for memory. The cost depends on the model, tile count and hardware. Short inputs fit in one tile, so they save little memory.

The compiler recognizes the dense, bias-free up/gate → SwiGLU → down pattern used by Llama, Qwen3, dense Qwen3.5 blocks, Qwen3-VL and GLM’s leading dense layers. It preserves GLM’s asymmetric activation clamps and applies LoRA in both forward execution and backward recomputation.

GLM also tiles routed and shared expert MLPs in resident BF16 training with ep_size: 1. Routed tiles operate on the permuted tokens, preserving routing, asymmetric clamps and grouped LoRA arithmetic. Wide expert intermediates shrink from O(B*T*top_k*moe_intermediate_size) to O(min(B*T*top_k, hidden_size)*moe_intermediate_size). The permutation, routing and hidden-width input/output buffers still span the full sequence.

Expert tiling does not cover CPU weight streaming or expert parallelism. Other models’ MoE branches, and activations such as NemotronH’s ReLU-squared MLP, keep their existing execution paths.

Native GPU regression tests cover BF16 full training and LoRA, including packed documents, gradient accumulation and recomputation. Tiling changes GEMM shapes and the gradient reduction order, so BF16 gradients need not be bit-identical. The tests check numerical tolerances, and check scoring with identical weights.

Use lora_dropout: 0. Nonzero adapter dropout is rejected, because tile recomputation does not reproduce the ordinary path’s dropout mask. The tiled GEMMs don’t use the ordinary FP8/FP4 recipe dispatch, and the BF16 checks described here don’t validate those recipes.

You can leave use_cuda_graphs: true on. The runtime splits execution: tiled MLP groups run eagerly, and eligible segments around them use CUDA graphs. Capture-unsafe operations can still force eager execution.

GLM’s frozen DSA indexer always scores 128 queries at a time, in both training and prefill, whether or not long_context is set. Keys are pooled once; each query tile is scored, selected and expanded before its scratch buffer is reused. Packed-document boundaries and deterministic tie ordering are preserved.

The FP32 score buffer shrinks from B*T*ceil(T/index_kpool) elements to B*min(T,128)*ceil(T/index_kpool). At 131,072 tokens, batch size one and pool size 16, that is 4 GiB → 4 MiB for scores alone. Key buffers and selected token indices still grow linearly with sequence length; the indices also scale with index_topk and the optional tail width. Tiling bounds score storage, but each query still scans the pools and top-k still sorts.

GLM native-colocate stores normalized MLA latents and reconstructs only the selected K/V projections during decode. Its MLA and indexer histories grow in 128-token pages, which return to a shared pool when a request finishes. Reconstruction applies the original BF16 projection and LoRA operations, so rollout and scoring match; it trades extra projection work for less persistent cache memory. Use options.glm_rollout_parity = True for consistent GLM rollout/scoring arithmetic. Native co-locate turns it on automatically.

GLM workspace sizing uses the shape-based heuristic and graph bounds, without the legacy multi-GiB minimum and MoE allowance. Graphs with no standard FlashAttention operations don’t reserve its 1 GiB attention workspace. Saved MoE buffers are allocated as needed before capture.

On GPU 7 (RTX 5090), the 4,096-token dummy GLM with BF16 LoRA rank 8 and recompute: true used the following device allocations after two updates:

ConfigurationAllocated memory
Before expert tiling and workspace changes7,306 MiB
Current runtime, long_context: false4,962 MiB
Current runtime, long_context: true4,852 MiB

The combined reduction is about 34%. These numbers include library caches and describe this small checkpoint only; they are not transient peaks or full-model capacity estimates. To reproduce the comparison, run each case in its own process on an otherwise idle GPU:

bash
CUDA_VISIBLE_DEVICES=7 python benchmarks/bench_glm_memory.py
CUDA_VISIBLE_DEVICES=7 python benchmarks/bench_glm_memory.py --tiled

Model and optimizer state, KDA chunk states, residual streams, token permutations and sparse attention indices can still take a lot of memory at long context. See GLM limitations and native-colocate.