Repository navigation
feat: implement the DSA lightning indexer (stage 2) - #61
Merged
Merged
Conversation
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.
Member
Author
|
Pushed a follow-up commit addressing findings from a code review: Fixed:
Documented as known limitations, not fixed here (confirmed pre-existing — Full suite: 132/132 passing, zero regressions. |
This was referenced Aug 26, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_topkcached positions once the context grows past that threshold, permlx_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, ornilbelowindex_topk(matching the reference's own inertness rule — dense stays exact in that regime).DeepseekV32Attention— aDeepseekV3Attention-shaped block (identical weight keys/shapes) plus the indexer, applying its selection as a boolean mask ANDed with the causal mask.CacheList(main, indexer)caches per layer, matchingFalconH1's established two-cache pattern and the reference's ownCacheList(KVCache(), KVCache()). Both children areKVCacheSimple, socanTrimPromptCache/trimPromptCachekeep working.DeepseekV32Modelis now standalone rather than subclassingDeepseekV3Model— needed once itsmodelproperty had to become aDeepseekV32ModelInner(paired-cache layers). ReusesDeepseekV3MLP/DeepseekV3MoE/MoEGateunchanged viaargs.v3Configuration; only attention/cache is forked.indexer_rope_interleaveis now decoded and honored (was dead JSON in stage 1 — no indexer existed to apply it to).sanitizekeeps.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 separateL==1/L>1branches. 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_dsacheckpoint is 308GB (per ml-explore#139's own framing, this is deliberate).index_topk, stays finite, and diverges from a same-weights dense run — proves the mask has a real effect, not just that nothing crashed.index_topk, output exactly matches a same-weights model whoseindex_topkis effectively infinite. Weights shared viaModule.update(parameters:)rather thanMLXRandom.seed()reproduction —swift-testingruns tests concurrently by default andseed()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).sanitizetest updated: indexer weights now kept, compressor still dropped.All 130+ tests across the full
mlx-swift-lmsuite pass locally — no regressions inDeepseekV3-derived orDeepseekV4tests (the latter a structurally similar but distinct architecture).Still open (flagged, not attempted here)
avlp12/GLM-5.2-Alis-MLX-Dynamic-3.5bpwwith--stream-experts.CacheList-basednewCacheoverride (matches stage 1 — never wired for this model regardless of stage).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.