Skip to content

feat: implement the DSA lightning indexer (stage 2) - #61

Merged
solderzzc merged 2 commits into
mainfrom
feat/glm52-dsa-stage2-indexer
Aug 26, 2026
Merged

solderzzc merged 2 commits into
mainfrom
feat/glm52-dsa-stage2-indexer

Conversation

@solderzzc

Copy link
Copy Markdown
Member

Summary

Closes SharpAI/SwiftLM#139. Follow-up to #111's stage 1 (dual-cache dense attention, submodule bump SwiftLM#138). Implements the DSA "lightning indexer" that restricts attention to the top index_topk cached positions once the context grows past that threshold, per mlx_lm/models/deepseek_v32.py / glm_moe_dsa.py.

What's new

  • DeepseekV32Indexer — the lightning indexer (wq_b/wk/k_norm/weights_proj), scoring cached keys against the query and returning the top-k selection, or nil below index_topk (matching the reference's own inertness rule — dense stays exact in that regime).
  • DeepseekV32Attention — a DeepseekV3Attention-shaped block (identical weight keys/shapes) plus the indexer, applying its selection as a boolean mask ANDed with the causal mask.
  • Paired CacheList(main, indexer) caches per layer, matching FalconH1's established two-cache pattern and the reference's own CacheList(KVCache(), KVCache()). Both children are KVCacheSimple, so canTrimPromptCache/trimPromptCache keep working.
  • DeepseekV32Model is now standalone rather than subclassing DeepseekV3Model — needed once its model property had to become a DeepseekV32ModelInner (paired-cache layers). Reuses DeepseekV3MLP/DeepseekV3MoE/MoEGate unchanged via args.v3Configuration; only attention/cache is forked.
  • indexer_rope_interleave is now decoded and honored (was dead JSON in stage 1 — no indexer existed to apply it to).
  • sanitize keeps .indexer. weights now (a real module loads them); still drops .attn.compressor. (a separate, still-unimplemented feature).

Design decision: boolean mask instead of absorbed-MLA gather

The reference's decode path gathers only the selected latent/rope entries because it keeps K/V in absorbed per-token latent form until attention time. This port's DeepseekV3Attention-derived structure (unchanged from stage 1) materialises full per-head K/V before attention, so instead of gathering, the top-k selection is applied as a boolean mask over the existing dense SDPA call — masking non-selected positions in a full attend-over-everything call is numerically identical to attending only the gathered subset, just without the compute/memory saving. One code path handles both prefill and decode, rather than the reference's separate L==1/L>1 branches. Documented at length in the file header — per ml-explore#139's explicit callout, this is where reviewer scrutiny should go.

Tests

No real checkpoint used — the smallest glm_moe_dsa checkpoint is 308GB (per ml-explore#139's own framing, this is deliberate).

  • Forward pass finite/shape-correct (existing).
  • Sparse path engages past index_topk, stays finite, and diverges from a same-weights dense run — proves the mask has a real effect, not just that nothing crashed.
  • Inertness property (the issue's proposed self-check): below index_topk, output exactly matches a same-weights model whose index_topk is effectively infinite. Weights shared via Module.update(parameters:) rather than MLXRandom.seed() reproduction — swift-testing runs tests concurrently by default and seed() is global mutable state, so reseed-then-construct raced with other tests' unseeded construction (verified empirically: passed in isolation, failed as part of the full suite, fixed by not depending on global RNG state at all).
  • sanitize test updated: indexer weights now kept, compressor still dropped.

All 130+ tests across the full mlx-swift-lm suite pass locally — no regressions in DeepseekV3-derived or DeepseekV4 tests (the latter a structurally similar but distinct architecture).

Still open (flagged, not attempted here)

Test plan

  • swift build --target MLXLLM — clean, no warnings in the new code.
  • swift test --filter DeepseekV32Tests — 8/8 passing.
  • swift test (full suite) — 130+ tests, 0 failures.
  • CI green.
  • Real-weights smoke test (follow-up, not this PR).

Follow-up to #111's stage 1 (dual-cache dense attention). Implements the
sparse indexer that restricts attention to the top index_topk cached
positions past that threshold, per mlx_lm's deepseek_v32.py /
glm_moe_dsa.py reference.

## What's new

- DeepseekV32Indexer: the lightning indexer (wq_b/wk/k_norm/weights_proj),
  scoring cached keys against the query and returning the top-k selection,
  or nil below index_topk (matching the reference's own inertness rule).
- DeepseekV32Attention: a DeepseekV3Attention-shaped attention block (same
  weight keys/shapes) plus the indexer, applying its selection as a
  boolean mask ANDed with the causal mask.
- Paired CacheList(main, indexer) caches per layer, matching FalconH1's
  established two-cache pattern and the reference's own
  CacheList(KVCache(), KVCache()) per layer. Both children are
  KVCacheSimple, so canTrimPromptCache/trimPromptCache keep working.
- DeepseekV32Model is now standalone rather than subclassing
  DeepseekV3Model — needed once its `model` property had to become a
  DeepseekV32ModelInner (paired-cache layers) rather than
  DeepseekV3ModelInner. Reuses DeepseekV3MLP/DeepseekV3MoE/MoEGate
  unchanged via args.v3Configuration; only attention/cache forked.
- indexer_rope_interleave is now decoded and honored (was silently
  ignored — dead JSON since stage 1 had no indexer to apply it to).
- sanitize keeps .indexer. weights (a real module now loads them);
  still drops .attn.compressor. (a separate, still-unimplemented
  long-range-compression feature some checkpoints in this family carry).

## Design decision: boolean mask instead of absorbed-MLA gather

The reference's DeepseekV32Attention decode path gathers only the
selected latent/rope entries because it keeps K/V in absorbed per-token
latent form until attention time. This port's DeepseekV3Attention-derived
structure (inherited unchanged from stage 1) materialises full per-head
K/V before attention, so instead of gathering, the top-k selection is
applied as a boolean mask over the existing dense SDPA call — masking
non-selected positions in a full attend-over-everything call is
numerically identical to attending only the gathered subset, just
without the compute/memory saving. This also means one code path is
correct for both prefill and decode, rather than the reference's
separate L==1/L>1 branches. Documented at length in the file header for
reviewer attention, per ml-explore#139's explicit callout that absorbed MLA is
where scrutiny should go.

## Tests (no real checkpoint — smallest glm_moe_dsa checkpoint is 308GB)

- Forward pass finite/shape-correct (existing, still passes unchanged).
- Sparse path engages past index_topk, stays finite, AND diverges from
  a same-weights dense run (proves the mask has a real effect, not just
  that nothing crashed).
- Inertness: below index_topk, output exactly matches a same-weights
  model whose index_topk is effectively infinite. Weights are shared via
  Module.update(parameters:) rather than MLXRandom.seed() reproduction —
  swift-testing runs tests concurrently by default, and seed() is
  global mutable state, so two reseed-then-construct calls raced with
  other tests' unseeded construction and were not reliably reproducible
  (verified empirically: passed in isolation, failed as part of the
  full suite).
- sanitize updated: indexer weights now kept, compressor still dropped.

All 130+ tests across the full mlx-swift-lm suite still pass (verified
locally — no regressions in DeepseekV3-derived or DeepseekV4 tests, the
latter being an unrelated but structurally similar architecture).

## Still open (out of scope here, flagged for follow-up)

- No real-weights verification yet (per #111/ml-explore#139: first real run should
  use avlp12/GLM-5.2-Alis-MLX-Dynamic-3.5bpw with --stream-experts).
- Quantized KV cache is not wired up for the new CacheList-based
  newCache override (matches stage 1's behavior — this was never wired
  for DeepseekV32Model regardless of stage).
A code review found 5 confirmed issues in the DSA stage-2 implementation
(previous commit). Cross-checked each against FalconH1 (the established
CacheList precedent this code follows) to separate genuinely new bugs
from pre-existing limitations of the paired-cache pattern that FalconH1
already has too.

## Fixed (genuine bugs, not shared by FalconH1)

- **Critical**: the causal mask was built from `mainCache.offset` *after*
  `mainCache.update(...)` had already run — `KVCacheSimple.update`
  mutates `.offset` as its first side effect, so every mask built from it
  here was sized one batch too wide against the actual key count. This
  crashed on a broadcast/shape mismatch the moment any real (non-nil)
  cache was used past `index_topk` — every existing test passed
  `cache: nil`, which trivially collapses `mainCache?.offset ?? 0` to 0
  in both the buggy and correct forms, so nothing caught it. Fixed by
  capturing the offset once before the update call. Verified red/green:
  temporarily reintroducing the bug reproduces the exact predicted
  broadcast crash against the new real-cache test below.
- `newCache(parameters:)` now honors `parameters.maxKVSize`, building a
  `RotatingKVCache` pair instead of unbounded `KVCacheSimple` when set —
  this model doesn't get `KVCacheDimensionProvider`'s default behavior
  for free once its cache shape became a `CacheList` pair, so it has to
  be handled explicitly (FalconH1's own `newCache` has the identical gap
  and was not the pattern to follow here).
- `callAsFunction`'s `cache as? [CacheList]` cast silently discarded a
  type-mismatched cache and ran with no cache at all (a silent "the
  model forgot everything" failure, worse than a crash). Now fails
  loudly with a clear message instead.
- Efficiency: the sparse-mask branch recomputed a causal mask on every
  decode step (`L == 1`) even though a length-1 causal mask is provably
  a no-op there — skipped entirely instead of materialising and ANDing
  a mask that can never change the result.

## Documented, not fixed here (pre-existing, shared by FalconH1)

`attentionWithCacheUpdate(cache: nil, ...)` — needed because the cache
is manually pre-updated above to size the top-k mask — opts this model
out of TurboKV's compressed-history decode/prepend and
QuantizedKVCacheProtocol routing, both of which only engage on a
non-nil cache. Confirmed FalconH1 has the identical gap (it doesn't
even route through `attentionWithCacheUpdate` at all for its own
CacheList-paired attention). KV-quantization (`--kv-bits`) also
silently no-ops for any `CacheList`-based model, confirmed via
`maybeQuantizeKVCache`'s own comment ("MambaCache and CacheList don't
use traditional KV quantization"). Making the CacheList pattern itself
TurboKV/quantization-aware is a cross-cutting change affecting every
paired-cache model in the codebase, not scoped to this PR — documented
in code comments at the call site instead of silently left unexplained.

## Tests

- New: real (non-nil) cache test — prefill past index_topk in one call,
  then one decode step — exercising both offset-read sites the bug
  lived in. Red-green verified against the reintroduced bug.
- New: newCache honors maxKVSize, confirming RotatingKVCache for both
  cache-pair slots when set (and KVCacheSimple, the previous default,
  when not).
- Full suite: 132/132 passing (was 130 before this PR's tests, +2 here),
  zero regressions.
@solderzzc

Copy link
Copy Markdown
Member Author

Pushed a follow-up commit addressing findings from a code review:

Fixed:

  • Critical: causal mask built from mainCache.offset after mainCache.update() had already mutated it — sized every mask one batch too wide, crashing on any real (non-nil) cache past index_topk. Every existing test used cache: nil, which trivially hid this. Added a real-cache regression test and red-green verified the fix against the reintroduced bug.
  • newCache(parameters:) now honors parameters.maxKVSize (RotatingKVCache pair instead of unbounded).
  • cache as? [CacheList] now fails loudly on a type mismatch instead of silently discarding the cache.
  • Skipped a provably-no-op causal mask recompute on every decode step.

Documented as known limitations, not fixed here (confirmed pre-existing — FalconH1, the established CacheList precedent, has the identical gaps and doesn't even route through attentionWithCacheUpdate): --kv-bits and --turbo-kv are effectively unsupported for any CacheList-based model in this codebase today, this one included. Making the pattern itself quantization/TurboKV-aware is a cross-cutting change affecting every paired-cache model, out of scope here.

Full suite: 132/132 passing, zero regressions.

@solderzzc
solderzzc merged commit f8da831 into main Aug 26, 2026
6 checks passed
@solderzzc
solderzzc deleted the feat/glm52-dsa-stage2-indexer branch August 26, 2026 06:03
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.2 / DeepSeek V3.2 stage 2: implement the DSA lightning indexer

1 participant