Repository navigation
Conversation
…tchLinear Adds enable_offload(resident_slots, fetch_fn) to the shared MoE switch-linear primitives. When enabled, only resident_slots experts stay resident in a dict-keyed LRU cache (expert_id -> weight); the rest are fetched on a router miss via the caller-supplied fetch_fn (e.g. an explicit byte-range read from the model's own safetensors shards) and evicted to capacity. The forward path reads only the cache, never the full stacked weight, so a model whose expert table exceeds unified memory can run with just the resident set + activations live. Design notes: - Dict-keyed cache (not a fixed slot array): an eviction later in the same forward call could otherwise overwrite a slot an earlier expert already resolved to, since the gather runs only after every index resolves. - Chunked resolve with a fixed max-stack cap bounds the transient stack a single call materializes, independent of resident_slots, so a diverse prefill that touches nearly every expert can't OOM. - Seeding the resident set from fetch_fn (not by slicing the loaded weight) and replacing the weight with a 1-row stand-in genuinely frees the full table: a prefix slice of an mx.array is a view that pins the whole parent buffer. - fetch_fn should return raw host data; the mx.array must be built on the thread that runs the model (MLX arrays are thread-affine), so callers should split disk I/O from array construction. Opt-in and off by default: models that fit should stay fully resident, since offload trades throughput for memory (a diverse prefill re-fetches most of the table because the resident fraction can't hold its working set). See ml-explore#1438.
_offload_chunked_gather partitions a call's unique experts into groups of at most max_stack_size and, per group, runs gather_fn over ALL token positions (out-of-group positions get a dummy index and are discarded via mx.where), then combines the G groups with mx.where. That bounds transient memory for any call shape but costs G times the matmul: each of the G groups touches every position. On a diverse prefill (~all 256 experts, max_stack 64 => G=4) that is a ~4x compute tax on top of the disk misses. When the caller guarantees sorted routing (SwitchGLU/SwitchMLP _gather_sort fires at indices.size >= 64, i.e. the multi-group prefill case) AND flat is verified monotonic, each group's positions form one contiguous slice of flat. Take a compact path: slice x to that segment, gather once over just those positions, and concatenate the segments -- each position computed exactly once, no mx.where. Guarded by an actual monotonicity check (not just the flag), so a mislabelled sorted_indices falls back to the always-correct mask path. Fetch and eviction are unchanged (shared _resolve_group helper), so disk behavior and output are identical; only the matmul/combine changes. Measured on Qwen3.6-35B-A3B-4bit, offload on 0.3, 3022-tok prefill, fresh backend: prefill 75.7 -> 136.2 t/s cold (1.80x), 75.7 -> 129.9 t/s warm; decode unchanged (compact path dormant on single-token calls); peak 7.31 -> 7.34GB, hit_rate 0.514 -> 0.514 (identical). Isolated gather micro-bench 3.24x at a 1458-tok prefill. Bit-identical to the mask path (regression-gated in mira-core tests/test_expert_offload.py). Complements ml-explore#1588.
|
Follow-up with a prefill optimization to the chunked gather in this PR. It is measured and bit-identical, so I wanted to put it here in case it is worth folding in. Context on the cost. The fix. SwitchGLU and SwitchMLP already sort the routing before dispatch whenever Measured on Qwen3.6-35B-A3B-4bit, offload on at fraction 0.3, 3022-token prefill, fresh backend:
That is 1.8x cold prefill, output bit-identical to the mask path (I regression-gate compact == mask directly), with hit_rate and peak unchanged. The isolated gather micro-bench is 3.24x at a 1458-token prefill; end-to-end is 1.8x because the gather is about half of offload-on prefill wall time and the rest is attention plus the disk misses. This is a different axis from the layout and heat-pinning discussion in #1438. @doramirdor is right that reordering does not fix prefill, since prefill routes to nearly all experts and a 30% cache cannot hold that working set. But part of the prefill tax was never the working set, it was the chunking doing G passes of the same matmul. Removing that redundancy is the one lever that moves the prefill number without touching hit_rate, and it composes with heat-pinning (which targets the decode miss tax) rather than competing with it. Happy to add this to the PR if you want it in the same change. It lives entirely inside |
|
A second follow-up on the same chunked gather, this time for decode rather than prefill. Also measured and bit-identical. Context. The fix. Skip the eval when Measured on Qwen3.6-35B-A3B-8bit, offload forced on at fraction 0.3, lazy load, greedy so the two runs select identical experts (hits and misses identical to the token). This is the real case for offload, since the 8bit stacked expert table is larger than this 32GB machine's memory and cannot be loaded eagerly at all:
That is +13% decode at identical peak, output bit-identical. The peak not moving is the point: on the real offload path only the resident fraction is held, so deferring one token's graph adds a negligible transient rather than materializing the whole table. A synthetic that keeps every expert warm can show the opposite, but that state is precisely what offload exists to avoid, so it does not occur on the real path. Relation to #1438. This is the decode side. It does not raise hit_rate, it makes each decode step cheaper independent of misses, so it composes with heat-pinning rather than competing. Together with the prefill compaction above, the two cover the two halves of the offload-on tax: the prefill compute redundancy and the decode sync overhead. Small change, entirely inside |
|
Nice work on this. I'd independently built the same capability as a layer on top of mlx-lm (adapters that stream experts from safetensors into a per-layer cache), so I wired your
So the primitive scales well past the 35B demo, and it's genuinely architecture- and quant-agnostic. The dict-keyed cache and the One data point in case it's useful: I A/B'd predictive prefetch (warming the next layer's likely experts) against reactive fetch-on-miss, and it didn't improve batch-1 decode throughput at any coverage I tested — the overlap just doesn't pay at batch 1. So reactive-only looks like the right call, not a limitation to fix later. Happy to run more configs if it helps the review. My on-top version and the benchmarks are at github.com/lBroth/blackmlx for reference, but your in-core approach is the cleaner place for this to live. |
_offload_chunked_gather partitions a call's unique experts into groups of at most max_stack_size and, per group, runs gather_fn over ALL token positions (out-of-group positions get a dummy index and are discarded via mx.where), then combines the G groups with mx.where. That bounds transient memory for any call shape but costs G times the matmul: each of the G groups touches every position. On a diverse prefill (~all 256 experts, max_stack 64 => G=4) that is a ~4x compute tax on top of the disk misses. When the caller guarantees sorted routing (SwitchGLU/SwitchMLP _gather_sort fires at indices.size >= 64, i.e. the multi-group prefill case) AND flat is verified monotonic, each group's positions form one contiguous slice of flat. Take a compact path: slice x to that segment, gather once over just those positions, and concatenate the segments -- each position computed exactly once, no mx.where. Guarded by an actual monotonicity check (not just the flag), so a mislabelled sorted_indices falls back to the always-correct mask path. Fetch and eviction are unchanged (shared _resolve_group helper), so disk behavior and output are identical; only the matmul/combine changes. Measured on Qwen3.6-35B-A3B-4bit, offload on 0.3, 3022-tok prefill, fresh backend: prefill 75.7 -> 136.2 t/s cold (1.80x), 75.7 -> 129.9 t/s warm; decode unchanged (compact path dormant on single-token calls); peak 7.31 -> 7.34GB, hit_rate 0.514 -> 0.514 (identical). Isolated gather micro-bench 3.24x at a 1458-tok prefill. Bit-identical to the mask path (regression-gated in mira-core tests/test_expert_offload.py). Complements ml-explore#1588.
_offload_chunked_gather evals after each group's combine to force MLX to release the previous group's temporary stack before the next group's gather allocates -- a bound that only matters ACROSS groups. Decode always routes to a single group (its top_k experts fit one stack), where there is no next group to bound against, so the eval only forces a per-layer GPU sync with no memory benefit. Skipping it when len(groups) == 1 lets MLX defer the token's gather graph to the caller's next eval boundary (the sampler evals each token anyway). Bit-identical output either way (guarded fallback; prefill's multi-group and compact paths keep their evals). Measured +13% decode (7.15 -> 8.09 tok/s) at identical 12.73GB peak memory on mlx-community/Qwen3.6-35B-A3B-8bit over-DRAM expert offload (fraction 0.3), the real case where offload is forced on.
|
Both follow-ups above are now folded in, as two commits on top of the original change. They are the same file and the same function as the base change, so I did not split them into a separate PR. Splitting would have stacked them on an unmerged branch, which seemed worse for review than one file with three commits. Happy to pull either back out if you would rather review the primitive alone first. One thing I deliberately left out. I have a small additive change locally that splits the hit/miss counters by phase, because the blended hit-rate is dragged down by the cold prefill and understates the decode steady-state that a residency change actually moves. It is useful for the follow-up work but it is observability, not the offload primitive, so it is not in this PR. I can open it separately once this lands, or add it here if you would prefer it in one go. I have also updated the tradeoff section in the description, since the numbers there predated both commits and understated the current state. |
|
@lBroth Thank you for running this, and on two architectures and two quant formats is more than I could test. The Qwen3-235B result is the one I find most useful: a 118GB table at 2.6x your RAM, running at all, is well past what I could demonstrate on 32GB. Your fraction 0.3 OOM at that size is worth writing down somewhere, because it is not obvious from the outside. The resident fraction is not a free knob, it has to shrink as the table grows relative to RAM, so the useful fraction is a function of that ratio rather than a constant. I have only ever tuned it at ratios near 1. Your prefetch A/B is the part I want to flag, because it is the third independent null. I measured per-token adjacent-layer Jaccard of selected experts at 0.017 against a 0.016 uniform baseline on Qwen3.6, so there is no cross-layer signal to prefetch on, and @doramirdor retracted the prefetch framing in #1438 on the same grounds. Yours is the strongest of the three because it is a direct end-to-end A/B rather than an offline statistic. If you still have the harness, I would be interested in whether the null holds on GPT-OSS as well as Qwen, since two architectures agreeing would make it much harder to dismiss as model-specific. That is not something I can test at my memory ceiling. Two things landed since you tested, both bit-identical and both inside |
|
I ran both things you asked: the null on GPT-OSS, and your two commits at our scale. Correction I owe you is at the end. (Your units and peak questions from #1438 I answered over there, since that is where the summary lives.) The two new commits hold at our scale. Your
TTFT improves 7 to 8% on both, peak unchanged, generated text identical. I trust the delta over the absolutes: an earlier 120B pass read +14.2%, and an unrelated iOS workload sharing the GPU dragged a re-run 8% lower and much noisier. Three pairs at different contention gave +14.2/+16.9/+15.1%. The prefetch null holds on GPT-OSS. Reproducing yours first: Qwen3.6-35B-A3B gives adjacent-layer Jaccard 0.0178 pooled over 5 traces against 0.0159 analytic, roughly your 0.017 vs 0.016, essentially the uniform baseline. Then same prompts, same greedy, both models:
Both on the baseline, prefill too. One caveat on the control: the analytic uniform baseline understates chance overlap when usage is skewed. A shuffle control (permute the token axis per layer, killing cross-layer structure but keeping each layer's usage) is cleaner. Against analytic, GPT-OSS reads 1.17x and looks like signal; against shuffle it is 0.98x. With the uniform baseline alone you might have called GPT-OSS the other way. The prefetch A/B, on my engine (your PR has no prefetch arm to test). Depth-2 predictor, cache 18GB, 200 tokens, five repeats each in its own process:
Decode is 2.9% slower, too small to lean on given the drift, but the accounting is the point: prefetch removes 18.3% of synchronous reads yet spends 103.86GiB of background reads to do it. At 14.4% precision with uniform-size expert blocks that is ~6.9 bytes read per byte saved (the ratio is just 1/precision here), and the extra bandwidth is not repaid in this run. Distinct from your Jaccard: the d2 predictor bets the residual moves little over two layers, not that adjacent layers agree, so it can carry signal (14.4% vs 3.1% random) and still not pay. The correction I owe you. You called my earlier prefetch result the strongest of the three; it does not deserve that. It ran on my engine, not on Two small ones. Your branch does not touch SSM code; the one failure in |
The blended offload hit-rate is dragged down by the diverse cold prefill (routes to ~all experts, no resident fraction fits it), so it understates the steady-state decode hit-rate that a residency/policy change actually moves. _offload_chunked_gather now infers phase per call from indices.size (< 64 = decode, the same threshold SwitchGLU/SwitchMLP use to decide sorting) and _resolve_group increments _offload_hits_decode/_offload_misses_decode alongside the blended counters. Additive; blended counting and output are unchanged.
|
Thanks for running both of these, and for the correction. I'd much rather have that than the stronger claim. On that point, I should own my half of it. I called your prefetch result the strongest of the three because I read it as running on The shuffle control is the part I'm taking away from this. My 0.017 vs 0.016 was against an analytic uniform baseline, and your GPT-OSS numbers show why that isn't good enough: 1.17x against analytic, 0.98x against shuffle. Same data, opposite reading. Two architectures sitting on the baseline under the better control is a stronger null than anything I had, and it's the control I should have been using. The prefetch accounting is the part I find most interesting. 14.4% precision against 3.1% random says the depth-2 predictor does carry signal. It just spends about 6.9 bytes to save one, and at batch 1 that isn't repaid. That's a more useful result than a flat null, because it says the lever is mispriced rather than missing. Batching or a faster device might move the ratio, but nothing here suggests it's worth chasing yet. Good to see the two commits hold at 120B and 235B. +15.1% and +9.6% at unchanged peak, on tables well past RAM, is the case I couldn't make on 32GB. My numbers only ever demonstrated it near ratio 1. Thanks also for confirming One thing I've changed my mind on. I said earlier that the phase-split hit/miss counters were observability rather than part of the primitive, and left them out. I've added them after all, and this thread is why. Every comparison in it, yours and mine, turns on a hit rate, and the blended figure mixes cold prefill into what is meant to be a steady-state decode number. I misread my own results that way once, and attributed a residency effect to a decode change. The split is what caught it. It's additive and output-identical, in the same function as the rest. Happy to pull it back out if you'd rather review the primitive on its own. On the resident fraction tracking table/RAM rather than being a constant: agreed, and I think that belongs in the docs rather than being something people discover via OOM. I'll add a note unless a maintainer would prefer it stayed out of this PR. |
|
One last update and then I will stop adding to this. The phase-split hit/miss counters are now in, so the branch matches what I run in production. That is everything I intended for this PR. Happy to split, squash or revert any of it on review, and content to let it sit until someone has time. @lBroth thank you for the independent validation. Running an unmerged PR on two architectures and two quant formats, at scales past my memory ceiling, is a lot more work than reviewing it would have been, and the +15.1% and +9.6% at unchanged peak are numbers I could not have produced myself. Also for confirming the |
|
Downstream use-case datapoint, since both open hooks affect us directly: we maintain an expert pager for GLM-5.2 on the MLX affine-4-bit checkpoint (~20.25 MiB per expert: gate/up/down × {weight, scales, biases} as nine sub-slices of the stacked tensors), currently installed via a duck-typed
GLM-5.2-affine end-to-end numbers were the one cell the campaign matrix didn't cover; once our side-file A/B runs on real weights we'll post the s/g-decomposed result here either way. |
|
@pierre427 Welcome — GLM-5.2-affine on MLX is exactly the cell the matrix never covered, and an s/g-decomposed A/B from a production pager is the best possible way to fill it. The API shape of both asks is @mabaeyens' call; three things on the parts that touch the side-file and the law: 1. The manifest already carries what your memoized per-expert fetch needs. Per layer it encodes 2. On-record prediction for your cell, so the A/B has a number to falsify. Transparent arithmetic: 9 preads → 1 saves 8 per-op overheads (t_op ≈ 100–120 µs, measured consistently across the four engines so far) against ~3.5 ms of transfer for a 20.25 MiB block at ~6 GB/s → g ≈ 1.2–1.3; scaling gpt-oss's measured A2 g = 1.29 at its ~12.6 MiB experts by block size gives ~1.18. Pre-registering A2-vs-9-scattered g ≈ 1.2, band 1.15–1.3 — your blocks sit between gpt-oss and the illiria endpoint (19 MiB already-contiguous, residual 1.05), so this is interpolation, not extrapolation. A1-vs-9-scattered ≈ 1.15, so the marginal I/O value of whole-expert granularity over what the current per-projection API already permits is real but modest at your block size — the stronger argument for your ask 1 is coherence (three independent LRUs can strand an expert partially resident; one memoized block can't). End-to-end I will not predict: I'm 0-for-2 on share in this thread, and the hardened rule is that s is engine-architecture-dependent and doesn't transfer — measured brackets from the campaign: misses serialized at deep offload → s ≈ 0.9+ → ~+20%; 8-way overlapped fetch → s ≈ 0.27 → ~+5%. Your decomposition will say which pager regime you're in, which is precisely why it's the right measurement. 3. One sourcing check before the docs note ships. I can't find the ~800→180 MB/s buffered-pread collapse in #1438 — closest measured there: per-miss 1.1 MiB cold reads rising 240→280 µs as resident fraction grows and the page cache shrinks (direction agrees, magnitude ~15%); our 32 KiB sub-slice reads at ~325 MB/s (small-read latency floor, not cache pressure); illiria's 13.4–13.6 GB/s at 19 MiB blocks. If 800→180 is your own rig's measurement, it's a new and interesting datapoint — worth posting with block size and method, and attributing to yourselves. If it traces to the "0.18×" figure in the summary's traps section, that one is the F_NOCACHE broken-eviction canary (a wrong-arm detector), not a throughput measurement. The page-cache-headroom advice itself is sound either way; only the cited magnitude needs a source. |
|
@doramirdor Good catch on 3, and the correction runs toward me: the 800→180 MB/s figure is not from #1438. It's iliria's own in-source measurement — the page-cache-reserve comment in On 1: we'll run |
|
@pierre427 Clean resolution, and better than a citation fix: an in-source, dated measurement with a hard-coded consequence — "2.5 GB reserve because we measured the collapse" — is exactly the kind of engineering record this campaign kept having to reconstruct after the fact. Single-rig with unstated block size is the right scoping; worth noting the direction is now triple-confirmed (your If iliria does share colibri lineage, that measurement belongs in JustVugg/colibri#119 too: the pin-budget discussion there (30 GB pin sizing on GLM-5.2) implicitly trades pinned bytes against exactly this page-cache headroom, and a collapse threshold with a block size attached would turn "reserve some headroom" into a sizing rule. I'm active in that thread and happy to carry it over once a block size exists — or @PhilipJohnBasile may already have it, since the comment lives in his tree. Two pointers so the A/B lands clean on the first run: the traps section of the consolidated summary here (comment 5024844476) — especially F_NOCACHE-doesn't-evict-resident-pages (it bit two of us independently; the 0.18× "speedup" is the canary) and arm-swapping as the page-cache control; and iliria's follow-up that fd reuse does not eliminate per-read latency (t_op ≈ 122 µs on cached-fd 13.7 KiB preads) — that per-op overhead is the term your 8 saved ops cash in, so it's worth benching t_op on your rig once and plugging it into the band. Looking forward to the decomposed numbers — g gets falsified cleanly either way, which is the good outcome. |
|
@doramirdor The GLM-5.2-affine cell is filled, and your pre-registration survives contact: measured A2-vs-9-scattered g = 1.195 (same-device micro, disjoint-cells protocol, M5 Max internal NVMe) against your registered 1.2, band 1.15–1.3. One mechanism note from the decomposition: our 9-sub baseline relocated adjacent inside the side-file actually beats the single block pread by ~7% (t_op(adjacent) ≈ −25 µs), while true scattered reads cost t_op ≈ 64 µs at 8.2 GB/s — so t_op behaves as a locality cost, not per-op overhead, and your band held because the assumption errors (110 µs @ 6 GB/s) cancel almost exactly. Corollary: the A1 per-projection rung measured worse than 9-adjacent (1.12 vs 0.92 relative to A2) on this rig — it is not an intermediate rung once subs are adjacent. End-to-end (ABBA, greedy, byte-identical outputs across all five runs; 60 GB materialized cache, 54.5% decode hit, 273 misses/token): A2 vs 9-adjacent is a wash (0.345 vs 0.343 t/s) at s ≈ 0.33. The adoption delta — coalesced side-file on internal NVMe vs stock scattered shards on the external USB3 SSD, which is the deployment question if not the pure layout question — is 3.6× decode (0.097 → 0.345 t/s) and 5.3× prefill, with s moving 0.91 → 0.33, matching your serialized-miss bracket. One more point for the hardened rule: a fixed-non-disk s/g extrapolation over-predicts (5.5× vs measured 3.6×) — sustained ~2 GB/s buffered streaming visibly contends with compute on unified memory, so even a measured g and s don't compose cleanly across devices. Format interop: |
|
Thanks, this is the cell I couldn't reach on 32GB, and a decomposed A/B from a production GLM-5.2 pager is the right way to fill it. g = 1.195 against the registered band is clean. Ask 2 ( Ask 1 (shared per-expert fetch): your own end-to-end number settles it for me. A2 vs 9-adjacent is a wash (0.345 vs 0.343 t/s), so whole-expert granularity doesn't earn its way into this PR on I/O grounds. The argument that does hold is coherence (three independent LRUs can strand an expert partially resident), and that's a separate design axis from the offload primitive. I'd rather keep this PR to the primitive and do the shared per-SwitchGLU cache as a small follow-up, with your pager as the consumer that validates it. Happy to prototype against whatever fetch shape you land on. Noted on the two smaller points: the GLM dense-first-3-layers assert (sparse layer set, not One unrelated thing: |
|
@pierre427 The band survived, and I want the record to say how: right number, partially wrong mechanism. I assumed t_op ≈ 110 µs of per-op overhead at 6 GB/s; you measured a locality cost — ~64 µs for true scatter at 8.2 GB/s, ≈ −25 µs once subs are adjacent — and the two assumption errors nearly cancel. A pre-registration that lands by cancelation gets called that in public, or the registry teaches the wrong lesson. The refinement is now the stated form in the summary: t_op is a scatter penalty, and A1 is not an intermediate rung once subs are adjacent — your 9-adjacent beating the mono-block pread by ~7% puts the ladder's endpoint at adjacency, not merge-count, which also retroactively explains why iliria's one-big-pread container and your 9-adjacent land in the same place. The e2e wash at s ≈ 0.33 plus the 3.6×/5.3× adoption delta (with s moving 0.91→0.33, squarely in the serialized bracket on the USB3 side) says it cleanly at 20 MiB blocks: where the side-file lives dwarfs how it's ordered. And the 5.5×-predicted vs 3.6×-measured gap is a genuinely new rule for the thread — measured g and s don't compose across storage devices because the "non-disk" term is itself load-dependent under unified-memory contention. All of it is folded into the consolidated summary (comment 5024844476, now v1.4), with your runs credited in the scope line. Tooling: the dense-prefix trip is fixed and pushed to the gist. @mabaeyens both calls look right from here. |
enable_offload gains an optional resident_bytes budget as an alternative to the resident_slots count. A slot count is the wrong unit when experts are not all the same size -- heterogeneous or mixed-precision expert tables -- where bytes, not slots, are the real memory budget. When resident_bytes is given, the slot count is derived by probing a single expert through the same fetch path a cold miss uses (so the per-expert figure is the true resident footprint of a cache entry: quantized weight + scales + biases, not an on-disk estimate) and floor-dividing. Passing both budgets keeps the tighter of the two, so a byte budget can only ever lower a slot count, never raise it. New _offload_data_nbytes() sums the resident bytes of one cache entry (a quantized tuple with possibly-None biases, or a dense array). Both public enable_offload methods take and forward resident_bytes; resident_slots becomes optional. The positional enable_offload(resident_slots, fetch_fn) call still works, so existing callers are unaffected.
The offload feature shipped with no tests in-tree. Adds tests/test_switch_offload.py (unittest.TestCase, matching the existing suite and CI's unittest discover): 11 tests covering dense and quantized offload vs an eager baseline, resident_bytes slot derivation for both tiers, the both-budgets-takes-tighter rule, the fetch_fn and no-budget guards, the no-op when residency covers all experts, and SwitchGLU decode (bit-identical to baseline) and prefill (compact vs mask).
Adds a usage docstring to the public enable_offload methods so an mlx-lm user sees the feature and how to size the resident set: resident_slots vs resident_bytes (preferred for mixed-precision tables), that both keeps the tighter, that it is opt-in because offload trades throughput for memory, and to leave page-cache headroom when budgeting bytes. The full sizing rationale (measurements, per-model re-derivation) stays in Mira's own docs.
|
Pushed the two things we agreed on. I also added the first offload tests in the tree ( Branch is updated to base. Ask-1, the shared per-SwitchGLU cache, stays a separate follow-up as we discussed. I'll open the fetch-shape question shortly so your pager and mira-core end up behind one interface. |
|
Picking up ask-1, the shared per-SwitchGLU expert cache, now that Here is what I am leaning toward; push back on any of it. One cache per SwitchGLU, keyed by For the contract itself, Coalescing I would keep out of the contract. Whether those three projections arrive from one coalesced byte-range read (your 9-adjacent case) or three separate reads is Two things I need from you to lock it. First, layout: on the GLM-5.2 shards, are an expert's three projections contiguous, so one pread coalesces them, or scattered across the shard? Your 9-adjacent number reads like adjacency, but I would rather hear it from the fetch you would actually hand in. Second, projection count: SwitchGLU is three (gate/up/down), SwitchMLP is two (fc1/fc2), and the coordinator will read that set off the module instead of hardcoding three. Does your pager ever wrap a block with a count I should not assume away?
|
|
@mabaeyens This shape works for us — the coherence-first cache we argued for, and we can hand you Layout. Two layouts; the fetch we'd hand in reads the coalesced one. Stock mlx-community shards are 9-scattered — an expert's three projections are slices of three separate stacked tensors ( Projection count. Always 3 (SwitchGLU, gate/up/down) — we only wrap GLM-5.2's One thing to pin, because it's where our cache-sizing result bites: how does the byte budget compose across the per-SwitchGLU caches? Our cache today is a single global |
|
This locks it, thanks. Both answers are what I needed, and the layout one is reassuring: the 9-scattered stock shards (three stacked tensors, each split into weight/scales/biases, non-contiguous and sometimes across shard files) are exactly why coalescing had to stay out of the contract. Your side-file does one pread, mlx-lm's own fetch does nine scattered reads, same On the byte budget you are right, and it is the part I had underweighted. It is the same effect I saw as page-cache headroom on my rig (240 to 280 microseconds per cold read as the resident set grows), just at your depth, where it turns into a +65% cliff. And what starves is the total, not any one layer, so a per-SwitchGLU So here is the shape I will build. One shared expert cache keyed Two small things. I will read the projection set off the module rather than hardcode three, so SwitchMLP's two-projection case (fc1/fc2) keeps working even though GLM never hits it. And One thing to confirm and the shape is locked. Do you want a single shared LRU across layers (your current design, global eviction, best under skewed access), or one global budget divided down into per-layer caches (simpler, rigid, fine at uniform decode)? I lean to the shared LRU, because then our interface and your validator are the same object and there is nothing to reconcile. Say which and I will drop the coordinator in behind your fetch. |
|
@pierre427 @doramirdor — iliria author here. Two clarifications on the Lineage. iliria is a genuine fork of JustVugg/colibri (Apache-2.0; attribution in
Scoping. @pierre427's framing is the correct one: "iliria reserves 2.5 GB for a measured reason," not a general throughput law. The in-source consequence is a hard floor in the RAM budget — The block size, since it wasn't recorded in the comment. The engine has exactly one bulk-read granularity: one whole expert per So the ~800 → ~180 MB/s collapse is on ~19 MB buffered preads, not small-block IO — worth stating explicitly, since the same squeeze behaves differently at 4K. Still a single rig, so I'd treat the direction as the transferable part; it lines up with the 240→280 µs per-miss rise you measured from the other side. Minor: it's iliria, one |
|
@PhilipJohnBasile Thanks for the block size — that was the missing coordinate, and "one whole expert per pread" (≈18.9 MB) fully specifies the figure at last: ~19 MB buffered preads, single rig, whole-expert granularity, 800→180 MB/s under page-cache squeeze. Folding that spec into how the summary cites it. On provenance, though, I have receipts that run the other way — with a correction for each of us in them: The measurement is in upstream colibri, and predates iliria's publication. Raw-fetching upstream at historical snapshots: the RISERVA comment is present in colibri's And the symmetric correction is mine. I claimed the fork "dropped the su Linux tag" — wrong. The 07-06 original had no platform tag; upstream added "su Linux" on 07-15 ( The timeline then settles the platform for free: at 16:00 on 07-06, colibri was Linux-only — the macOS/Apple-Silicon port (RDouglasSharp's PR #1) landed four hours after the reserve commit. So the measurement could not have been on a Mac, and woolcoxm's later "su Linux" annotation is provably correct, not just plausible. Net scoping is unchanged and now fully specified: Linux, ~19 MB whole-expert buffered preads, single rig — mechanism transferable, magnitude not, with @pierre427's +65% cliff as the Apple-side number and your 2.5 GB floor as the Linux-side consequence. Spelling is fixed everywhere it was mine to fix (summary v1.4.1 + a sweep of my older comments), and the Hub container link is a welcome addition — that's the reproduction path for the GLM cells this thread never had. |
|
Correction to my previous comment — I was wrong, and @doramirdor's v1.5 scoping was right. I claimed that measurement was iliria's own rather than inherited, on the basis that a code search over colibri returned no matches. That was a bad instrument, not evidence: the file is /* RISERVA PAGE-CACHE (misurato 2026-07-06 su Linux): strangolarla fa crollare
* le pread buffered da ~800 a ~180 MB/s — gli ultimi GB di LRU rendono MENO di
* quanto costino in banda disco persa. 2.5 GB restano SEMPRE al kernel. */So the measurement is inherited — and colibri's version carries a qualifier that iliria's copy dropped: "su Linux." "Mechanism exists (Linux, The block-size figure stands on its own — iliria reads one whole expert per |
|
@doramirdor Receipts accepted on both counts — and the mechanism is the valuable part. My zero-hit wasn't "not indexed" in some vague sense; it was the >350 KB silent skip, which converts a missing result into a confident false claim with no warning attached. It's in our traps list with the control spelled out: before trusting any zero-hit over a repo, check the size of the file you'd expect the match in — if it's over ~350 KB, the search told you nothing. The symmetric withdrawal on the "su Linux" tag is noted with thanks; the 07-06/07-15 timeline settling the platform for free is the cleanest kind of resolution — nobody's memory, everyone's receipts. |
|
Thanks for the PR but at the moment the number of PRs is way beyond our capacity to review so I'm closing the non-essential ones so we can actually work on this repo. |
What this adds
An opt-in
enable_offload(resident_slots, fetch_fn)onSwitchLinearandQuantizedSwitchLinear. When enabled, onlyresident_slotsexperts stay resident in a dict-keyed LRU cache; the rest are fetched on a router miss via a caller-suppliedfetch_fnand evicted to capacity. The forward path reads only the cache, never the full stacked weight, so a MoE model whose expert table exceeds unified memory can run with just the resident set plus activations live.This addresses #1438 (running MoE models larger than unified memory on Apple Silicon). It is a single-file change and off by default; nothing changes unless a caller opts in.
How it is meant to be used
The primitive is deliberately storage-agnostic:
fetch_fn(expert_id)returns the raw host data for one expert, and the caller decides where it comes from. In my app I read expert bytes by explicit byte-range from the model's own safetensors shards (0.3 to 0.6ms per expert on an Apple SSD, no repacking, no separate cache format). Two design points I learned the hard way:mx.arrayfor a fetched expert must be constructed on the thread that runs the model. MLX arrays are thread-affine, so building one on a worker thread crashes the first time the engine thread touches it. Split the disk I/O (parallel, thread-safe) from the array construction (on the calling thread).There is also a subtle memory point baked into the seeding: seed the resident set from
fetch_fn, not by slicing the loaded weight, and replace the weight with a 1-row stand-in. A prefix slice of anmx.arrayis a view that pins the whole parent buffer, so slicing does not actually free the rest of the table.Demonstrated
Running Qwen3.6-35B-A3B-8bit (35GB on disk, ~33.8GB stacked expert table) on a 32GB Mac, where eager load cannot complete: with
load(lazy=True)plus offload at fraction 0.3 it loads and generates coherent text at a peak of 12.7GB resident.Honest tradeoff
Offload trades throughput for memory and should be used only when a model would not otherwise fit. On a model that does fit (Qwen3.6-35B-A3B-4bit), enabling offload at fraction 0.3 measured about 5x slower decode and 8 to 12x slower prefill, because a diverse prefill routes to nearly all experts while the cache holds only a fraction, so it re-fetches most of the table every prefill.
Those two figures predate the two commits below and now understate the current state. Both commits cut part of that tax without moving hit_rate, and both are bit-identical to the path they replace: the compact chunked-gather drops the G-fold matmul on sorted prefill, and the lone-group guard skips a memory barrier that does nothing at decode. Their measurements are in the comments below, and I will update this section with a fresh end-to-end measurement on the current build.
Co-activation-aware on-disk expert ordering is the remaining natural follow-up and is out of scope here. Cross-layer prefetch is not a follow-up: it measures as a null on this architecture, see #1438.
Notes
fetch_fnand the lazy-load wiring live in my application, not in this PR, since they are storage- and app-specific. Happy to add a small referencefetch_fnor a short doc example if that would help.