Skip to content

perf(deepseek_v41): read offloaded experts with positional preads - #3628

Merged
jundot merged 4 commits into
jundot:mainfrom
beatakouchnir:feat/v41-offload-128gb
Sep 13, 2026
Merged

jundot merged 4 commits into
jundot:mainfrom
beatakouchnir:feat/v41-offload-128gb

Conversation

@beatakouchnir

Copy link
Copy Markdown
Contributor

perf(deepseek_v41): read offloaded experts with positional preads

Follow-up to #3574 / #986 (V4.1 expert adapter) and #2595 (expert offload primitive). Companion to #3589, which does the same for the common adapter.

Problem

omlx/patches/deepseek_v41/moe_offload.py fetched non-resident experts through TensorFile.read(key, rows=expert), the Engram row-gather path: an mmap under MADV_RANDOM, read by NumPy advanced indexing. That is the right shape for Engram (many scattered rows, each smaller than a page). An expert is the opposite: 14.8 MiB of contiguous bytes per expert at the oQ3e geometry, faulted in one 16 KiB page at a time with readahead disabled.

Measured on an M5 Max internal SSD with a synthetic checkpoint at the oQ3e expert geometry (384 experts, 3-bit affine gs64, 4 layers, random weights written with F_NOCACHE so the first pass is cold), 12.5% residency:

before after
decode, one token, per MoE layer 362 ms 9.1 ms
expert fetch throughput (cold) 0.23 GB/s 9.3 GB/s
sorted prefill, 256 tokens 33 token-layers/s 568 token-layers/s

Summed over 40 layers, the before path spends about 14 s per decoded token on expert reads at 12.5% residency; the after path about 0.35 s. That gap is what decides whether V4.1 is usable on a 128 GB machine, which is the configuration the offload setting exists for.

Change

  • Expert slabs are read with os.preadv on per-shard descriptors, submitted to a small reader pool of their own (24 workers) rather than the Engram page pool, whose long sequential page touches would otherwise queue ahead of a layer's misses. No knobs. TensorFile stays the Engram path; the header parser and the dtype table are shared with residency.py and storage.py instead of duplicated, and the tensor byte-length check is kept.
  • _ExpertSlots.ensure_ids runs two passes: start the misses' reads ahead of the installs (at most INFLIGHT_BYTES of host payload in flight), then install serially in the order the misses were seen. Eviction victims, hit and miss counts, and resident bytes are identical to the serial path; the test pins the LRU order against a pure-Python reference at two in-flight windows. A failed read or decode leaves the cache exactly as it was (no slot leak, every started read drained before the error propagates), which the previous serial path did not guarantee either.
  • Sorted prefill routes are chunked on expert boundaries: every route of up to capacity distinct experts per chunk, instead of capacity rows per chunk. A prefill reads each expert once per layer and runs one kernel per chunk (with enough routes for the affine block kernels to engage), where the row-count chunking ran one kernel per 48 rows.
  • admission_bytes(path, fraction) and fit_resident_fraction(path, budget_bytes) give the engine pool's admission estimate for a fraction and the largest fraction whose estimate fits a byte budget. The test pins both to EnginePool._entry_runtime_resident_size for every capacity, with and without Engram tables (the pool has two branches there). docs/MoE_Expert_Offload.md gets the resident set per fraction for Jundot/DeepSeek-V4.1-Flash-oQ3e-mtp on a 128 GB Mac.
  • benchmarks/deepseek_v41_offload_bench.py loads a checkpoint through the loader with Engram on SSD and offload at each fraction, then runs chunked prefill and greedy decode, reporting memory, TTFT, decode speed, and per-phase hit rate and fetch throughput.

Validation

  • tests/test_deepseek_v41_moe_offload.py (46 with test_moe_offload_compat.py): existing cases unchanged except the load probe, which now asserts expert reads are single-expert slabs that never touch the Engram mapping; new cases for serial LRU order under concurrent reads, the failure path (cache intact, no slot leak, later reads work, idempotent close), expert-boundary chunking with arithmetic equality against the resident Expert, and admission/fit against the engine pool with and without Engram tables.

  • test_deepseek_v41.py, test_deepseek_v41_offload.py, test_deepseek_v41_moe.py, test_engine_pool.py, test_model_settings.py, test_moe_expert_offload.py, test_admin_model_settings_template.py: 392 pass.

  • Real checkpoint, Jundot/DeepSeek-V4.1-Flash-oQ3e-mtp on a 128 GB M5 Max (internal SSD, iogpu.wired_limit_mb unset), Engram on SSD, native kernels built, 433-token prose prompt in one prefill chunk plus 64 greedy tokens, single runs:

    residency experts/layer load Metal active peak footprint prefill decode decode hit rate
    12.5% 48 3.9 s 38.0 GiB 49.6 GiB 28 tok/s 5.6 tok/s 0.69
    25% 96 4.5 s 65.7 GiB 77.4 GiB 25 tok/s 4.2 tok/s 0.78

    Coherent continuations at both settings. Prefill reads each routed expert once per layer (about 226 of 384 per layer for this prompt) at 8 to 9 GB/s. Decode is miss-latency bound at one to two misses per layer per token; 12.5% decodes faster than 25% because the RAM the slots do not take becomes page cache, which serves repeated misses at 6.5 GB/s effective against 3.4 GB/s from the SSD. The first, repeated-sentence run at 12.5% gave 4.0 tok/s at a 0.81 hit rate. 33% was not measured: the session's memory guard stopped a run once the page cache had taken all free RAM (macOS itself was not under pressure).

  • omlx serve end to end on the same machine: the checkpoint is discovered from the HF cache (companion PR), admitted at 39.98 GB against 38.44 GB actual, Engram forced to SSD by admission, VLM engine load 4.4 s; two 64-token chat completions at 2.7 tok/s (cold expert slots) and 4.1 tok/s.

Not in this PR

DSpark MTP under offload stays excluded. On this path decode is bound by expert reads, and a 5-token verification block touches about 4.6x the experts of a single token at both 12.5% and 25% residency (measured on the synthetic checkpoint: 283 vs 1343 misses per 16 steps at 12.5%, 197 vs 906 at 25%), so DSpark's 1.6 to 2x tokens per step would net roughly 0.4x the throughput. It only pays once residency is high enough that reads stop being the bottleneck, which is not a 128 GB configuration.

The mlx-community/DeepSeek-V4.1-Flash-MLX-2bit checkpoint (222 GiB, per-expert affine layout, no omlx_deepseek_v41 spec) does not load through the V4.1 loader at all. That is a separate loader-side gap.

🤖 Generated with Claude Code

beatakouchnir and others added 4 commits September 12, 2026 16:05
The V4.1 expert adapter fetched non-resident experts through the Engram
row-gather mapping (`TensorFile.read(rows=expert)`, an mmap under
MADV_RANDOM). An expert slab is megabytes of contiguous bytes, so that
path faulted it in one page at a time: 0.23 GB/s on an M5 Max internal
SSD, 362 ms per MoE layer per decode step at 12.5% residency on a
synthetic checkpoint with the oQ3e expert geometry.

Read expert slabs with `os.preadv` on a small reader pool of their own
(the Engram page pool runs long sequential page touches that would queue
ahead of a layer's misses). A residency update starts the misses' reads
ahead of the installs, bounded by INFLIGHT_BYTES of host payload, then
installs them serially in the order the misses were seen, so LRU
victims, hit and miss counts, and resident bytes are identical to the
serial path. A failed read or decode leaves the cache as it was and
drains every read the call started before raising. Chunk sorted prefill
routes on expert boundaries (every route of up to `capacity` distinct
experts per chunk) so a prefill reads each expert once per layer and
runs one kernel per chunk. Same synthetic checkpoint, cold reads: 9.1 ms
per layer per decode step (9.3 GB/s), sorted prefill 568 vs 33
token-layers/s.

The shard header parser and its data offset, the checkpoint signature,
and the safetensors dtype table are shared with residency.py and
storage.py instead of duplicated; resident bytes use one rounding rule.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
`admission_bytes(path, fraction)` returns the engine pool's admission
estimate for expert offload at a resident fraction, and
`fit_resident_fraction(path, budget_bytes)` the largest fraction whose
estimate fits a byte budget, expressed as a whole number of experts per
layer so the value round-trips through the setting. Both follow
`EnginePool._entry_runtime_resident_size` exactly, including its two
branches: the header residency estimate less 1.05 times the savings when
Engram tables exist, and the discovery size less the savings when they
do not. The test pins them to the pool for every capacity in both modes.

Document the resident set per fraction for the oQ3e-mtp checkpoint on a
128 GB Mac against the Metal working-set limit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Load a V4.1 checkpoint through the oMLX loader with Engram on SSD and
expert offload at each requested resident fraction, then run a chunked
prefill and a greedy decode directly on the model. Reports load time,
Metal memory and phys footprint, time to first token, decode speed, and
the expert cache's hit rate and fetch throughput per phase, after
printing the admission estimate per fraction and the largest fraction
that fits the Metal working-set limit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Jundot/DeepSeek-V4.1-Flash-oQ3e-mtp on an M5 Max with 128 GB, Engram on
SSD, run with the offload harness on a 433-token prose prompt and 64
greedy tokens: 12.5% residency loads in 3.9 s at 38.0 GiB active and
decodes at 5.6 tok/s; 25% loads at 65.7 GiB and decodes at 4.2 tok/s.
The lower residency is faster because the RAM its slots leave free
becomes page cache, which serves repeated misses far faster than the
SSD. The same settings through `omlx serve` answer chat completions at
2.7 tok/s on cold slots and 4.1 tok/s after.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@jundot

jundot commented Sep 13, 2026

Copy link
Copy Markdown
Owner

Thanks for implementing this. Positional reads and expert-boundary chunking are a useful improvement for V4.1 offload. I found that completed futures retain their read buffers until ensure_ids() returns, exceeding the intended memory window. I'll merge this and address buffer release in a small follow-up with a regression test.

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