Skip to content

glm5-next: align with upstream GLM5-Next - #331

Closed
amangupta-tether wants to merge 13 commits into
temp-11018from
glm5-next/align-upstream
Closed

amangupta-tether wants to merge 13 commits into
temp-11018from
glm5-next/align-upstream

Conversation

@amangupta-tether

Copy link
Copy Markdown

Replaces temp-11018's own GLM5-Next port with upstream's merged implementation (ggml-org#27773 + ggml-org#29745), then re-adds the fork-only behaviour upstream doesn't have.

Commits

  1. Reverts of the fork's GLM5-Next port: support GLM-5.3-Flash, support tensor-parallel execution, preserve k-pool history across sequence edits, reject invalid metadata during model load.
  2. Upstream, cherry-picked: add GLM-5.3-Flash (GLM5-Next) support (#27773) and glm5-next: give dead indexer slots unique scatter rows (#29745).
    • One mtmd conflict: both the Qwen3VL tiling and the GLM5V preprocessors are kept.
    • Upstream brings recurrent rollback for GLM5-Next, the mHC helpers shared with deepseek4, the persistent k-pool layout with per-sequence staleness, and a build_attn_mha stream-view fix for permuted q.
  3. llama : drop restored GLM5-Next indexer state with seq_rm: temp-11018 has no llama_kv_cache::state_clear (llama : fix K/V and recurrent state cleanup after failed restores ggml-org/llama.cpp#27530), so a failed restore drops the sequence with seq_rm as before.
  4. Re-applied fork commits: tensor-parallel execution (-sm tensor), and the stricter metadata validation (throws instead of asserts, GLM5V pixel limits). The validation commit also restores the --glm5-kpool-sequences test.
  5. llama : align the hybrid-idx k-pool code with upstream: hybrid-idx now matches ggml master (159c651), i.e. the k-pool changes from llama: fix qwen4exp ggml-org/llama.cpp#29751, llama : clamp kpool re-pool bound to existing pools ggml-org/llama.cpp#29805 and qwen4exp: fix tests ggml-org/llama.cpp#29819, plus the indexer_kpool_row / indexer_kpool_by_order hparams.
  6. glm5-next: pool k-pool cells in sequence order: a fix for upstream's version.
    • Upstream pools runs of consecutive positions. After a sequence edit leaves gaps (e.g. seq_add during a context shift), no run completes and the tail only counts positions, so surviving cells are never selected. With live positions 0, 1, 3, 4, the token at 5 attended only to {4, 5}.
    • temp-11018 had already fixed this by grouping cells in sequence order. This commit does the same through upstream's by-order k-pool mode.
    • The shared-token case of the test now expects the token's first sequence only, which is what the KQ mask attends to (seq_id[0]).
  7. glm5-next: prefer CUDA sparse FA over the latent gather: restores the fork's choice of the CUDA sparse FA path when every DSA layer is on CUDA and n_kv is large, plus the 512/512 ncols1=8 sparse kernel case and its test-backend-ops coverage.
  8. glm5-next: keep reading indexer.index_share_mtp: restores the GGUF key and converter output that glm5-next: enable sparse NextN MTP draft head #316's GLM5-Next MTP work reads.

Testing

  • test-llama-archs: --glm5-kpool-sequences, --glm5-invalid-metadata, --qsa-unified-multiseq, --mtp-shared-cpu, --hadamard-contracts, and -a glm5-next|qwen4exp|deepseek4|qwen35moe on CPU all pass.
  • test-backend-ops -o FLASH_ATTN_EXT -b CUDA0: 3997/3997 pass (RTX PRO 6000).
  • GLM-5.3-Flash IQ2_XXS on GB10, wikitext-2 perplexity, ctx 8192, 2 chunks:
build PPL s/pass
this PR 3.5696 ± 0.0763 88.1
ggml master (159c651) 3.5696 ± 0.0763 87.5
temp-11018 3.5661 ± 0.0763 89.8

A greedy completion is coherent.

  • Not tested on hardware: tensor-parallel execution. The single-GPU box only runs the Meta rows of test-llama-archs as SKIP.

Relation to other PRs

🤖 Generated with Claude Code

amangupta-tether and others added 13 commits October 2, 2026 11:57
This reverts commit d37224a.

Replaced by the upstream GLM5-Next implementation (ggml-org#27773)
below; fork-only behaviour is re-added on top of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This reverts commit 4efc6ac.

Replaced by the upstream GLM5-Next implementation (ggml-org#27773)
below; fork-only behaviour is re-added on top of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This reverts commit c23700b.

Replaced by the upstream GLM5-Next implementation (ggml-org#27773)
below; fork-only behaviour is re-added on top of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This reverts commit 9560410.

Replaced by the upstream GLM5-Next implementation (ggml-org#27773)
below; fork-only behaviour is re-added on top of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Rebase GLM-Next support onto master, and migrate to llama-memory-hybrid-idx

* Add initial MTP support

* Merge branch optimizations. Reduce allocated compute buffer size, speed up long context decode, fla, and slight MTP improvements.

* Review driven changes, remove env vars, protect tensors

* Strip MTP for initial PR

* Clean up after mtp strip

* Clean up after mtp strip

* Update speculative.cpp

* Update llama-context.h

* Clean up after mtp strip

* Fix tokenizer ignore merges

* Improve quantization protection selection

* Refactor mhc helpers, graph base

* Lint Fixes

* Apply suggestions from code review

Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>

* Skip glm5-next in model saver, fix CRLF

* Skip glm5-next in sweep

* Remove T4 fallback

* Review cleanup

* Review suggestions

* Defer separate MTP gguf handling to MTP PR, drop filter

* Repad n_head_kv

* kpool init apply

* Order by descending score

* Drop guard

* read kpool from hparams, clarify kpool cache flags, remove kpool_build_state(nullptr)

* Add glm5-next support to model saver and add arch test fixture

* Review cleanup

* Kpool pooled caching clarify

* Add multi stream support

* Finish Rebase

* Sparse FA fir DSA prefill

* Const

* Update llama-model.cpp to fix rebase error

* gguf-py : merge tensor map entries for HC tensors

* model : use build_gdn_l2_norm in GLM5_NEXT implementation

* chore : remove trailing whitespace

* model : use new OP precision setting API in GLM5_NEXT implementation

* mtmd : use ggml_swiglu_clamp in GLM5V and apply the image token limit

The two clamps around swiglu_split are what ggml_swiglu_clamp already does,
so the clamp bounds collapse back to one value. GLM5V also never called
set_limit_image_tokens(), so --image-max-tokens had no effect.

Assisted-by: Claude Opus 5
(cherry picked from commit 46d18e1)

* llama : keep the GLM5-Next k-pool layout across ubatches

The layout was rebuilt from a full cell scan on every ubatch. Pools are fixed
by the positions relative to the sequence's first one, so the layout now lives
on the memory and a ubatch only appends to it.

A sequence edit no longer stales every pooled key either, only the ones at or
after the edited position, which makes a tail seq_rm free. The pooling subgraph
is built unconditionally so the graph shape no longer changes every kpool
tokens, and the pool axis is folded into rows before soft_max, which otherwise
exceeds the CUDA gridDim.y limit past n_kv 262144.

Assisted-by: Claude Opus 5
(cherry picked from commit 5d1c40b)

* model : write the GLM5-Next recurrent rollback checkpoints

The conv state and the delta net state were only written to the live row, so a
rollback restored whatever the checkpoint rows happened to hold. Take the same
route as kimi-k3: build_recurrent_attn for the state, and write all K_rs conv
groups. That also drops a state view that assumed contiguous rows.

Enroll the arch in test-recurrent-state-rollback, which catches this under its
garbage-filled cache pass.

Assisted-by: Claude Opus 5
(cherry picked from commit 5ace37e)

* llama: fix PR ggml-org#27773 test-save-load-state restore failure

Clear the attention and indexer cache data after a failed hybrid state restore so restored NaNs cannot affect a later sequence.

Assisted-by: Codex

* llama: fix PR ggml-org#27773 gpu-rocm graph reallocation

Reserve the full GLM5-Next pool capacity and dirty pool count. The gpu-rocm Test step aborts when n_new grows while the graph node count stays fixed; CUDA, Vulkan, Metal, and WebGPU checks report the same error.

Assisted-by: Codex

* llama : fix GLM5-Next k-pool layout staleness after edits and shared teardown

Two defects in the cross-ubatch k-pool layout added by the k-pool commit:

1. Wrong results. An edited sequence only rebuilt its pool layout when its cell
   count changed, so if the first ubatch after an edit added back exactly as many
   cells as were removed, the stale position-to-cell list survived. With a unified
   cache and more than one sequence, where another sequence takes the freed cells,
   the reused layout points at the wrong cells (CPU: large logit drift, CUDA: NaN).
   Rebuild whenever the sequence is stale, not only on a size mismatch.

2. Slowdown. "shared" mode was assumed to end only with an edit that forces a
   rebuild, but sharing also ends when the other sequence is removed. The survivor
   kept shared = true, pinning cache_safe off and re-pooling every pool on every
   ubatch (server trigger: n>1 completions with -kvu, via the seq_cp in
   copy_state_to). In seq_rm, if the layout has shared cells, stale every sequence
   so one rebuild re-derives sharing and cache_safe returns to 1.

Assisted-by: Claude Opus 5

* llama : fix build_attn_mha stream stride for non-contiguous q

build_attn_mha split the batch into streams with a stream stride of
q->nb[3]/n_stream. That only equals one stream's span, (ne[2]/n_stream)*nb[2],
when q is contiguous. GLM5-Next is nope-only, so it does not concat a rope part
and passes the permuted q_absorbed straight in, where nb[3] != ne[2]*nb[2]; the
stride was then n_head times too large and every stream s >= 1 read another
head's queries. Split-KV (-np N without --kv-unified) multi-stream prefill was
wrong for every stream past the first. Unified KV and decode were unaffected
(n_stream == 1, and decode takes the gather path). Other MLA models concat rope
so q is contiguous and the computed value is unchanged for them.

Compute the stride from the token dimension, which is identical for a
contiguous q.

Assisted-by: Claude Opus 5

* llama : re-derive GLM5-Next k-pool sharing on state_read/state_drop

The shared-cell teardown added to seq_rm (stale every sequence when the layout
has shared cells, so a survivor does not keep shared = true and pin cache_safe
off) was missing from the other paths that can free shared cells: state_read
and state_drop staled only the one sequence. Apply the same re-derivation there
and correct the comment that claimed sharing ends only via an edit or seq_rm.

Assisted-by: Claude Opus 5

* quant : drop duplicate GLM5-Next hc_ filter

The hc_ name filter was listed twice in the GLM5_NEXT protection block.

Assisted-by: Claude Opus 5

* glm5-next: scope K-pool cache access to indexed operations

* glm5-next: keep K-pool access in hybrid index memory

* glm5-next: keep mHC graph builders model-local

* glm5-next: mark only touched pools per ubatch

---------

Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>
Co-authored-by: Stanisław Szymczyk <sszymczy@gmail.com>
Co-authored-by: Piotr Wilkin <ilintar@gmail.com>
(cherry picked from commit 649dcb1)
The sparse indexer mask is built with a set_rows scatter. Padded pools,
absent sequences and missing tail cells all pointed to the same n_kv
sentinel row, and invisible pools picked by top_k to fill the selection
overlap the tail cells of the token, so several CPU threads wrote the
same element (ThreadSanitizer data race in the sanitize CI).

Allocate the slot mask for both selection paths and route every dead
slot to its own dump row n_kv + slot. Live slots address disjoint cells,
so the scatter indices of a token are unique.

(cherry picked from commit 05af0d2)
temp-11018 has no llama_kv_cache::state_clear (ggml-org#27530),
so a failed hybrid-idx restore drops the sequence with seq_rm as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c879310)
(cherry picked from commit c23700b)
(cherry picked from commit d41996d)
(cherry picked from commit d37224a)
Bring llama-memory-hybrid-idx to ggml-org/llama.cpp master (159c651):
the k-pool changes from ggml-org#29751 (sequence-order pools, pooled-key
positions, a stable re-pool list size), ggml-org#29805 (clamp that bound to the
pools the cache can hold) and ggml-org#29819 (unique cells for the padded
entries), plus the indexer_kpool_row / indexer_kpool_by_order hparams.

qwen4exp on this branch still uses the per-cell QSA inputs, so the old
set_input_qsa stays until qwen4exp moves to the k-pool indexer, and a
failed restore still drops the sequence with seq_rm (no state_clear,
ggml-org#27530, here).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Upstream GLM5-Next pools runs of kpool consecutive positions. After a
sequence edit leaves gaps in the positions (e.g. seq_add for a context
shift), no run completes and the tail only counts positions, so the
surviving cells fall outside both: with live positions 0, 1, 3, 4 the
token at 5 selected only {4, 5}. temp-11018 fixed this by grouping cells
in sequence order; do the same with upstream's by-order k-pool mode.

The shared-token case of --glm5-kpool-sequences now expects the token's
first sequence only: the KQ mask attends to seq_id[0], so cells only in
another sequence are masked whether or not they are selected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Restores temp-11018's choice: when every DSA layer runs on CUDA with flash
attention and n_kv is large enough for the sparse kernels to beat the
dense pass, skip the small-batch latent gather and let build_attn_mha's
n_kv_max route to the CUDA sparse FA. Also keeps the 512/512 ncols1=8
sparse kernel case for 8-query tiles and its test-backend-ops coverage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Restores the GGUF key, hparam and converter output temp-11018 added for
GLM5-Next MTP (index_share_for_mtp_iteration): MTP iterations reuse one
indexer selection. Upstream does not read it yet; the open GLM5-Next MTP
work (#316) consumes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ChicoPinto70

ChicoPinto70 commented Oct 3, 2026 •

Copy link
Copy Markdown

Cool!!!! I test it with GLM-5.3-Flash_320B-A18B-GSQ-RCO-3.5bit in a Dual Xeon E5-2699V3 with 256GB DDR4 and 3xRTX3090. And it worked fine!

But the tensor parallelism and MTP didn't work (I know the pfeifferj model doesn't have NextN layer. I supplied it one).

Ah! And the TG performance increased, in relation to Timkhronos' PR, from 12Tk/s to 14Tk/s!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants