Skip to content

feat(deepseek-v4): implement HiSA hierarchical sparse attention #549

Closed

Description

@inureyes

Summary

DeepSeek-V4 attention runs over two KV streams per layer: a sliding-window local stream at full token resolution, and (on layers with a nonzero compress ratio) a pooled stream in which a compressor summarizes every r consecutive tokens into one pooled token. On the r == 4 layers the pooled prefix grows without bound, so a per-layer indexer selects the index_topk most relevant pooled positions per query and attention runs over the local window plus only the selected pooled tokens. HiSA (hierarchical indexing for sparse attention) is the selection algorithm: a coarse block-level filter followed by a fine within-block top-k, replacing a flat O(Np) scan.

This issue was filed on 2026-07-01 against a DeepSeek-V4 module that did not exist yet, and its original plan targeted the layout #523 was expected to introduce. #523 has since landed (PR #1455) and implemented the indexer end to end. The body below is rewritten against the code as it actually exists. What remains is validation and operability work, not implementation.

Current state: implemented by #523 / PR #1455

src/models/deepseek_v4_indexer.rs implements the full indexer:

  • Indexer with wq_b, weights_proj, a private Compressor instance at index_head_dim, and n_heads / head_dim / index_topk / index_block / index_keep / scale.
  • All three selection paths as separate, unit-testable functions: flat_select (line 174), hisa_select_decode (line 209), hisa_select_batched (line 263).
  • The dispatch gate (line 153) computes index_block * index_keep in i64 specifically so a large index_block cannot wrap an i32 and let the gate pass while nb = np / index_block is 0.
  • index_block (64) and index_keep (16) are serde defaults, absent from the real checkpoint config, as this issue specified.
  • The three-way attention branch (local only / dense pooled / sparse) and the split-softmax sparse combine sharing one log-normalizer with the per-head sinks live in src/models/deepseek_v4_attention.rs.

Unit tests in src/models/deepseek_v4_tests.rs:

  • hisa_selection_agrees_with_flat_fallback (line 1152): hierarchy equivalence against the flat scan on tie-free inputs.
  • indexer_forward_dispatches_and_respects_visibility (line 1204): path dispatch and causal visibility.
  • pool_visibility_counts_match_reference_make_mask (line 888): the V(t) = min(Np, floor((t + 1) / r)) visibility count.

The one deviation from this issue's original plan is deliberate: the plan proposed three attention structs mirroring the reference's class layout, and the port uses one struct with a kind discriminant, because the three share their entire projection set. The selection functions are factored exactly as planned.

What remains

1. The HiSA hierarchy has never run on the real checkpoint

This is the substantive gap. The engagement thresholds at r == 4 are:

pooled rows Np tokens (approx.) path taken
Np <= 512 (index_topk) <= ~2048 dense over pooled, selection unused
512 < Np < 1024 (index_block * index_keep) ~2048 to ~4096 flat scan top-512
Np >= 1024 >= ~4096 HiSA hierarchy

PR #1455's long-context real-model gate (deepseek_v4_real_model_long_context_hits_sparse_and_compressed_paths) runs at 2234 tokens, which gives Np = 558. That crosses index_topk and exercises the sparse split-softmax combine, but it lands in the flat-scan band and never reaches the hierarchy. Both hisa_select_decode and hisa_select_batched are therefore covered only by synthetic unit tests, never by real weights.

Needed: a real-checkpoint gate at >= ~4300 tokens (Np >= 1075) in tests/deepseek_v4_real_model.rs, asserting that prefill takes the batched hierarchical path, decode takes the fast path, generation stays coherent, and logits contain no NaN or inf. A retrieval probe (fact planted early in a filler prompt) is the useful assertion, since a hierarchy that selects the wrong blocks degrades recall while leaving output fluent.

2. No environment kill-switches

This issue specified two, following the MLXCEL_DSA_DENSE precedent at src/models/deepseek_v32_indexer.rs:41: one to disable the indexer entirely and fall back to dense pooled attention, and one to force the flat scan so the hierarchy can be A/B'd against it. Neither exists; src/models/deepseek_v4_indexer.rs reads no environment variable.

The second one is what makes item 1 diagnosable. Without it, a long-context regression cannot be bisected between "the hierarchy selects wrong blocks" and "the sparse combine is wrong", because there is no way to run the same prompt through the flat scan on the same weights.

3. Explicit tail-exclusion coverage

Rows in [nb*b, Np) are not candidates in the hierarchical paths, which is intended (they summarize the newest tokens the local window already covers at full resolution). hisa_selection_agrees_with_flat_fallback plants score mass inside the retained blocks, so it does not distinguish "the tail is excluded by design" from "the tail is unreachable by accident". A direct assertion that no selected index falls in the tail range would pin the intent.

Acceptance criteria

  • A #[ignore]-gated real-checkpoint test at >= ~4300 tokens that provably engages the hierarchy (not the flat scan) on both prefill and decode, with a retrieval assertion. Delivered as deepseek_v4_real_model_long_context_engages_hisa_hierarchy, running at 4410 tokens for ~1102 pooled rows against a 1024 threshold read from the real config.
  • An environment kill-switch that forces the flat scan, and one that disables sparse selection entirely, both following the MLXCEL_DSA_DENSE shape. Delivered as MLXCEL_V4_FLAT_INDEX and MLXCEL_V4_DENSE, each announcing itself once on stderr so an A/B cannot silently compare an arm against itself.
  • A unit test asserting hierarchical selections never return an index in [nb*index_block, Np). Delivered as hisa_selection_never_returns_a_tail_row, with a positive control that the flat scan does take the planted tail row.
  • Decode step time stays roughly flat as context grows past the hierarchy threshold. Met, on a reproduced measurement from mlxcel-bench-decode. Two earlier attempts got this wrong in both directions; all three are recorded below.

On the fourth criterion

Settled with src/bin/bench_decode.rs (mlxcel-bench-decode), which loads the model once, warms up, and reports instrumented prefill and decode separately, so neither figure can contaminate the other. Two independent passes, 100 measured decode tokens after a 20-token warmup, on a quiet machine:

prompt tokens pooled rows arm pass 1 ms/token pass 2 ms/token
2400 600 hierarchy 118.4 119.4
2400 600 flat 119.5 119.6
4400 1100 hierarchy 121.5 122.8
4400 1100 flat 121.9 121.4
8800 2200 hierarchy 124.3 123.9
8800 2200 flat 123.0 122.9

Every point agrees between passes within 1.1%.

Decode is flat in Np. Doubling the pooled prefix from 1100 to 2200 rows moves decode by x1.023 (pass 1) and x1.008 (pass 2). Prefill over the same step moves x2.03, which is the component the two earlier attempts were accidentally measuring.

Two earlier attempts, both unsound, recorded so nobody repeats them. The first timed one whole generate() and divided by tokens generated; that includes prefill, which at 8800 tokens is about 37 seconds against 12 seconds of decode, so it reported prompt-length scaling and concluded the criterion was not met. The second timed two decode lengths and subtracted, expecting prefill to cancel; it does not, because the two runs pay separate prefills, so their difference lands whole in the estimate. That one produced 98.3, then 369.5, then 186.4 ms/step at the same 4513-token point on consecutive runs, and briefly reported the criterion as met on the first of those samples.

Break-even: the hierarchy does not pay for itself at these lengths

Worth recording rather than filing as its own issue, since there is no action to take yet.

At 8800 tokens the hierarchy is 1.1% and 0.8% slower than the flat scan across the two passes. Same sign both times, so it is a real if tiny cost, not noise. Selection of either kind is negligible beside the roughly 120 ms/token of expert weight traffic, and the hierarchy adds its coarse stage on top of that.

This is not a defect. HiSA targets contexts far longer than these, and the port is faithful to the reference with selections bit-checked against the flat fallback. It simply has not reached its break-even point by 2200 pooled rows. Anyone benchmarking DeepSeek-V4 at much longer contexts now has a baseline to compare against, and MLXCEL_V4_FLAT_INDEX makes the A/B one environment variable.

deepseek_v4_real_model_hisa_decode_cost_scaling remains a reporting harness, not a gate: its subtraction method is the unsound one above, and the numbers that settle this question come from mlxcel-bench-decode instead.

Notes

  • The checkpoint is at models/deepseek-v4-flash-4bit relative to the repo root, reached in tests through common::repo_model_dir. The original body's /home/inureyes/models/... path is stale.
  • The checkpoint carries 44 compress_ratios entries for 43 layers and the first num_hidden_layers are used, so the final layer is ratio 4 (sparse), not the trailing 0. This is reference behaviour and is already handled; it matters here because it means the last layer is one of the sparse layers this issue covers.

Out of scope

Activity

  1. added
    type:enhancement
    status:blocked
    priority:low
    area:models
    on Jul 1, 2026
  2. added
    status:ready
    status:in-progress
    status:review
    and removed
    status:blocked
    status:ready
    status:in-progress
    on Aug 27, 2026
  3. added
    status:done
    and removed
    status:review
    on Aug 31, 2026
  4. self-assigned this
    on Aug 31, 2026
  5. added this to the 0.7 milestone on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:modelspriority:lowstatus:donetype:enhancement

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions