Skip to content

Add opt-in disk-backed expert offloading to SwitchLinear/QuantizedSwitchLinear - #1588

Closed
mabaeyens wants to merge 8 commits into
ml-explore:mainfrom
mabaeyens:expert-offload
Closed

mabaeyens wants to merge 8 commits into
ml-explore:mainfrom
mabaeyens:expert-offload

Conversation

@mabaeyens

@mabaeyens mabaeyens commented Jul 19, 2026 •

Copy link
Copy Markdown

What this adds

An opt-in enable_offload(resident_slots, fetch_fn) on SwitchLinear and QuantizedSwitchLinear. When enabled, only resident_slots experts stay resident in a dict-keyed LRU cache; the rest are fetched on a router miss via a caller-supplied fetch_fn and 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:

  • The cache is dict-keyed rather than a fixed slot array. With a fixed array, an eviction later in the same forward call can overwrite a slot an earlier expert already resolved to, because the gather runs only after every index in the call resolves. A dict has no shared slots to collide over.
  • The mx.array for 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 an mx.array is 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

  • No change to the default path; existing models load and run identically.
  • The disk-backed fetch_fn and the lazy-load wiring live in my application, not in this PR, since they are storage- and app-specific. Happy to add a small reference fetch_fn or a short doc example if that would help.

…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.
mabaeyens added a commit to mabaeyens/mlx-lm that referenced this pull request Jul 19, 2026
_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.
@mabaeyens

Copy link
Copy Markdown
Author

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. _offload_chunked_gather bounds transient memory by partitioning a call's unique experts into groups of at most max_stack_size and running each group's gather_fn over the full index tensor, discarding out-of-group positions with mx.where. That holds memory for any call shape, but it costs G times the matmul, since each of the G groups touches every position. On a diverse prefill (nearly all 256 experts, max_stack 64, so G = 4) that is a 4x compute tax sitting on top of the disk misses.

The fix. SwitchGLU and SwitchMLP already sort the routing before dispatch whenever indices.size >= 64, which is exactly the multi-group prefill case, and they pass sorted_indices=True. When that holds and the flat index run is verified monotonic, each group's positions are one contiguous slice, so I slice x to that segment, gather once over just those positions, and concatenate the segments, with no mx.where. It is guarded by an actual monotonicity check rather than trusting the flag, so a mislabelled sorted_indices falls back to the existing mask path. Fetch and eviction are untouched, so disk behavior and output are identical; only the matmul and combine change.

Measured on Qwen3.6-35B-A3B-4bit, offload on at fraction 0.3, 3022-token prefill, fresh backend:

prefill cold prefill warm decode peak hit_rate
this PR (mask) 75.7 t/s 75.7 t/s 10.2 t/s 7.31GB 0.514
compact 136.2 t/s 129.9 t/s 12.3 t/s 7.34GB 0.514

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 _offload_chunked_gather plus threading sorted_indices through the two __call__ sites, so it is a small addition on top of what is already here.

@mabaeyens

Copy link
Copy Markdown
Author

A second follow-up on the same chunked gather, this time for decode rather than prefill. Also measured and bit-identical.

Context. _offload_chunked_gather calls mx.eval() after each group's combine, which forces MLX to release the previous group's temporary stack before the next group's gather allocates. That eval is what makes the max_stack_size memory bound real, since without it laziness re-batches every group into one deferred graph and the bound is fiction. But it only does anything across groups. Decode routes to a single group every step, because the top_k experts a token selects fit inside one max_stack (8 <= 64), so there is never a next group to bound against. On the single-group path the eval just forces a per-layer GPU sync, roughly 3 per layer over 40 layers per token, where a fully resident model evals the whole token once.

The fix. Skip the eval when len(groups) == 1 and let MLX defer the token's gather graph to the caller's next eval boundary, which for generation is the sampler evaling each token anyway. Prefill is untouched: its multi-group mask path and the compact path both keep their per-group evals, so the memory bound still holds wherever it actually matters. Output is bit-identical (guarded), and I check that peak does not move, since deferring the graph is exactly what could have raised it.

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:

decode peak prefill
barrier every group 7.15 t/s 12.73GB 117.3 t/s
skip lone-group barrier 8.09 t/s 12.73GB 120.0 t/s

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 _offload_chunked_gather, one guard on the existing eval. Happy to fold both into the PR if useful.

@lBroth

lBroth commented Jul 20, 2026

Copy link
Copy Markdown

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 enable_offload up to my byte-range reader and ran it on two larger models on an M5 Pro (48 GB), both larger than RAM. It just worked, across two architectures and two quant formats:

  • GPT-OSS-120B, MXFP4 (61 GB expert table), resident fraction 0.3: 18.7 GB peak, ~7.7 tok/s steady, coherent output. Your mode passthrough handles MXFP4 fine — the fetch returns (weight, scales, None) since there are no quant zero-points, and the FFN bias stays resident.
  • Qwen3-235B-A22B, affine Q4 (118 GB table, ~2.6x the 48 GB RAM), resident fraction 0.2: 28.5 GB peak, ~1.35 tok/s, coherent output. Fraction 0.3 OOMs here, as you'd expect: for a table this much larger than RAM the resident set has to be a smaller fraction.

So the primitive scales well past the 35B demo, and it's genuinely architecture- and quant-agnostic. The dict-keyed cache and the max_stack_size bound both earn their place at this scale — I hit exactly the chunked-gather OOM you describe before dropping the fraction.

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.
@mabaeyens

Copy link
Copy Markdown
Author

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.

@mabaeyens

Copy link
Copy Markdown
Author

@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 _offload_chunked_gather, so your reader needs no changes: a compact gather that drops the G-fold matmul on sorted prefill, and a skipped memory barrier at decode. If you re-run, I would be glad to see whether they hold at your scale, where the miss rate is much higher than mine.

@lBroth

lBroth commented Jul 20, 2026

Copy link
Copy Markdown

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 switch_layers.py unmodified (verified from the loaded module source, and byte-identical to head 7c341cd); the fetch_fn and driver around it are mine, since the PR is a primitive that needs both. Quiet machine, greedy, warmup then repeats, arms in separate processes:

model fraction b547bcb 7c341cd
GPT-OSS-120B MXFP4 0.3 8.685 +/- 0.070 9.997 +/- 0.132 +15.1%
Qwen3-235B-A22B Q4 0.2 1.524 +/- 0.010 1.671 +/- 0.007 +9.6%

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:

model layers experts k measured shuffled ratio
Qwen3-Coder-Next-80B 48 512 10 0.0107 0.0108 0.990x
GPT-OSS-120B MXFP4 36 128 4 0.0186 0.0189 0.982x

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:

off on
decode tok/s 12.773 +/- 0.169 12.404 +/- 0.222
synchronous SSD read 81.65 GiB 66.67 GiB
prefetch SSD read 0 103.86 GiB
prefetch precision n/a 14.4%

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 enable_offload, but the same comment described wiring your code up for the residency runs, so it reads as if the prefetch arm ran there too. It did not. It was also one run per side, and one supporting table was not a comparison at all: lever flags passed inside the label string, so both cells ran prefetch-off (byte-identical hit rates gave it away). The conclusion survives and is now measured properly, but what you were weighing was one noisy null and one unrepeated run.

Two small ones. Your branch does not touch SSM code; the one failure in tests/test_models.py here is test_ssm, which also fails on main on this machine (M5, mlx 0.32.0), so it is unrelated to your change. And the resident fraction you asked about: 0.3 OOMs on the 235B and works on the 120B, the two tables being about 2.6x and 1.3x RAM, so the useful fraction tracks table/RAM rather than being constant. I did not bisect the boundary.

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.
@mabaeyens

Copy link
Copy Markdown
Author

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 enable_offload, which is exactly the misreading you've flagged. I wanted a third null that settled the question and I didn't check what it had actually run against. What you've posted now is better evidence than what I was crediting you with, so the conclusion is on firmer ground than it was before.

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 test_ssm fails on main on your machine, I had no way to show that from here.

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.

@mabaeyens

Copy link
Copy Markdown
Author

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 test_ssm failure reproduces on main, which saved me guessing.

@pierre427

Copy link
Copy Markdown
Contributor

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 switch_mlp replacement. We'd rather build on enable_offload than maintain that boundary, and we're adopting the coalesced side-file layout from the #1438 campaign — which makes the two open hooks concrete for us:

  1. Fetch-at-dispatch / whole-expert granularity (A2): with a per-expert-contiguous container, our natural fetch is ONE pread returning all three projections' (weight, scales, biases). Under the current per-projection fetch_fn, that becomes three fetches against three independent LRUs — tripling reads on a layout whose entire point is one. A shape that would work for us without disturbing the existing API: keep per-projection fetch_fn as-is, but allow the three SwitchLinears of one SwitchGLU to share a memoized per-expert fetch (the projection-level fetch_fns become slice views into one cached block). Happy to prototype against whatever shape you prefer — we have a concrete consumer to validate it.

  2. Byte-bounded capacity: resident_slots is a slot count; for heterogeneous or mixed-precision experts, bytes are the real budget. An optional resident_bytes (slots derived from measured per-expert bytes) would let byte-budgeted callers avoid wrapping the LRU. Related datapoint for the docs note you offered: when budgeting bytes on Apple SSDs it's worth reserving explicit page-cache headroom — the iliria measurements in Feature request: MoE expert streaming / SSD offload for memory-constrained Apple Silicon (run 395 GB GLM-5.2-mxfp4 on 128 GB RAM) #1438 put buffered pread throughput collapsing ~800→180 MB/s when the page cache is squeezed.

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.

@doramirdor

Copy link
Copy Markdown

@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 expert_offset[e] + block_bytes (the one pread), each of the 9 subs with relative offset / size / dtype / per-expert shape (your projection-level slice views), and proj_ranges for the per-projection A1 fallback — it was designed so one file serves both granularities, so prototyping your shared-fetch shape needs no format changes. It also embeds source_stamp (per-shard size + sha256 of the safetensors header) with a verify_source_stamp() helper, so the side-file stays a verifiable disposable cache and read-straight-from-shards remains the invariant path — built for exactly the durability concern a duck-typed boundary has. On naming: your gate/up/down × {weight, scales, biases} is the same 9-sub geometry, and st_map's regexes are prefix-agnostic with sub-set discovery — coalesce_rewrite.py ran unmodified on Qwen3-235B (94 layers × 128 experts, 119 GB side-file, bit-exact 64/64), so switch_mlp naming on GLM-5.2 should run as-is. If anything trips, post the tensor-name listing and I'll confirm the regexes same-day.

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.

@pierre427

Copy link
Copy Markdown
Contributor

@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 glm.c (~line 4261): “RISERVA PAGE-CACHE (misurato 2026-07-06): strangolarla fa crollare le pread buffered da ~800 a ~180 MB/s”, which is why it hard-codes the 2.5 GB kernel reserve. The date suggests it may even be inherited from the colibri parent, and it's a single-rig number with unstated block size — so treat it as “iliria reserves 2.5 GB for a measured reason,” not a general throughput law. My comment compressed “iliria, as discussed around #1438” into a false citation; #1438's own numbers are as you state them. The headroom advice stands on your 240→280 µs direction regardless.

On 1: we'll run coalesce_rewrite.py against the GLM-5.2 affine-4bit shards as-is and post the tensor listing only if it trips. On 2: g ≈ 1.2 band 1.15–1.3 is registered on our side too — the A/B will report s and g separately so it falsifies cleanly, and agreed the coherence argument is the durable case for ask 1.

@doramirdor

doramirdor commented Jul 22, 2026 •

Copy link
Copy Markdown

@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 glm.c find; the 240→280 µs per-miss rise as resident fraction grows in the sweep here; and our own 64 GB-Mac squeeze runs, where an mlocked holder past ~48 GB didn't just slow reads but destabilized whole sessions — the same cliff from the other side).

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.

@pierre427

Copy link
Copy Markdown
Contributor

@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: coalesce_rewrite.py's regexes matched all 675 GLM switch_mlp tensors as you predicted; the only trip was the completeness assert over range(n_layers) — GLM's first 3 layers are dense, so the loop needs the sparse layer set. Manifest schema otherwise adopted unchanged (407.69 GB side-file, bit-exact 128/128; the 21,233,664-byte expert is exactly 1296×16 KiB, zero padding).

@mabaeyens

Copy link
Copy Markdown
Author

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 (resident_bytes): agreed, and straightforward. I'll add it as an optional alternative to resident_slots; bytes derive the slot count from the measured per-expert size, since a slot count is the wrong budget once experts are mixed-precision.

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 range(n_layers)), and the page-cache-headroom docs note (I'll cite the 240→280 µs direction, not the retracted 800→180 figure).

One unrelated thing: test_ssm fails on main here too, so it isn't coming from this branch.

@doramirdor

doramirdor commented Jul 22, 2026 •

Copy link
Copy Markdown

@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. st_map now discovers the sparse MoE layer set (STMap.layers) and validates completeness over that instead of range(n_layers); coalesce_rewrite.py iterates it, the verify loop samples from the actual entries, and the manifest schema is unchanged (entries always carried absolute layer ids) plus a top-level moe_layers list. Qwen regression after the change: discovery identical, 16/16 bit-exact. Thanks for the exact trip report — and for the 21,233,664-byte detail: exactly 1296 × 16 KiB with zero padding means the block size is page-aligned by construction on Apple Silicon, which is a nice property to get for free. The trace-coupled analysis scripts still assume trace layer i = i-th MoE layer; if a GLM routing trace ever exists, map through STMap.layers.

@mabaeyens both calls look right from here. resident_bytes deriving slots from measured per-expert size is the correct shape for mixed-precision tiers. And splitting the shared per-SwitchGLU cache into a follow-up matches the evidence: on I/O it only earns at deep-offload s (lBroth's fetch-at-dispatch build measured +31.2% at 25/128 resident — prior art for the follow-up's shape, so it starts with two consumers), while the durable argument at moderate s is coherence, which is a design axis, not an offload primitive. The 240→280 µs citation for the docs note is the right one.

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.
@mabaeyens

Copy link
Copy Markdown
Author

Pushed the two things we agreed on. resident_bytes is in as an optional alternative to resident_slots: it derives the slot count from the measured per-expert size, and when both are given it keeps the tighter, so a byte budget can only lower a count, never raise it.

I also added the first offload tests in the tree (tests/test_switch_offload.py, 11 of them). The feature shipped with no in-tree coverage, all of it lived in mira-core. They cover dense and quantized against an eager baseline, the byte-budget derivation on both tiers, the fetch_fn and no-budget guards, and SwitchGLU decode (bit-identical) and prefill (compact vs mask). Plus a short sizing docstring on enable_offload; the full rationale, the page-cache measurements and the per-model re-derivation, stays in our own docs rather than bloating the docstring.

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.

@mabaeyens

Copy link
Copy Markdown
Author

Picking up ask-1, the shared per-SwitchGLU expert cache, now that resident_bytes has landed. Before I prototype I want to pin the fetch interface, so your pager and mira-core both sit behind it and neither of us has to reshape later.

Here is what I am leaning toward; push back on any of it. One cache per SwitchGLU, keyed by expert_id, holding all three projections (gate/up/down) as a single unit that is either all resident or all evicted. That all-or-none residency is what actually motivates this. The I/O barely moves at moderate s (your 0.345 vs 0.343) and only pays at deep offload, so the interface should be built around coherence, not read count.

For the contract itself, fetch_fn(expert_id) returns raw host data for the whole expert: an ordered per-projection structure, each projection the same raw shape the current primitive already returns (dense is one array's bytes; quantized is weight + scales + biases, with biases possibly None). Concretely a list in projection order [gate, up, down], each entry the per-projection raw tuple. Same thread-affinity rule as today, fetch hands back host bytes and the mx.array gets built on the model thread.

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 fetch_fn's business, invisible to the cache. That leaves the deep-offload win open to whoever's layout is adjacent, without baking any on-disk assumption into mlx-lm.

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?

resident_bytes now measures the whole expert (sum over the projections) rather than one matrix, so the byte budget carries over cleanly. If the shape works for you, I will prototype the SwitchGLU/SwitchMLP coordinator against it and wire mira-core in as the second consumer; then you drop your pager's fetch in behind the same interface.

@pierre427

Copy link
Copy Markdown
Contributor

@mabaeyens This shape works for us — the coherence-first cache we argued for, and we can hand you [gate, up, down] with each entry the per-projection raw tuple straight from one read. Keeping coalescing out of the contract is the right call: it's what lets our side-file's adjacency pay at deep offload without mlx-lm knowing. resident_bytes on the whole expert closes ask-2. Your two:

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 (switch_mlp.{gate,up,down}_proj), each split into weight/scales/biases, and they're non-contiguous, sometimes across different shard files (layer 3's down_proj is in model-00002 while gate/up are in model-00001). That's the baseline the side-file exists to fix. Our side-file stores each expert as one 16 KiB-aligned block, 9 subs adjacent (projection-major), so the fetch is a single ~20.25 MiB coalescing pread (exactly 1296×16 KiB — page-aligned by construction) that we slice into [gate, up, down]. Internally our reader returns a projections mapping, but the bytes are proj-major, so handing you the ordered list is free. A stale/missing side-file can fall back to the 9-scattered shard reads (that path exists); we keep the explicit side-file request strict so an A/B can't silently degrade.

Projection count. Always 3 (SwitchGLU, gate/up/down) — we only wrap GLM-5.2's switch_mlp, never a 2-projection SwitchMLP, and the loader rejects any other switch_mlp tensor name, so reading the set off the module is correct; no count to accommodate for us. Each projection is (weight, scales, biases), affine-4bit with all three always present (your "biases possibly None" covers the MXFP4 case, not ours).

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 MaterializedExpertCache keyed (layer, expert) under one max_cache_bytes — deliberately global, because the +65% cache-cliff is about the total resident footprint vs the OS page cache the side-file streams through, and the starvation threshold is global (tens of GB), not per-layer. If each of the 75 sparse SwitchGLUs sizes resident_bytes independently, their sum is what has to stay under the cliff — so the coordinator needs a shared/global ceiling (or a way to divide one down to the per-layer caches), not 75 budgets that can sum past it. At uniform decode access the per-layer split is fine numerically; the knob that matters is the total. Expose that and the shape's locked — I'll drop our fetch in behind it.

@mabaeyens

Copy link
Copy Markdown
Author

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 [gate, up, down] on the other side.

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 resident_bytes that all 75 layers satisfy locally can still sum past the ceiling. A local budget is the wrong unit for a global resource.

So here is the shape I will build. One shared expert cache keyed (layer, expert) under a single byte ceiling, which is your MaterializedExpertCache, with resident_bytes as a model-global knob rather than 75 independent ones. The per-layer LRU falls out of the shared store, and coherence is unchanged: an expert is its three projections, resident or evicted together. enable_offload takes an optional shared cache object; pass it and every SwitchGLU feeds one store and one ceiling, omit it and you get the per-module behavior that shipped in #1588. That primitive stays as-is, by the way, a shared cache still needs a per-entry byte measure and resident_bytes already gives it one.

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 _offload_data_nbytes already sums a (weight, scales, biases) tuple with biases possibly None, so the MXFP4 case is covered; your affine-4bit with all three present is the easy path.

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.

@PhilipJohnBasile

PhilipJohnBasile commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

@pierre427 @doramirdor — iliria author here. Two clarifications on the glm.c citation, plus the block size that was missing from it.

Lineage. iliria is a genuine fork of JustVugg/colibri (Apache-2.0; attribution in NOTICE and per-file headers), so checking provenance was the right instinct. But that measurement is not inherited — a code search over colibri finds no RISERVA PAGE-CACHE and no 800→180 figure. It's iliria's own, dated 2026-07-06.

⚠️ Retracted — this was wrong. The measurement is inherited: it is at c/colibri.c:6141, and colibri's version says "misurato 2026-07-06 su Linux". My code search returned nothing because GitHub does not index that file — absence of hits was not evidence of absence. @doramirdor's original scoping was correct. See the correction comment below.

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 — pc_b = 2.5e9, withheld from the expert-cache slack unconditionally, because the last GB of LRU cost more in lost disk bandwidth than they return in hit rate.

The block size, since it wasn't recorded in the comment. The engine has exactly one bulk-read granularity: one whole expert per pread (wtot = gate + up + down, fetched as a single read into an aligned slab). At GLM-5.2 dims that is

3 × 2048 × 6144 int4 weights  = 18,874,368 B
+ 10,240 per-row f32 scales   =     40,960 B
                              = 18,915,328 B  ≈ 18.9 MB

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 l — github.com/PhilipJohnBasile/iliria. The int4 container it serves is on the Hub if it helps reproduce any of this: philipjohnbasile/GLM-5.2-colibri-int4-with-int8-mtp (int8 MTP heads).

@doramirdor

Copy link
Copy Markdown

@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 c/glm.c by end of day 2026-07-06 (snapshot 193d2ce92d), and the introducing commit is 3278ea78d0 — author JustVugg, 2026-07-06T16:00:35Z, message "reserve 2.5 GB for the page cache in the RAM budget: starving it drops…". Why your code search said no: upstream's file is now c/colibri.c at ~400 KB, and GitHub code search silently skips files above ~350 KB — a confident false negative with no warning. Worth adding to everyone's traps list: code search absence over large files is not absence.

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 (d0971ff7c1). iliria's copy preserves the original text faithfully. Withdrawn.

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.

@PhilipJohnBasile

Copy link
Copy Markdown
Contributor

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 c/colibri.c (6,743 lines), which GitHub code search does not index. Fetching the raw file shows the comment at colibri.c:6141, exactly where you had it:

/* 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, colibri.c:6141), not Apple sizing — this curve is the Apple number" is precisely correct, and my attempted correction of it was the error. Sorry for the noise.

The block-size figure stands on its own — iliria reads one whole expert per pread, 18,915,328 B ≈ 18.9 MB at GLM-5.2 dims — but that is the Apple/iliria read granularity and should not be attached to the Linux 800→180 number without re-measuring on Apple. I'd treat those as two separate facts until someone runs the squeeze on an Apple rig at 19 MB blocks.

@PhilipJohnBasile

Copy link
Copy Markdown
Contributor

@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.

@zcbenz

zcbenz commented Aug 21, 2026

Copy link
Copy Markdown
Member

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.

@zcbenz zcbenz closed this Aug 21, 2026
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.

6 participants