Skip to content

llama : one MoE cache entry per expert weight for looped layers - #421

Open
danielhanchen wants to merge 2 commits into
base/upstream-e300919ccfrom
moe-cache-loop-dedupe
Open

danielhanchen wants to merge 2 commits into
base/upstream-e300919ccfrom
moe-cache-loop-dedupe

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Pin for the prebuilt: upstream b12631 (e300919) plus this change (two commits: the cache, then the trace and tuner). Base branch base/upstream-e300919cc.

Fixes the duplication reported in ggml-org#32744.

What it changes

The MoE expert cache (--moe-cache-mib, src/llama-moe-cache.cpp, upstream since ggml-org#29887) keys its slots, LRU entries and slot maps by layer index. A looped model runs the same physical layer several times: Inkling-2-Mini has 48 layer visits over 24 physical layers (core layers 6 to 17 run 3 times), and the later visits read the same expert weights (the same tensor upstream, or whole views of it with #396). The cache treated each visit as its own layer, so:

  • the same expert of the same weight could sit in up to 3 slots and be uploaded up to 3 times,
  • the host expert total counted each core layer 3 times (UD-Q4_K_XL logs 28188.00 MiB of host experts for 15066 MiB of experts),
  • the slot cap was visits x experts, and the budget split between groups weighted core layers 3 times.

With this change, a layer whose expert tensors are the same weights as an earlier layer of its group (same tensor, or an offset-0 view with the same type, shape and strides) shares that layer's slots, LRU keys and slot map data. Each cached expert is stored once and uploaded once. The owner's visit advances the LRU clock once per ubatch, so the recency half-life is still counted in tokens. Each visit keeps its own slot map tensor (the scheduler copy and the copy callback find the lookup by it) and its own CPU-miss map. The host bytes, the budget split between groups and the slot cap count each expert weight once. The physical-bytes budget split follows AhmadSaeedZaidi's #410.

A model with no shared expert weights runs the old code path unchanged: every layer owns itself and the byte counts are the same. LLAMA_MOE_CACHE_DEDUPE=0 restores one entry per layer visit for looped models too. test-llama-archs now also runs inkling2_loop with host experts and with the MoE cache, so a looped model with shared expert weights is checked against the CPU through the cache.

--moe-cache-mib auto (#251) is updated in its own branch so that its minimum cache size counts shared experts once, which keeps it consistent with this split. At the old visit-weighted minimum for UD-IQ1_S (299 MiB), the 1-layer NVFP4 core group gets 0 slots and is not cached. At the new minimum (438 MiB), it gets exactly 8 slots (n_expert_used).

Evidence (B200, the current pr-set at b12631 vs the same tree + this commit and the #251 update, all routed experts in host RAM via -ot exps=CPU)

Exactness, Inkling-2-Mini, llama-perplexity wikitext-2 -c 512 --chunks 20, KLD against the pin set:

file, cache, ubatch PPL (pin set = this commit = DEDUPE=0) mean KLD same top hit rate uploaded distinct experts / slots
UD-IQ1_S, 2500 MiB, -ub 4 8.468848 0 100% 58.4% -> 87.3% 1972 -> 585 GiB 775 of 1200 -> 1226 of 1226
UD-IQ1_S, 5500 MiB, -ub 4 8.468848 0 100% 87.6% -> 99.6% 573 -> 17.2 GiB 1544 of 2647 -> 2707 of 2707
UD-IQ1_S, 2500 MiB, -ub 512 8.463164 0 99.980% (pin set A/A: 99.980%)
UD-IQ1_S, 5500 MiB, -ub 512 8.463164 0 99.980% (pin set A/A: 99.980%)
UD-Q4_K_XL, 4999 MiB, -ub 4 7.676816 0 100% 55.7% -> 81.3% 4768 -> 2013 GiB 1016 of 1016
UD-Q2_K_XL, 3000 MiB, -ub 2 8.086630 0 100% 65.6% -> 89.6% 2489 -> 714 GiB 1217 of 1217

With LLAMA_MOE_CACHE_DEDUPE=0, every run reproduces the pin set's cache log lines, slot counts, hit counts and upload bytes exactly. Greedy decode (128 tokens) is byte-identical on all three arms, with the hit rate going from 72% to 89-92%.

When does output change? A group is read from the cache for a ubatch only if it has at least n_tokens x n_expert_used slots (up to n_expert). Otherwise that layer's experts are computed from the host weights, on the CPU for small batches. The new split gives some groups more slots and some fewer, so near that threshold a layer can switch paths, and CPU and GPU round differently. Two cases came up:

  • UD-Q2_K_XL at 3000 MiB with -ub 4: the 1-layer MXFP4 group had 23 slots on the pin set (below the 32 ids, so CPU) and has 50 now (cached). The result was mean KLD 0.000087 and top-1 99.765%. At -ub 2, where every group is cached on both arms, the result is in the table.
  • UD-IQ1_S at 2500 MiB, decoding a 9-token prompt at the default ubatch: the 1-layer NVFP4 core group went from 74 to 50 slots, below the 72 ids. With -ub 4, all three arms give the same text.

The cache itself returns the same results on every arm whenever the same layers are read through it.

Non-looped no-op, OLMoE-1B-7B f16 (16 layers, 64 experts), cache 3000 MiB: the MoE cache log lines (3000.00 MiB for 12288.00 MiB of host experts, 249 slots), hit/miss/upload counts and greedy text are identical to the pin set. PPL is string-equal (10.2627) and mean KLD 0. Same top is 99.961% here and on the pin set's own A/A, which comes from the quantized stored base log-probs.

Host-expert offload (ggml-org#32807 trap)

ggml-org#32807 (merged after b12631) stops the partial expert copy for inkling2_loop, because one device copy of a shared host weight held only the experts that the first pass selected. This commit does not change which tensors the graph reads. A visit that misses the cache still reads its own host weight, which is a separate view with #396, so the scheduler still makes one copy per visit. Only the cache's slots and its large-batch copy_experts source are shared, and both hold the same weight data. Checked on UD-IQ1_S at the default batch (512, so prompt batches take the host-expert copy path), on the pin set and on the previous revision of this commit (identical in this respect):

Decode speed

Decode speed, Inkling-2-Mini UD-Q4_K_XL, llama-completion -n 256. The cache size is what --moe-cache-mib auto picks for an 8 GB and a 12 GB card, emulated with --fit-target; the same size is used for every arm. One exclusive B200, 3 interleaved repeats per arm, medians. "Previous revision" is this commit with the visit-weighted split and redistribution, before the #410 split was folded in.

card arm tok/s (median; repeats) hit rate uploaded per run
8 GB (cache 5002 MiB) pin set / A/A 15.09 / 14.49 (14.95-15.45; 11.67-15.05) 72.2% 121 GiB
8 GB (cache 5002 MiB) this commit 29.24 (29.17-29.28), 1.9x 89.5% 46 GiB
8 GB (cache 5002 MiB) previous revision 29.65 (25.53-29.68) 90.9% 45 GiB
8 GB (cache 5002 MiB) DEDUPE=0 15.30 72.2% 121 GiB
12 GB (cache 9098 MiB) pin set / A/A 26.59 / 24.41 (26.06-26.95; 23.45-26.78) 87.5% 54 GiB
12 GB (cache 9098 MiB) this commit 51.65 (49.77-52.40), 1.9x 97.5% 11 GiB
12 GB (cache 9098 MiB) previous revision 47.22 (44.83-51.25) 97.9% 11 GiB
12 GB (cache 9098 MiB) DEDUPE=0 23.97 87.5% 54 GiB

On UD-Q4_K_XL the physical split caches slightly fewer hits than the previous revision (89.5% vs 90.9% at 8 GB, 2% more upload bytes). The tok/s difference (-1.4% at 8 GB, +9% at 12 GB) is inside the pin set's own A/A spread on this run, so the change is a tie on Q4_K_XL. On UD-IQ1_S it is clearly better (at 5500 MiB the hit rate is 99.6% instead of 97.7%, and the uploads are 17 GiB instead of 95 GiB). Decoded text is byte-identical across all 15 runs. On a Colab L4 (PCIe 4.0), the previous revision went from 8.27 to 17.48 tok/s at 8 GB and from 14.99 to 28.96 at 12 GB against the kill switch. Those runs were not repeated for this revision.

Trace and tuner

A trace (LLAMA_MOE_CACHE_TRACE) with shared layers is written as MCT2, which records each layer with its owner. Traces without shared layers stay MCT1. scripts/moe-cache-tune.py reads both: it plans each layer in its owner's slots, advances the clock on the owner's lookup only, and caps the slots and full-cache size at the distinct experts. On a real UD-IQ1_S trace (2500 MiB, -ub 4) the replay predicts exactly the runtime's uploads, with dedupe on (7164.58 MiB) and with LLAMA_MOE_CACHE_DEDUPE=0 (21714.53 MiB). tests/test-moe-cache-tune.py checks two synthetic traces.

Pin set

  • test-llama-archs: inkling2_loop, deepseek2 and qwen3moe pass every row on the pin set and with this commit, including the inkling2_loop MoE cache row, where 4 layer visits share the experts of 3 layers.
  • test-backend-ops CUDA0 (pin set + this commit on b12647): MUL_MAT 2861/2861, MUL_MAT_ID 1177/1177, PAD 37/37, GET_ROWS 361/361.

Not covered

  • --moe-cache-cpu-share > 0. With shared slots fewer misses go to the CPU, so the CPU computes a different set of experts than before. The output is then not bit-comparable with the old code, and it was not measured.
  • Multi-GPU layer split. Groups stay per device, and visits of one weight on two devices are not shared. Only one GPU was run.
  • HIP, Vulkan and Metal did not run. The change is host-side C++ in src/llama-moe-cache.cpp with no backend code, but the cache itself only runs on GPU backends.

The layers of a looped model (Inkling 2, 48 visits of 24 layers) that read the
same expert weights got one cache entry, one slot map and one upload per visit:
Inkling-2-Mini UD-Q4_K_XL reported 28188 MiB of host experts for 15066 MiB of
experts. A layer whose experts are the same tensors as an earlier layer of its
group (or whole views of them) now shares that layer's slots and LRU keys. The
owner's visit advances the LRU clock once per ubatch. Each layer keeps its own
slot map tensor and CPU map. The host bytes, the budget split among the groups
and the slot cap count each expert weight once. The physical-bytes budget
split follows AhmadSaeedZaidi's #410. Models without shared
expert weights are unchanged. LLAMA_MOE_CACHE_DEDUPE=0 restores one entry per
layer.

test-llama-archs runs inkling2_loop with the experts in host memory and with
the MoE cache, so a looped model with shared expert weights is checked against
the CPU through the cache.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T05:19:11.102902Z b336a7e Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 975c44a447

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/llama-moe-cache.cpp
size_t n_hit = 0;
if (!g.lru.plan(il, ids.data(), ids.size(), sel->src[0]->ne[1], n_used, n_zero, n_cpu, fills, cpu, n_hit)) {
// a layer that shares the slots of its owner plans in its slot map, the owner's visit advances the clock once per ubatch
if (!g.lru.plan(l.owner, l.owner == il, ids.data(), ids.size(), sel->src[0]->ne[1], n_used, n_zero, n_cpu, fills, cpu, n_hit)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Update trace replay to account for shared cache owners

For looped models with deduplication enabled, the runtime now plans against the owner's cache keys, but the unchanged MCT1 trace still records logical layer IDs without their owner mapping. scripts/moe-cache-tune.py consequently replays these visits as independent experts in ClassLRU and calculates the full-cache size using the logical layer count. This produces incorrect upload estimates and cache-size/CPU-share recommendations: with two visits sharing two physical experts and two slots, replay predicts continuing uploads after warm-up even though the runtime retains both experts. Include ownership in the trace and update replay and slot limits accordingly, or explicitly disable deduplication for tuning runs until the simulator supports it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in b336a7e. A trace with shared layers is now written as MCT2: each layer of a group is recorded with its owner, the layer whose slots it shares. Traces without shared layers stay MCT1 and are byte-for-byte the same as before. scripts/moe-cache-tune.py reads both formats. It plans each layer in its owner's slots, advances the clock only on the owner's lookup (as the cache does), and caps the slots and the full-cache size at the distinct experts.

Checks:

  • tests/test-moe-cache-tune.py replays two synthetic traces with the same routing. With two layers sharing two experts (MCT2) there are no uploads after warm-up. With independent layers (MCT1) there are 2 x 2 uploads per token. The test fails on the previous tuner.
  • Real traces, Inkling-2-Mini UD-IQ1_S, 2500 MiB cache, -ub 4, 96 tokens: the replay predicts 7164.58 MiB uploaded with dedupe on and 21714.53 MiB with LLAMA_MOE_CACHE_DEDUPE=0, the same as the runtime counters in both cases. Read the old way (every layer independent), the dedupe-on trace would predict 21768.12 MiB and a full cache of 18731 MiB instead of 6277 MiB.
  • Runtime is unchanged: llama-perplexity wikitext-2 -c 512 --chunks 20 -ub 4 at 2500 MiB gives the same PPL (8.468848), KLD 0 against the pin set, and the same hit, miss and upload counts and decode text as 975c44a. test-llama-archs passes inkling2_loop (including the MoE cache row), deepseek2 and qwen3moe.

With looped layers sharing the slots of their owner, the cache trace still
listed every layer as independent, so scripts/moe-cache-tune.py replayed the
visits as separate experts and sized the full cache by the layer count. A
trace with shared layers is now MCT2: each layer of a group is written with
its owner. The tuner reads MCT1 and MCT2, plans each layer in its owner's
slots, advances the clock on the owner's lookup only (as the cache does) and
caps the slots at the distinct experts. Traces without shared layers are
unchanged (MCT1). tests/test-moe-cache-tune.py replays two synthetic traces.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: b336a7e65e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

erokhins pushed a commit to JetBrains-Hardware/llama.cpp that referenced this pull request Nov 24, 2026
abeloin added a commit to abeloin/llama.cpp-mix that referenced this pull request Nov 24, 2026
…nslothai#421, commit b336a7e)

Merge --no-ff du commit épinglé par unsloth (scripts/unsloth/pr-set.json).
Couche 2, liste A (banc/notes/couche2-unsloth-liste-2026-11-24.md côté
notes).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QBjnvFeJ4P7Jp71oC6pzWf

This branch has not been deployed

No deployments
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.

1 participant