Skip to content

glm5_next: absorbed sparse-MLA prefill (TF_GLM5_PREFILL=absorbed), flat with context — stacked on #9 - #39

Closed
chadhurley25075-png wants to merge 15 commits into
ashhart:mainfrom
chadhurley25075-png:hurley-glm5-prefill-0341
Closed

chadhurley25075-png wants to merge 15 commits into
ashhart:mainfrom
chadhurley25075-png:hurley-glm5-prefill-0341

Conversation

@chadhurley25075-png

Copy link
Copy Markdown
Contributor

Stacked on #9 (base: our fork's glm-5.3-flash; the two commits on top are this PR). Prefill only; decode arithmetic is untouched, so drafted == serial holds by construction and the kit's exactness gate agrees.

The finding. On the Studios, TensorFold's GLM-5.3-Flash prefill fell behind oMLX as prompts grew (−31% at 35K). Profiling the real layers with the recipe-book method, the time was in one place: glm5_next/model.py MLA._prefill. On every 2,048-token chunk the 11 sparse-attention layers un-absorb k and v for all keys of the prefix (two quantized matmuls over [0, end) — O(N²) over a prompt) and run SDPA over every key with the indexer's top-512-block choice as a dense mask. Cost per token grows with position: the reference prefilled 419 / 319 / 165 tok/s at 10K / 35K / 103K on the 512 GB Studio. oMLX is flat because past 4,096 keys it attends on the absorbed latent over each query's top-k ids. KDA and the MoE are identical in both engines and flat — not the problem.

The change: TF_GLM5_PREFILL=absorbed (default stays reference; unset it to roll back). Prefill attention the way this port's own decode path already attends (_attend): queries absorbed into the 512-wide latent, each query over its selected keys (top-k blocks plus the unfinished tail; all keys under 2,048) gathered from the latent cache, two batched matmuls per 512-query sub-chunk (scores in fp32, softmax over each query's keys), values un-absorbed after. Same cache state (latents, indexer keys, pooled blocks), decode rows (≤ 16) untouched, cache layout unchanged. A query costs ~2,051 keys whatever the context, so the cost per token is flat. The second commit is the batched-matmul form of the same attention (a batch of single-query SDPA calls read the gathered keys once per head and was 20% slower on the 8-layer profile).

Measured, full model, M3 Ultra 60-core 256 GB, fixed-seed prompts, T=0, 64-token replies

build 10.4K cold 35.1K cold 102.7K cold warm re-send resumed (+1 line)
reference (last night's production, 0.3.0-based, same kernels) 331 tok/s · TTFT 31.4 s 260 · 135.0 s 143 · 719 s 0.06 / 0.09 / 0.19 s 0.47 / 1.10 / 2.89 s
absorbed, same build 336 · 31.0 s 334 · 105.1 s 309 · 332 s 0.06 / 0.09 / 0.19 s 0.22 / 0.25 / 0.35 s
absorbed, this PR on 0.3.4.1 (today) 337 · 30.9 s 333 · 105.3 s 307 · 334.5 s 0.88 / 1.12 / 1.47 s 0.94 / 1.21 / 1.57 s
oMLX 0.7.0.dev2, 256 GB-class Studio (for scale) 351 346 — — —

+1% / +28% / +116% over the reference at 10K / 35K / 103K; TTFT at 100K 719 → 332 s; flat with context; 0 OOMs. Today's warm and resumed TTFTs are ~1 s rather than last night's 0.1–0.4 s: that is 0.3.4.1's grid (a reply is prefilled again from the last grid point on the next turn), the same on every family, not this patch. The 512 GB Studio went 419 / 319 / 165 → 416 / 409 / 364. Rolled out to four Studios last night behind the kit (30/30 answers, 8/8 tools, 5/5 drafted == serial, 19/19 cancel, 10/10 no leaks on each).

Exactness, plainly. Decode is untouched, so drafted == "draft": false (today on this PR: 15/15 drafted == serial, 58.8 / 48.8 tok/s). Prefill bits differ from the reference prefill's in the last bf16 places, the same way oMLX's differ from TensorFold's — the documented prefill ≠ decode limit — so a long-prompt reply can change on a near-tie (seen once each at 32K and 100K on a needle prompt where reference and absorbed were each wrong). A resumed prompt equals a fresh one on the same build through the 0.3.4.1 grid, as for every family. Tests: the full suite passes in both modes (392 passed / 71 skipped each, S4).

One part of the original patch is not here: pipelining prompt chunks with mx.async_eval in the serial engine's _feed (+5% on the M3, bit-identical). 0.3.4 removed that engine and the lane engine feeds chunks itself, so I left the engine alone; if you would like it in _family_feed it is a three-line change and I can measure it there.

Thank you for the recipe book. "Profile the real layers, find where the time actually goes, change one thing, gate it on exactness" is the whole method here, and it is why this was a two-evening finding rather than a two-week one.

— Chad

indexer-bf16 and others added 15 commits September 27, 2026 13:44
- GLM-4.5 and later (GLM-5.3-Flash) write <tool_call>NAME<arg_key>K</arg_key><arg_value>V</arg_value>...
  </tool_call>. A payload that is neither JSON nor <function=...> is read that way; a call with no arguments is
  just the name.
- The chat template writes string arguments raw and every other value as JSON, so each value is converted by
  the type its parameter declares (coerce_glm_value), as oMLX's _coerce_param_value does, without its repair of
  near-valid JSON. Noted in THIRD_PARTY_NOTICES.md (Apache-2.0).
- tests/test_glm_tool_calls.py: typed values, parallel calls, raw strings kept verbatim, unknown tools stay text.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FaooCnQeKYApFByWS3Y7gz
(cherry picked from commit 0294b50)
The glm5_next package gains load(): the same checkpoint (Vontra/GLM-5.3-Flash-MLX-4bit-MTP) on one Mac with
256 GB or more, beside the CUDA engine, which is unchanged.

- model.py: a forward pass from the checkpoint layout (four hyper-connected streams, 34 KDA and 11 sparse MLA
  layers, 288-expert MoE), checked sublayer by sublayer against mlx-vlm's glm5_next on the real weights. kv_b
  stays as stored and is applied per head. Prefill uses MLX's kernels; the decode path (up to 16 rows) gives
  every row its one-row bits.
- kernels/glm/flash/v1: qmv_rows for groups of 64 and one-launch row kernels for the router, the routed experts,
  the hyper-connection mix, the indexer gate and KDA's f_b / g_b (strategy B); the KDA decode step in one kernel
  a layer (ported from mlx-vlm ashhart#2105) and sparse attention reading the chosen keys by index (from mlx-vlm ashhart#2245);
  the MoE block in five kernels, a hyper-connection boundary in three, MLA's same-input projections stacked
  (strategy B, the logits unchanged).
- mtp.py / runtime.py: the checkpoint's MTP layer as the draft head. KDA states are rolled back by replaying the
  kept rows from the window's entry state through the same kernel, so drafts can chain. A load-time check turns
  drafting off when a multi-row forward does not reproduce one-row steps. depth_for picks the depth from each
  position's acceptance and the measured verify cost; --mtp-drafts defaults to 1 for this family.
- The decode graph goes to the GPU every 2 layers (mx.async_eval); the shared expert runs in kernels of its own
  beside the router.
- THIRD_PARTY_NOTICES.md credits mlx-vlm (ashhart#2030, ashhart#2105, ashhart#2245, ashhart#2107) and the MLX kernels whose arithmetic the
  row kernels repeat.

Full model on an M3 Ultra (512 GB, MLX 0.32.0), 4,096 keys: one-row step 35.7 -> 22.3 ms, 3,578 -> 1,197
kernels a token. Through the server: short answer 62.4 tok/s (46.9 serial), code 63.6, file edit 93.6, 18k
context 48.0, 23k agent prompt 53.4. Drafted replies are byte-identical to "draft": false (5 of 5 prompts).
Tests: tests/test_glm5_*.py on a small synthetic checkpoint (CPU and Metal), plus real-weight tests with
TF_GLM5_MODEL set.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FaooCnQeKYApFByWS3Y7gz
(cherry picked from commit ca6c4bd)
- README: the model row (182 GB, 256 GB Mac), what the checkpoint needs (MLX 0.32.2 or later on a 256 GB Mac),
  the M3 Ultra speeds, the --mtp-drafts default, the kernel folder.
- RUNBOOK: the pull, and the MLX version to install.
- docs/recipes/glm-5.3-flash.md: an Apple Silicon (MLX) section after the DGX Spark recipe: what decides the
  speed, what paid, speeds and fixed depths, where the time goes, tried and rejected, traps, exactness, limits.
- The recipe book lists it among the Mac families.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FaooCnQeKYApFByWS3Y7gz
(cherry picked from commit 0834afd)
The serial engine is gone in 0.3.4; glm5_next now declares LANES = True and its runtime speaks
engine.lane_family's contract, as Flash Next does: exact_width and window_costs measured at load
(check_windows), speculate/settle/unspeculate for the MTP head with chained drafts kept on the GPU,
one-step-ahead rounds for the serial reference (gpu_tokens), and engine_settings for the row cap.
The engine's own cost-based depth rule replaces the runtime's depth_for. Tests drive LaneEngine.
…5_next

check() no longer refuses Mia's EXL3 checkpoint on a Mac itself (require_readable does, through
QUANT_METHODS), so the CUDA experiment's check runs the same everywhere; the hub test takes a
family's own kernel_version prefix.
…-5.3-Flash) — layouts.py name map, fused conv, absorbed embed_q/unembed_out, mtp.0 head with bf16 eh_proj, mixed-bit tensors (QSplit stacks, per-row projections), lossless bf16 for fp32 mixes/routers; tests on a converted twin

(cherry picked from commit a1c345c76c069ac0d9b45cf7b60e3f50948368d7)
…e MTP head on the loading thread (a lazy load first evaluated in a request thread raised 'no Stream(cpu, 0)')

(cherry picked from commit 27f83095451166931eaf778cb0f6f3a0cf2e30b1)
…quad_rows) with MLX 0.32.2's one-row qmv_fast and qmv_quad loops, an 8-bit shared expert in the fused MoE, an opt-in 8-bit f_b/g_b fold in the KDA kernel; tests at the abliterated checkpoint's widths

(cherry picked from commit d9285042ed52213a27fb0793af2c46598393ed21)
…t, a bare <think> closed when thinking is off, TF_GLM5_SPLIT_SHARED, the MTP head reads the normed row by default

From kingjamez's test of PR ashhart#9 on an M5 Ultra (256 GB, MLX 0.32.2; 87.6 tok/s greedy drafted, 68.8 serial,
12 of 12 prompts drafted == "draft": false):

- MLX runs fp32 matmuls as TF32 on M5-generation GPUs by default (median relative error 4e-4 against 3e-8), so
  prefill (MLX's hc_expand) and decode (the row kernels' sequential FMA order) disagreed in the last bf16 bit on
  ~11% of stream values. tensorfold/__init__.py sets MLX_ENABLE_TF32=0 before mlx loads; an explicit value wins.
- GLM-5.3's chat template ignores enable_thinking and always ends the prompt on <|assistant|><think>, so with
  thinking off the model reasoned anyway (99 tokens against 20) and the reasoning landed in content. The server
  closes a trailing bare <think> as the template's own no-reasoning turn (<think></think>); templates that honour
  the switch never end on a bare <think>. His unit test is included.
- TF_GLM5_SPLIT_SHARED=0 combines the shared expert with the router (split stays the default: 3% faster for a
  lone 1-row MoE layer, 2.5% slower end to end on the M5).
- The MTP head reads the final-normed row by default (TF_GLM_MTP_INPUT=normed; raw restores the streams' mean;
  TF_GLM_MTP_NORMED=0/1 still works): 78.8 -> 79.8% first-draft acceptance and 86.9 -> 87.9 tok/s on the M5,
  61-76 -> 66-78% and +0.5 tok/s on the M3 Ultra. Drafts only, so exactness is unchanged either way.

Not folded: VERIFY_MS_M5 and the depth_for table — 0.3.4 dropped depth_for; the lane engine now measures each
window's cost at load and picks the depth from those, so his M5 timings are read off the machine itself.

Co-authored-by: kingjamez <[email protected]>
…TP row and the absorbed prefill move out of Next
… absorbed latent over each query's selected keys (flat cost per token; the reference un-absorbs k/v for every key on every chunk, quadratic)

(cherry picked from commit 66e5cb9223183028a830d3bdbd8760c0b2237d35)
(cherry picked from commit b8ea3d353583; its second half, SerialEngine._feed pipelining chunks with async_eval,
does not apply on 0.3.4 — the serial engine is gone and the lane engine feeds prompt chunks itself)
@ashhart

ashhart commented Sep 27, 2026

Copy link
Copy Markdown
Owner

Thanks @chadhurley25075-png, this is timely: prefill against a standard is one of the two things left before GLM on Mac lands. We'll take it together with #9 into 0.3.5.1 in the next few days, check the absorbed path's output against the current prefill (resumed equal to fresh at every context length) and measure it on long prompts. The PR stays open until then, and you'll be credited as the author.

ashhart pushed a commit that referenced this pull request Sep 28, 2026
…bsorbed

Pull request #39 by chadhurley25075-png: prefill attends the way decode does.
Queries are absorbed into the 512-wide latent space, and each query reads only
its own keys (the indexer's best blocks plus its unfinished tail) gathered from
the latent cache, with values un-absorbed after. The reference prefill
un-absorbs keys and values for every position of the prefix on every chunk, so
its cost and memory grow with the context; the absorbed one stays flat. The
attention is two batched matmuls a sub-chunk of 512 queries, scores in fp32.

Adapted by the maintainer: the pull request's two commits land as one, moved
from the single model.py of the pull request into the split engine (the switch
in config.py, the method in mla.py, per stream as the shared forward calls it).
The code is otherwise the contributor's.
@ashhart

ashhart commented Sep 28, 2026

Copy link
Copy Markdown
Owner

Your absorbed prefill shipped in 0.3.6 as fcca783, under your name, and it's now GLM's only prompt path on Macs. It keeps 128k prompts inside memory where the old path refused them. On top of it, sparse prompt scores now run in bf16 with a precise softmax, with the same bits, which put 8k prompts ahead of mlx-vlm. Thank you!

Release: https://github.com/ashhart/TensorFold/releases/tag/v0.3.6

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.

2 participants