Skip to content

feat: write the GLM and LongCat MLA latent through the latent view - #3176

Merged
inureyes merged 8 commits into
mainfrom
feature/issue-3161-glm-longcat-quant-latent
Nov 19, 2026
Merged

inureyes merged 8 commits into
mainfrom
feature/issue-3161-glm-longcat-quant-latent

Conversation

@inureyes

@inureyes inureyes commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Closes #3161

GLM-4.7-Flash and both LongCat types now write the MLA (kv_latent, k_pe) pair through mla::MlaLatentCache, and a single-token int8 step reads it absorbed (fused Metal kernel up to 2048 keys, composed beyond). GLM covers the single-sequence forward, batched decode, MTP verify (per-row quantized attention on prefix slices, byte-identical to the decode chain) and rollback, and the drafter cache follows the target mode table. LongCat covers both MLA sub-layers per layer, and its model-owned caches take the per-layer mode table.

LongCat is enabled. GLM is not. longcat_flash and longcat_flash_ngram join mla::QUANTIZED_LATENT_FAMILIES and list fp16 and int8 in the registry. glm4_moe_lite stays off the list, so its --kv-cache-mode int8 still resolves to fp16 with the warning.

  • LongCat-Flash-Lite passed the hard gate on an M3 Ultra, measured at 440a5ee. Behind 1024 tokens: 0 decided of 239, 9 flips above 0.11 (largest gap 0.375). Behind 4096: 0 of 121, 5 flips (largest gap 0.25). ppl moves -0.7% and -1.2%. The noise floor is the int8 fused-vs-composed pair: 0 decided and 11 flips. LongCat's fp16 latent has no second kernel. Path counters show absorbed_fused behind 1024 and absorbed_composed behind 4096, with decompressed only on the context pass. Decode int8 vs fp16 is +8.0%, -15.5% and -49.2% at 512, 2048 and 16384 tokens. The 560B longcat_flash shares LongcatFlashNgramModel and was not measured on this host.
  • GLM-4.7-Flash failed the hard gate (after the bf16 dtype fix, 4feb841). Behind 1024 tokens: 1 decided of 193 (gap 2.75). Behind 4096: 0 of 95. That 1 equals the int8 fused-vs-composed noise count (1 decided), so it is at that floor, not below it. Decode int8 vs fp16 before that fix was -0.6%, -11.3% and -39.3%; it was not re-run because GLM stays fp16.

Also fixed:

  • LongCat-Flash-Lite failed to run on any mode, for two reasons:
    • Its quantized word and n-gram embeddings were loaded as dense tables.
    • The MoE passed [B, L, hidden] to SwitchGLU, which throws in its sorted path at 64 or more positions. A new 64-token test covers it.
  • kv_arch now counts LongCat's two latent caches per layer. It used to size them at half.
  • LongCat load now validates the word, embed_tokens and n-gram embedding tables against vocab_size, hidden_size and each embedder's modulus, and rejects n-gram config values that would underflow, divide by zero or overflow, with an error naming the field instead of an out-of-range gather or panic.
  • logit_trace ran GLM's int8 arm as fp16. It now hands the requested mode to the model, as DirectEngine does.

Tests:

  • Tiny models of both LongCat types and of GLM cover absorbed int8 decode, batched rows, MTP verify and rollback, the mode table and the affine byte rate.
  • The production tests now pin int8 for LongCat and fp16 for GLM.
  • Real-checkpoint smoke at fd8ffb3: LongCat-Flash-Lite loads under the new guards and generates coherent text in fp16 (absorbed_composed=1008) and int8 (absorbed_fused=1092, decompressed only on the context pass); GLM-4.7-Flash with --kv-cache-mode int8 reports effective fp16 with the substitution warning.
  • The narrow selectors pass serially on Metal under the GPU lock, and clippy (-D warnings) and fmt pass.

Results: docs/benchmark_results/mla-quantized-latent-glm-longcat-m3ultra-2026-11-19.md.

GLM-4.7-Flash and LongCat cached their (kv_latent, k_pe) pair through KVCache::update_and_fetch, so no quantized latent could reach them. Both now store it through mla::MlaLatentCache: GLM in its single-sequence forward, batched decode and MTP verify and rollback (the drafter cache follows the target mode table), LongCat in both MLA sub-layers per layer, with model-owned caches that take the per-layer mode table. A single-token int8 step reads the latent absorbed.

Neither family joins mla::QUANTIZED_LATENT_FAMILIES, so int8 still resolves to fp16. GLM failed the gate on glm-4.7-flash-4bit: 2 decided-position disagreements behind 1024 and 2 behind 4096 tokens, with a zero fp16 kernel noise floor. LongCat was not traced because its checkpoint did not finish downloading. Tests opt each model in to cover the ported path.

kv_arch now counts LongCat's two latent caches per layer (it sized LongCat at half), and logit_trace hands the requested mode to a model that reports a mode table, which had run GLM's int8 arm as fp16.

Targeted lib tests pass (719), and clippy and fmt pass.

Refs #3161
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Nov 19, 2026
LatentWindow::into_dense returns the dequantized window in the cache's fp16 sidecar dtype. Under a bf16 model (GLM-4.7-Flash is bf16) a multi-token step then mixed bf16 queries with fp16 keys, MLX promoted the attention to f32, and the promotion carried through o_proj into the residual stream, so the int8 arm's whole context pass and its logits ran in f32 while the fp16 arm ran bf16. The GLM gate traces were taken on that arm, so their int8-vs-fp16 numbers conflate the codec with a compute-dtype change.

mla_batched::dense_latent_window casts a quantized window to the queries' dtype; dense windows pass through untouched, so fp16 latent numerics are unchanged. GLM and LongCat multi-token steps use it. New tests build bf16 tiny models of both families and fail before the fix (int8 prefill logits came back f32).

The results doc, CHANGELOG and turbo-kv-cache.md now say the gate must be re-measured, correct the noise-floor rows (GLM's fp16 latent never runs a second kernel on any trace arm, and the batched-row counters were swapped), and record that the two int8 kernels agree within bf16 rounding at GLM geometry yet move 33 positions.

Refs #3161
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Write the GLM-4.7-Flash and LongCat MLA latent through MlaLatentCache behind the QUANTIZED_LATENT_FAMILIES opt-in, and list a family only if its int8 trace has 0 decided disagreements behind 1024 and 4096.

Findings Addressed

  • The int8 arm ran multi-token steps in f32 under a bf16 model: into_dense returns the fp16 sidecar dtype, bf16 queries met fp16 keys, MLX promoted to f32, and the residual stream stayed f32 through the logits. The GLM gate traces were taken on that arm. Fixed in 4feb841 with mla_batched::dense_latent_window (quantized windows cast to the query dtype, dense windows untouched) for GLM and LongCat, plus bf16 tests for both that fail before the fix. (HIGH)
  • Results doc noise floors were wrong: GLM's fp16 latent recorded absorbed_composed on every arm, so "fp16 fused vs composed changes no position" compared a path with itself, and the batched-row counters for fp16 and int8 were swapped. Doc, CSV, CHANGELOG and docs/turbo-kv-cache.md corrected. (HIGH)

Remaining Items

Verification

  • All stated requirements implemented (gate measurement pending re-run)
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (GLM, LongCat, mla_batched, deepseek_v3, kv_arch: 157 passed; clippy -D warnings clean)

The first GLM trace ran the int8 context pass in f32 (fixed in 4feb841), so the gate was re-run on the fixed build with glm4_moe_lite temporarily listed. It still fails: 1 decided-position disagreement behind 1024 tokens (gap 2.75) and 0 behind 4096, against a gate of zero. That count equals the int8 fused-vs-composed kernel-noise floor (1 decided, gap 6.5), and the composed int8 arm has 0 against fp16. The ppl delta is now -3.1% and -0.4%. glm4_moe_lite stays unlisted, so int8 resolves to fp16.

The results doc, CSV, CHANGELOG and turbo-kv-cache.md carry the new numbers, with the pre-fix rows kept as superseded.

Refs #3161
LongCat-Flash-Lite passed the #3161 gate on an M3 Ultra: 0 decided-position disagreements against the fp16 latent behind 1024 tokens (of 239) and 4096 (of 121), 9 and 5 top-1 flips above 0.11 (largest gap 0.375), perplexity -0.7% and -1.2%. The int8 kernel pair (fused against composed) also has 0 decided and 11 flips. longcat_flash and longcat_flash_ngram join mla::QUANTIZED_LATENT_FAMILIES and the registry int8 kv_modes. The 560B longcat_flash shares LongcatFlashNgramModel and is not measured on this host.

Two defects that predate this issue blocked the checkpoint on every mode. The quantized word and n-gram embedding tables loaded as dense embeddings, so the first projection threw; they now load through UnifiedEmbedding. The MoE handed SwitchGLU [B, L, hidden], which works by accident below 64 positions and threw in the sorted path at 64 or more; tokens are flattened first, with a 64-token test.

Decode on the int8 latent: +8.0% behind 512 tokens (fused), -15.5% behind 2048, -49.2% behind 16384. Narrow LongCat, registry, turbo_args, kv_arch, advisor, allowlist and mla tests pass serially under the GPU lock; clippy and fmt are clean.

Refs #3161
The n-gram embedder lookups take ids modulo m + 2i + 1 and cast them to INT32, and MLX gather does not range-check a positive index, so a checkpoint whose embedders, word_embeddings or embed_tokens table was shorter or narrower than the config claims read past the end of the table on an ordinary prompt. Each table is now checked with the shared validate_embedding_table guard, which handles dense and quantized tables.

The config arithmetic also panicked or overflowed on hostile values: emb_neighbor_num below 2, emb_split_num of 0, a hidden_size that is not a multiple of the embedder count, an overflowing ngram_vocab_size_ratio * vocab_size, and vocab sizes above i32::MAX. These are now Err results naming the config field, raised before compute_vocab_mods runs.

LongcatFlashMoE::forward reads the router's configured top_k instead of unwrapping the last index axis, which is the same value.

Tests cover a one-row-short embedders.0 table and emb_neighbor_num of 1.

Refs #3161
@inureyes

Copy link
Copy Markdown
Member Author

Security and Performance Review

Findings addressed (b8cf0c4)

  • MEDIUM: LongCat n-gram embedder tables were never checked against the m + 2i + 1 rows their lookups index, and word_embeddings / embed_tokens were never checked against vocab_size x hidden_size. MLX gather does not range-check a positive index, so a short table read past its end on any prompt. Each table now goes through the shared validate_embedding_table guard, which covers dense and quantized tables.
  • MEDIUM: the n-gram config arithmetic panicked or overflowed on hostile values (emb_neighbor_num below 2, emb_split_num 0, hidden_size not a multiple of the embedder count, an overflowing ngram_vocab_size_ratio * vocab_size, embedder vocab above i32::MAX truncated by the INT32 cast). These are now load errors that name the field.
  • LOW: LongcatFlashMoE::forward used expect on the index axis; it now reads the router's top_k, which is the same value.

Two tests were added (a one-row-short embedders.0, emb_neighbor_num: 1). models::longcat_flash_ngram passes serially under the GPU lock (22 tests), clippy -D warnings is clean, and fmt is clean. The LongCat-Flash-Lite-4bit shapes were checked against the guard by reading the safetensors headers, but the 38 GB model was not loaded.

Checked, no change needed

  • MoE flatten: [tokens, hidden] / [tokens, k] in, reshaped back to [.., k, hidden]. The element counts match and the 64-token test covers the sorted path.
  • The fp16 latent stays bit-identical: store_latent_step returns the dense window for a cache without affine bits, and dense_latent_window returns a dense window untouched. Non-MLA paths are not touched.
  • Sizing uses saturating_mul for the two latent caches per LongCat layer and lowercases the model type.
  • GLM MTP verify/rollback trims packed rows through the same trim, with an int8 rollback test. The drafter mirrors the target's resolved mode, which stays fp16 for GLM.
  • Decode hot path: the PR adds only cheap supports checks and a geometry struct each step. Nothing avoidable was found in this PR's code on the composed path. The -49% at 16384 comes from the merged feat: Store the absorbed MLA latent as affine int8/int4 on DeepSeek V2 #3155 composed kernel, which is past the fused 2048-key limit.

The b8cf0c4 guards (embedding-table shape checks and config arithmetic validation at LongCat load) had no CHANGELOG entry. Add a Fixed entry naming the out-of-bounds gather risk and the config values that now fail with a named error.

Validation: release build, then real loads of longcat-flash-lite-4bit at fp16 and int8 (both load and generate coherent text, int8 runs absorbed_fused=1092) and glm-4.7-flash-4bit with int8 (substitutes fp16 with the warning); cargo fmt --check, both clippy invocations with -D warnings, and the longcat_flash_ngram, glm4_moe_lite and mla_batched test selectors pass.

Refs #3161
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 19, 2026
…m-longcat-quant-latent

# Conflicts:
#	docs/supported-models.md
#	docs/turbo-kv-cache.md
#	examples/logit_trace/kv_mode.rs
#	src/cli/turbo_args_tests.rs
#	src/execution/kv_arch.rs
#	src/lib/mlxcel-core/src/cache/turbo/allowlist.rs
#	src/lib/mlxcel-core/src/mla/latent_pair.rs
#	src/models/mla_batched.rs
#	src/models/registry.rs
@inureyes
inureyes marked this pull request as ready for review November 19, 2026 17:40
@inureyes
inureyes merged commit 7a85fe5 into main Nov 19, 2026
32 checks passed
@inureyes
inureyes deleted the feature/issue-3161-glm-longcat-quant-latent branch November 19, 2026 18:07
inureyes added a commit that referenced this pull request Nov 22, 2026
…2 and V3 (#3202)

* fix: cast the dequantized MLA latent to the query dtype in DeepSeek V2 and V3

A multi-token step over an int8 latent dequantized the window with
LatentWindow::into_dense, which returns FP16. On a bf16 checkpoint those keys
met bf16 queries, MLX promoted the attention to float32, and the float32
carried through o_proj into the residual stream for that step. Both sites now
go through mla_batched::dense_latent_in with the step's q_pe dtype, as the
Kimi and GLM-4.7-Flash sites do (#3174, #3176). A dense (fp16) window is
returned untouched.

Closes #3177.

* fix: cast the dequantized latent on DeepSeek V2's absorbed multi-token step

A multi-token step that the cost model absorbs (a short chunk behind a long enough cache, such as a speculative verify or a chunked prefill tail) reaches MlaLatentCache::attend_preprojected, whose quantized arm dequantized the window to FP16 and ran absorbed_attention with the step's bf16 queries. On a bf16 checkpoint that promoted the step to float32, the same defect #3177 fixes at the decompressed site. The window is now cast to the q_pe dtype there too, for every latent width (int8 and the int4 option of #3189 both take this arm).

The V2 test now also runs a 2-token absorbed step behind the 5-token prefill and checks it stays bf16; it fails without the cast (float32 output). It also restores the tiny_harness_model doc comment that the new test had absorbed.

Refs #3177, #3202

---------

Co-authored-by: Jeongkyu Shin <[email protected]>
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Store a quantized MLA latent in GLM-4.7-Flash and LongCat

1 participant