Skip to content

perf(deepseek_v41): run resident experts first in sorted prefill routes - #4959

Merged
jundot merged 1 commit into
jundot:mainfrom
cropduster:perf/dsv41-prefill-resident-first
Nov 12, 2026
Merged

jundot merged 1 commit into
jundot:mainfrom
cropduster:perf/dsv41-prefill-resident-first

Conversation

@cropduster

@cropduster cropduster commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

#4951 has landed as 9aa3f28, so this is now a single commit on main: perf(deepseek_v41): run resident experts first in sorted prefill routes is the whole diff.

Content unchanged, only the base moved — the resident-first change can be reviewed on its own.

Problem

OffloadedExpert._sorted cut the expert-sorted prefill routes into chunks of up to capacity distinct experts and called ensure_ids per chunk. ensure_ids protects only the experts of the current call, so on a sweep over more experts than slots, chunk 1 (lowest ids) evicted every resident expert, chunk 2 evicted chunk 1, and so on. By the time a chunk reached an expert that had been resident when the call started, it had already been evicted. Every prefill forward therefore read every expert it touched, regardless of what was resident (the existing test even asserted this: "sorted routes over more experts than slots thrash by construction").

With V4.1-Flash and 131/384 experts resident, an 8K-token chunk touches ~364 experts per layer in the lower 20 layers, so each forward read ~108 GB from SSD.

Change

_sorted now builds expert groups with _groups:

  1. one group with every touched expert that is already resident (no reads), run first while the first miss group is read ahead;
  2. the misses, in ascending id order, at most capacity distinct experts per group (as before).

Each group gathers the routes of its experts (positions stay ascending, so the group's ids stay sorted), runs as one sorted_indices=True call, and the outputs are put back in the routes' sorted order, which combine_sorted_experts expects. Routing, arithmetic, read-ahead window and eviction policy are unchanged. On CPU the outputs are bitwise identical to the previous chunking; with no resident experts (first sweep) the groups are exactly the previous chunks.

Measurements

M4 Max 128 GB, DeepSeek-V4.1-Flash-1017-oQ2.5e-mtp, MoE offload 131/384 resident (fraction 0.34), prefill step 8192, CED prefill on, temperature 0. Agent-like pattern per block: fresh load → 3.4K warm-up → S1 9.2K fresh prompt → S2 +14.4K suffix (prefix-cache hit) → S4 19-token follow-up → S3 +10.2K suffix, 300 tokens each, real texts with a nonce. Arms interleaved (A R R A, A R RP RP R A), 3–4 blocks per arm; per-forward counters from instrumented _ExpertSlots.

before this PR
hits per full 8K forward (40 layers) 1,836 4,038
expert reads per full forward 108 GB 79 GB
full 8K forward wall time 36.9 s 32.0 s
short (~1K) forward wall time 18.3 s 13.8 s
TTFT S1 / S2 / S3 56.7 / 72.5 / 78.5 s 46.8 / 62.9 / 62.7 s
TTFT S1+S2+S3 per block 207.8 s (SD 3.6, n=4) 172.4 s (SD 0.8, n=3), −17 %
decode ms/cycle (cycles 1–16 / 17–64 / 65+) 293 / 190 / 167 280 / 189 / 165

Things I tried alongside, for reference (not in this PR):

  • Merging short prefill forwards (a <2K remainder or a misaligned prefix-cache resume) into the next block: saves ~17 s on the first prefill but breaks prefix-cache reuse, because the skipped boundary snapshot is part of the chain the stateful caches need. Rejected.
  • Speculatively reading the next layer's lowest non-resident experts during prefill: SSD wait −3 s per forward but wall time only −0.7 s, plus ~3 GB of unused reads per forward. Not worth it.

Tests

  • test_sorted_routes_chunk_on_expert_boundaries: the second sweep now runs the resident pair first — 6 reads instead of 8, same outputs.
  • New test_resident_first_groups_restore_the_sorted_route_order (3 seeds × 4 sweeps): random routes and weights, outputs allclose to the resident reference, experts resident before a call are never read by it, read-ahead drained.
  • macOS/Metal, at this commit: tests/test_deepseek_v41_moe_offload.py tests/test_deepseek_v41_offload.py tests/test_moe_expert_offload.py → 136 passed, 3 skipped, 4 deselected. The 13 failures of the same run are all ModuleNotFoundError: No module named 'mlx_vlm.models.d1_lfm3_vl': my local 0.7.3rc1 bundle vendors an mlx-vlm 0.7.10 wheel without that submodule, which exists from v0.7.11 (138d761) — the version main pins. Unrelated to this diff.

🤖 Generated with Claude Code

@cropduster
cropduster force-pushed the perf/dsv41-prefill-resident-first branch from 478befa to a98a9e1 Compare October 30, 2026 04:39
A sorted call over more experts than slots used to evict every resident
expert before reaching it: each chunk protected only its own experts, so
chunk 1 (lowest ids) replaced all slots and the experts a chunk later
needed had to be read again. A prefill forward therefore read every
expert it touched, about 384 per layer at 8K tokens, no matter what was
resident.

_sorted now runs one group with the resident experts first (no reads,
while the first miss group is read ahead), then the misses in groups of
at most `capacity` experts in ascending id order. Outputs are put back in
the routes' sorted order. Routing and arithmetic are unchanged; on CPU the
outputs are bitwise identical to the previous chunking.

Measured on M4 Max 128 GB, DeepSeek-V4.1-Flash-1017-oQ2.5e, 131/384
experts resident, agent pattern (9K fresh + 14K and 10K prefix-cache
suffixes), 3-4 interleaved blocks per arm:
  hits per full forward  1836 -> 4038, expert reads 108 -> 79 GB
  full 8K forward        36.9 -> 32.0 s, short ~1K forward 18.3 -> 13.8 s
  TTFT per round         S1 56.7 -> 46.8 s, S2 72.5 -> 62.9 s,
                         S3 78.5 -> 62.7 s (sum 207.8 -> 172.4 s, -17%)
  decode ms/cycle        unchanged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cropduster
cropduster force-pushed the perf/dsv41-prefill-resident-first branch from a98a9e1 to 5419431 Compare October 31, 2026 09:28
@cropduster cropduster changed the title perf(deepseek_v41): run resident experts first in sorted prefill routes (stacked on #4951) perf(deepseek_v41): run resident experts first in sorted prefill routes Oct 31, 2026
@cropduster

Copy link
Copy Markdown
Contributor Author

Rebased onto main after #4951 landed as 9aa3f28 — this is now a single commit on top of it, and the content is unchanged: the commit's line delta is identical before and after the rebase, only the base moved. Title and body now say so, so there is no stacked review any more — the whole diff is the resident-first change.

CI: test (3.11) passes in 17m18s.

One note for local runs with the 0.7.3rc1 app bundle, in case it shows up elsewhere: that bundle vendors an mlx-vlm 0.7.10 wheel, which has no mlx_vlm.models.d1_lfm3_vl, so 13 tests in the offload files fail at import with ModuleNotFoundError: No module named 'mlx_vlm.models.d1_lfm3_vl' (136 passed, 3 skipped, 13 failed — all 13 are that import). It is environmental: CI installs the pinned mlx-vlm 138d761 (v0.7.11), where the submodule exists, and does not hit it.

@cropduster

Copy link
Copy Markdown
Contributor Author

Measured: what the resident-first ordering does under real expert offload

I benchmarked this on an offloaded DeepSeek-V4.1 Flash checkpoint, where every miss is an actual disk read — that is the case this change targets, and it shows up directly in the server's offload counters.

Setup

  • Mac Studio M4 Max, 128 GB unified memory
  • DeepSeek-V4.1 Flash 1017, oQ2.5x weights, 40 MoE layers, top-6 routing, 142/384 expert slots; Engram tables forced to SSD because the resident set does not fit under the memory ceiling
  • both arms run the same checkout and the same mlx build; only the ordering switch differs, so nothing but the group order changes

Method

  • model unloaded and reloaded before every run, so the plan and its residency map are rebuilt from the switch
  • one freshly generated prompt per run: a repeated prompt is served from the paged SSD cache (0.4 s instead of ~60 s — I hit that first, hence fresh text for every run, no shared prefix)
  • numbers below are the server's own per-forward offload counters: misses = experts read from disk, distinct = experts that forward routed to, read = bytes read

100k prompt (13 forwards), one run per arm

resident-first ordering off delta
reads 337.7 GB 518.4 GB −34.8 %
request wall (prefill + 4 tokens) 221.6 s 255.0 s −13.1 %
prefill rate 455 tok/s 395 tok/s +15 %

25k prompt, two runs per arm (fresh prompt each, values are means)

forward misses/distinct ON misses/distinct OFF read ON/OFF read-wait ON/OFF wall ON/OFF
1 — cold 100 % 100 % 61.5 / 61.1 GB 9.7 / 9.2 s 23.3 / 22.4 s
2 — full 43.6 % 69.5 % 23.0 / 36.3 GB 2.3 / 5.4 s 16.0 / 18.7 s
3 — full 35.0 % 60.0 % 18.6 / 31.5 GB 1.7 / 4.4 s 15.5 / 17.8 s
4 — tail 60.5 % 58.1 % 36.6 / 34.5 GB 5.6 / 5.9 s 9.4 / 8.1 s
total 139.6 / 161.9 GB 69.5 / 69.9 s

How I read it

  • The gain lands where the change operates: in the full forwards, misses drop from ~60–70 % of the distinct experts to ~35–44 %, and the read wait falls by more than half.
  • The first forward is cold in both arms (nothing is resident yet) and the trailing partial forward has few groups. At 25k those two fixed costs dominate, so the total there is flat — that is expected, not a null result.
  • It therefore scales with the number of full forwards: −14 % reads and flat total at 25k, −35 % reads and −13 % wall at 100k.
  • The tail forward is the one place I see movement in both directions; it is a partial forward, so I would not read a regression into it from two runs.

Caveats

  • Single machine, single checkpoint, single mlx build; two runs per arm at 25k, one at 100k.
  • Prompts differ between runs by design (generated text), which moves distinct by ~1–2 %.
  • The unit tests cover this path with synthetic experts only, so this is real-model evidence, not a CI benchmark.

Happy to re-run at another depth or residency fraction if a specific number would help the review — the harness is a single script.

@jundot jundot left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With id-order chunks the first chunk evicted every resident expert before the loop reached it, so each full prefill forward re-read everything it touched. Running the resident group first keeps those slots, and the new test shows it directly (on the old chunking it fails with the resident experts read again, here it passes). The read drop in your 100k run lines up with the share of slots that stay resident.

Thanks for the per-forward counter breakdown too. LGTM, merging.

@jundot
jundot merged commit 7ce022c into jundot:main Nov 12, 2026
1 check passed
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.

2 participants