Skip to content

glm5_next: long contexts on a latent MLA cache (256k on two Sparks) - #54

Closed
taussoe wants to merge 4 commits into
ashhart:mainfrom
taussoe:pr/glm-long-context
Closed

taussoe wants to merge 4 commits into
ashhart:mainfrom
taussoe:pr/glm-long-context

Conversation

@taussoe

@taussoe taussoe commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Fixes #53

Problem

Past its 2,051-token dense window, GLM-5.3-Flash on 0.3.5.1 answers !!!!... on two DGX Sparks, and the per-head
KV cache admits at most ~40k tokens there (details in the issue).

What this changes

  • Latent cache (glm5_next/cuda/latent.py). The DSA layers are NoPE MLA: head h's key is Wk_h c, its value
    Wv_h c, with c the token's 512-wide normalized latent. The cache keeps c only (bf16, 1 KB a token and layer,
    shared by the heads and both ranks). The query absorbs kv_b's key blocks (read as the checkpoint stores them,
    4-bit), attention runs over latents, and the attended latent is expanded once through the value blocks.
    TF_GLM_LATENT=0 keeps the per-head path.
  • Sparse selection (sparse.py). Token selection for all rows of a chunk at once over the pools the chunk can
    see, rounded up to a power of two (fixed sizes also stopped allocator growth at 128k), and the top 512 pools by
    one radix-select kernel: the same set as a stable descending sort, 45 → 6 ms a layer for a 2,048-row chunk at 128k.
  • CUDA graphs past the dense limit (graphs.py), one per pool bucket.
  • Prompt-chunk kernels: latent attention tiles of all 32 heads (16 in decode windows); the KDA chain of a prompt
    chunk as three kernels (state-independent work for all rows, then the delta rule alone). Both keep the bits of the
    kernels they replace, tested.
  • Admission (cuda/geometry.py): mla_geometry(latent=True) sizes the latent cache and its scratch, so
    --context 0 allocates 487,495 tokens on two Sparks.
  • Several conversations: up to 8 conversations' prompts are kept; when another conversation takes the caches, a
    kept prompt's rows are saved, within TF_GLM_CACHE_GIB (default 3) for states and rows together. As in 0.3.5, only
    prompts are snapshotted.
  • TF_GLM_PROFILE=1 prints a prefill's time and memory by block.
  • docs/recipes/glm-5.3-flash.md describes the latent cache and the measurements below.

Upstream's prefill matmuls and grouped CUDA experts are used unchanged.

Exactness

Every kernel computes a row alone in an order fixed by its own position, so drafted replies equal serial ones and
prompt chunks give the same bits for any chunking. New tests: tests/cuda/test_glm_latent.py (latent attention
against a float64 definition of the expanded MLA attention, window rows against serial steps, 16- vs 32-head tiles),
tests/cuda/test_glm_long_context.py (drafted == serial past 2,051 tokens, sparse graphs == eager, resumed ==
fresh prefill, switching conversations, the memory budget), plus radix top-k and KDA three-kernel bit tests in
test_glm_kernels.py. One existing check in test_prompt_chunks_leave_the_same_state compares prefill and decode
cache rows within 3e-2 instead of 2e-2 for the latent rows (values up to ~4, a few bf16 steps).

tests/cuda: 336 passed, 7 skipped on a GB10.

Measured

Two DGX Sparks (GB10, 128 GB each), Vontra/GLM-5.3-Flash-MLX-4bit-MTP, MTP drafts only, --context 262144, a cold
synthetic codebase with one hidden fact:

Prompt Prompt reading First token Decode at that depth Hidden fact
32,770 tokens 1,155 tok/s 28 s 42.7 tok/s found
130,839 tokens 1,110 tok/s 118 s 45.1 tok/s found
262,099 tokens 1,033 tok/s 254 s 40.1 tok/s found
0.3.5.1, 32,770 tokens (--context 36864) 626 tok/s 52 s – !!!!

At least 14 GB stayed free on each Spark through the 256k prompt. Short prompts (64 tokens, 5 seeds; code/chat,
sampled/greedy): 49.8 / 42.3 / 60.9 / 48.0 tok/s, against 51.0 / 42.7 / 55.9 / 47.8 for 0.3.5.1. Drafted == serial 9/9.

🤖 Generated with Claude Code

@taussoe

taussoe commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

Added a commit: prompt chunks now absorb/expand through one bf16 head GEMM (decode keeps its kernels). Two Sparks: 32k prompt 1,292 tok/s (25 s), 128k 1,231 tok/s (106 s), 258k 1,139 tok/s, needle found each time; drafted == serial 9/9.

Taus Soe and others added 4 commits September 28, 2026 11:50
Past its 2,051-token dense window, GLM-5.3-Flash on 0.3.5.1 answered "!!!!..."
on two DGX Sparks (--context 36864, a 32k prompt), and the per-head cache
admitted at most ~40k tokens. This keeps the DSA layers' 512-wide latent
instead of per-head keys and values and makes the sparse path fast:

- latent.py: the cache holds c (1 KB a token and layer, both ranks); queries
  absorb kv_b's key blocks (read as stored, 4-bit), outputs expand through its
  value blocks; dense and sparse attention over latents, 32-head tiles in
  prompt chunks, 16 in decode windows (same bits).
- sparse.py: token selection for all rows of a chunk over the visible pools,
  bucketed to powers of two; the top 512 pools by one radix-select kernel
  (the same set as a stable sort).
- graphs.py: CUDA graphs past the dense limit, one per pool bucket.
- kda: prompt chunks run the chain as three kernels (same bits).
- geometry.mla_geometry(latent=True): admission sizes the latent cache, so
  --context 0 allocates 487,495 tokens on two Sparks.
- engine: prompts of several conversations kept (rows saved when another
  conversation takes the caches) within TF_GLM_CACHE_GIB (default 3).
- TF_GLM_PROFILE: prefill time and memory by block.

Two DGX Sparks, MLX 4-bit checkpoint, MTP drafts, cold synthetic codebase
with one hidden fact: 32k prompt 1,155 tok/s (28 s to the first token), 128k
1,110 tok/s (118 s), 256k 1,033 tok/s (254 s), fact found each time; decode
42.7 / 45.1 / 40.1 tok/s at those depths; short prompts 49.8 / 42.3 / 60.9 /
48.0 tok/s; drafted == serial 9/9. tests/cuda: 336 passed, 7 skipped on a
GB10 (tests/cuda/test_glm_latent.py and test_glm_long_context.py added).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RgHrzgLoSTDm9VAdr5jVb7
Prompt chunks absorbed queries into kv_b's key blocks and expanded outputs
through its value blocks with the decode kernels (4-bit, a row at a time,
~1.5-3 TFLOP/s). They now use bf16 copies of those blocks (made once,
~17 MB a layer and rank) on one tensor-core GEMM over all heads with fixed
64x64x64 tiles: any chunking gives the same bits, as 0.3.5's prompt path
requires; decode keeps its kernels. Tested for chunk invariance and against
the decode path (within 2e-2).

Two Sparks, cold synthetic codebase: 32k prompt 1,155 -> 1,292 tok/s (first
token 25 s), 128k 1,110 -> 1,231 tok/s (106 s); drafted == serial 9/9.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RgHrzgLoSTDm9VAdr5jVb7
…nd prompt weights

mla_geometry(latent=True) now also counts the kept conversations' budget
(TF_GLM_CACHE_GIB, default 3) and the bf16 kv_b copies prompt chunks use.
TF_GLM_PROFILE prints the highest memory torch reserved.

Two Sparks, --context 262144, a 257,711-token prompt: estimate 100.19 GiB of
the 103.01 GiB budget, torch's peak 94.17 GiB reserved, at least 18 GB of
system memory left on each Spark; needle found, drafted == serial 9/9.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RgHrzgLoSTDm9VAdr5jVb7
@taussoe

taussoe commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto 0.3.6.1, and the memory estimate now covers the measured peak: mla_geometry(latent=True) also counts the kept conversations' budget (TF_GLM_CACHE_GIB, default 3) and the bf16 kv_b copies prompt chunks use. Two Sparks, --context 262144, a 257,711-token prompt: estimate 100.19 GiB of the 103.01 GiB budget, torch's peak 94.17 GiB reserved, at least 18 GB of system memory left on each Spark; needle found, drafted == serial 9/9. tests/cuda pass on a GB10 (490 passed). Thanks for fixing #53 so quickly!

@taussoe
taussoe force-pushed the pr/glm-long-context branch from e6ba57f to 31226b0 Compare September 28, 2026 10:17
ashhart added a commit that referenced this pull request Sep 28, 2026
…; tool_choice "required"

- Review of #54: prompts prefill under no_grad again, the prompt chunk size is an engine argument, the engine admits a context before importing any kernel module, and only EXL3 buffers allocate the shared expert's scratch.
- The latent estimate counts one prompt chunk's partials and the pool scores, and a dropped kept conversation frees its rows at once. On two Sparks at 262,144 tokens: drafted == serial 9/9, resumed == fresh 6/6, 8 streams equal their solo runs, needles found at 32k, 131k and 256k, and the torch peak is 93.7 GiB against a 96.1 GiB estimate. Next-token loss is within 0.001 nats of the per-head cache.
- tool_choice "required" and a named tool make the reply call an offered tool on both servers, drafted or serial (#52).
@ashhart

ashhart commented Sep 28, 2026

Copy link
Copy Markdown
Owner

Thanks @taussoe, for #53 and for this PR. The issue came with a clean repro and a fix already running, and the PR
came with tests for every kernel it touches, so both were quick to act on.

Your commit lands in 0.3.6.2 as you wrote it, under your name (fb985b86). Our changes sit on top as separate commits.

What caused #53: the per-head sparse attention kernel kept each row's partial sums at c * 128 + r, in buffers
sized for 128 rows. That held while GLM read prompts 64 rows at a time. 0.3.5 moved prompts to 2,048-row chunks,
so past about 2,176 tokens rows 128 and up read each other's partials and wrote past the buffer. The NaNs came
out as token 0, which is !, and the MTP head drafted ! too, so every draft was accepted. That's why the
broken replies streamed at ~110 tok/s. Your latent kernels index partials by the chunk's own row count, so your
PR fixed it on its default path. We shipped the fix for the old kernel in 0.3.6, together with the same 128-row
limit in the BF16 matmul EXL3 checkpoints use.

The latent cache is the bigger win: attention memory drops from about 384 KB to about 19 KB a token on each rank
(latents plus the indexer's keys), so two Sparks hold a 256k window. On our Sparks the hidden fact was found at
4k, 32k, 128k and 256k, prompts read at 850-1,140 tok/s (261,906 tokens in 261-309 s across two runs), and decode ran at
32-40 tok/s at 256k. Drafted replies equal serial ones (9/9 at 2k-16k), resumed prompts equal fresh ones (6/6),
and four interleaved conversations each equal their solo replies.

What we changed on our side: prefill runs under torch.no_grad again; the prompt chunk size is a GlmEngine
argument instead of an environment variable; the GB10 peak probe stays out of the tree; the engine admits a
context before importing any kernel module, since the CPU admission tests failed on machines without triton;
only EXL3 allocates the shared expert's scratch, as before; the latent estimate counts the prompt chunk's
partials once and 4 bytes a pool score. The kept conversations needed one more fix. When _take_over dropped a
saved snapshot to make room, the loop's copy of the list kept its rows alive while the next conversation's rows
were cloned, so a 256k prompt after a 131k conversation briefly held two 2.34 GiB copies. Dropped rows are now
freed at once, the snapshot a request resumes from is never dropped, and the kept conversations get
min(TF_GLM_CACHE_GIB, what the window leaves), inside the memory estimate.

On short prompts the latent path rounds attention differently, so some replies differ from 0.3.6 by a token
(greedy code opens " Fibonacci sequence:" instead of " The Fibonacci sequence"); speed is unchanged, and
TF_GLM_LATENT=0 gives 0.3.6's replies exactly.

Thanks again. This was a lot of careful work, and it shows in the tests.

@ashhart ashhart closed this Sep 28, 2026
BlivionIaG referenced this pull request in BlivionIaG/TensorFold Oct 20, 2026
…; tool_choice "required"

- Review of #54: prompts prefill under no_grad again, the prompt chunk size is an engine argument, the engine admits a context before importing any kernel module, and only EXL3 buffers allocate the shared expert's scratch.
- The latent estimate counts one prompt chunk's partials and the pool scores, and a dropped kept conversation frees its rows at once. On two Sparks at 262,144 tokens: drafted == serial 9/9, resumed == fresh 6/6, 8 streams equal their solo runs, needles found at 32k, 131k and 256k, and the torch peak is 93.7 GiB against a 96.1 GiB estimate. Next-token loss is within 0.001 nats of the per-head cache.
- tool_choice "required" and a named tool make the reply call an offered tool on both servers, drafted or serial (#52).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GLM-5.3-Flash on CUDA answers "!!!!" past the 2,051-token dense window (0.3.5.1)

2 participants