Skip to content

llama : layer-major MoE cache prompts: one graph per batch, each host expert copied once - #517

Open
danielhanchen wants to merge 4 commits into
moe-offload-prefetch-cachefrom
pin-moe-layer-major
Open

danielhanchen wants to merge 4 commits into
moe-offload-prefetch-cachefrom
pin-moe-layer-major

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

The unslothai/llama.cpp prebuilt is an aged upstream b#### tag plus the pins listed in scripts/unsloth/pr-set.json, merged in order. This pin is stacked on #268 (host-weight prefetch and MoE cache): it builds on #268's MoE cache, expert copy callback and prefetch, so it branches from #268 (#268's head 6be5908e42f is merged in) and must come right after #268 in pr-set.json. Its own diff against #268's head is 7 files, +1109 / -12. It is dropped once upstream has an equivalent change.

The problem

With a MoE cache (--moe-cache-mib N) and experts in host memory (-ncmoe / --cpu-moe), every prompt ubatch copies every host expert it uses to the device. A batch of K ubatches therefore moves the spilled experts over PCIe K times, and long prompts on spilled loads are bound by that link.

The fix

  • decode() hands consecutive prompt ubatches of one batch (up to ceil(n_batch / n_ubatch), at most LLAMA_MOE_LAYER_MAJOR_UB_MAX = 16) to decode_layer_major. Each ubatch graph is built as usual, its inputs are set in a host arena, and the graphs are cut before every first use of a host weight. The pieces are merged so that piece s of every ubatch runs before piece s+1 of any (ggml_build_forward_order, compute flags kept). Each ubatch keeps its own graph, kernels and order of operations, so the outputs match the ubatch-by-ubatch order.
  • ggml-backend: ggml_backend_sched_set_reuse_weight_copies keeps every use of a host weight copy in the split that copied it, so each host expert is copied once per group. While a merged graph runs, expert copies hold every expert (prefetched whole; copied whole on the regular path if the scheduler did not prefetch).
  • Memory: ggml_backend_sched_set_alloc_limit refuses a merged graph that would grow a device compute buffer by more than LLAMA_MOE_LAYER_MAJOR_GROW_MIB (1024) or past the prefetch headroom; the group is then split in halves down to single ubatches. A refusal is scoped to its prompt. The scheduler node table is sized for a merged graph but the usual graphs use a table of their own size (ggml_backend_sched_set_hash_size_small), and the scheduler and graph allocator clear only the used entries of a large table. The group's host arena and graph results are freed after the group.
  • MoE cache seed: the last large ubatch seeds the cache from its own routing, as the ubatch-by-ubatch order does; in the merged graph each layer's seed is issued once its routing is computed (eval callback) from the shared expert copy.
  • Not used (falls back to the usual path): embeddings, layer-input or next-n extraction, backend samplers, layer input / state rows from another context, non-causal attention, looped layers, multi-sequence ubatches, ubatches below the prefetch threshold (256 tokens), batches holding fewer than two ubatches, a cache holding 98%+ of the host experts.
  • Default on whenever a MoE cache exists with experts in host memory and n_batch >= 2*n_ubatch. Kill switch LLAMA_MOE_LAYER_MAJOR=0 (or LLAMA_MOE_LAYER_MAJOR_NODRAFT=0); =1 forces it. Load line (info level): MoE cache: layer-major prompts, up to N ubatches of M tokens per graph; per group with LLAMA_MOE_LAYER_MAJOR_LOG=1: decode_layer_major: N ubatches ....
  • Without --moe-cache-mib nothing changes: the path is never entered and the scheduler keeps its usual table size.

This is the layer-major prompt path of our private fork, reduced to what #268 has: the fork's device seed, cache lending, hybrid gate, weight store, MTP / DFlash / drafter paths, released cache banks, server checkpoint changes and 16k batch rules are left out.

Evidence

All runs below use the pin-set tree, not the fork: upstream b13024 + the master pr-set.json with #268 at 6be5908e42f + this pin right after #268 + every open candidate pin (#485-#494, #496-#499, #501-#503) = 061a2a31af5 (HEAD). The local matrix was also run on the b13016 tree (#268 at 38c73159024, HEAD 71552e1fc4c) with the same results. BASE is the same tree with this pin's merge reverted (git revert -m 1), so BASE and HEAD differ only in this pin's 7 files. In both trees the two GGML_OP_COUNT asserts in ggml.c were set to 103 (what reconcile_op_count.py does in the nightly; the candidate set adds an op).

Check Result
llama_pinset.py sim b13016, master pr-set + this pin after #268 51 pins merge, pin_contract: all 51 intact, merge_checks: clean
llama_pinset.py sim b13016 and b13019, + all open candidates 67 pins merge, pin_contract: all 67 intact, merge_checks: clean
llama_pinset.py sim b13024, #268 at 6be5908e42f, + all open candidates this pin and #268 merge and are intact; merge_checks clean. #251 does not merge at b13024 (common/common.h, not touched by this pin), which is the only pin_contract failure
CPU build (-DGGML_CUDA=OFF, tests on) of HEAD builds; test-alloc passes
CUDA build (sm_100, tests on) of HEAD and BASE both build; test-backend-sched and test-alloc exit 0 on a B200 in both
test-backend-ops -b CUDA0 on HEAD (B200) MUL_MAT_ID 1322/1322, MUL_MAT 3197/3197, GET_ROWS 372/372, SET_ROWS 211/211, ADD 180/180, CPY 286/286, ARGSORT 101/101, TOP_K 550/550, SOFT_MAX 241/241 (this pin changes no op; the scheduler and graph allocator changes are covered by test-backend-sched / test-alloc)

Greedy text (48 tokens after a ~3.4k-token prompt, --temp 0 -c 8192 -b 2048 -ub 512 -ngl 99, B200, llama-completion), md5 of the generated text. "groups" counts the decode_layer_major: N ubatches lines, "load" the MoE cache: layer-major prompts line:

Model / flags BASE HEAD HEAD LLAMA_MOE_LAYER_MAJOR=0 HEAD engagement
Qwen3-30B-A3B UD-Q2_K_XL, -ncmoe 48 --moe-cache-mib 1024 4f938d87 4f938d87 4f938d87 (LLAMA_MOE_LAYER_MAJOR_NODRAFT=0: 4f938d87) load 1, groups 2 (4 + 3 ubatches)
same, -ub 256 4f938d87 4f938d87 groups 2 (8 + 5 ubatches)
granite-4.0-h-tiny Q4_K_M (hybrid MoE + Mamba2), -ncmoe 40 --moe-cache-mib 256 43dceeb8 43dceeb8 43dceeb8 load 1, groups 2
Qwen3-30B-A3B, -ncmoe 48 without a cache (feature off) 4f938d87 4f938d87 none
Qwen3-30B-A3B, full offload 4f938d87 4f938d87 none
Qwen3-0.6B BF16 (dense) b8be7d09 b8be7d09 none
Llama-3.2-1B-Instruct F16 (dense) 64b8a1e7 64b8a1e7 none
gemma-3-1b-it BF16 6e941b56 6e941b56 none
granite-4.0-h-tiny Q4_K_M, full offload 43dceeb8 43dceeb8 none

The merged graphs give the same text as the ubatch-by-ubatch order on both MoE families, including the recurrent (Mamba2) layers of granite, and the kill switch gives the BASE text. Models and flags without a MoE cache never enter the path.

Speed, RTX 5090 (Vast), pin-set trees built for sm_120a, Qwen4-35B-A3B UD-Q4_K_XL, llama-server -ngl 99 -ncmoe 20 --moe-cache-mib 3072 -b 2048 -ub 512, MTP off, prompt tok/s, median of 3 rotated rounds (BASE2 = BASE again for the A/A spread):

prompt BASE BASE2 HEAD HEAD LLAMA_MOE_LAYER_MAJOR=0
1926 tokens 1299.9 1307.7 1477.1 (+13.6%) 1308.1
7015 tokens 2361.9 2359.5 3139.1 (+32.9%) 2357.5
decode tok/s (after the 7015-token prompt) 151.3 151.5 151.4 151.4
  • Round-to-round spread is under 1% in every arm; the kill switch lands on BASE. The answer md5 is the same in all arms. Without --moe-cache-mib, BASE 847 vs HEAD 842 prompt tok/s, decode 27.9 in both, same md5.
  • Greedy md5 on the same box, BASE vs HEAD fully on the GPU, and BASE / HEAD / HEAD with the kill switch spilled with --moe-cache-mib 2048: equal on Qwen4-35B-A3B (-ncmoe 10 full, -ncmoe 20 spilled), Qwen3.8-Flash-Next UD-IQ1_S (--cpu-moe), Inkling-2-Mini UD-IQ1_S (full, and -ncmoe 99 spilled) and Qwen3.8-27B (full). Spilled HEAD runs log the load line once and 3-4 decode_layer_major groups.
  • The speed and four-model runs used the branch head before its last change (74a8d48cc02), which differed only in where the MoE cache seed of a merged graph is issued and in a whole-copy fallback for unprefetched copies; on the final code a second RTX 5090 run (Qwen4-35B-A3B spilled, -ncmoe 20 --moe-cache-mib 2048) gave the same greedy md5 for BASE, HEAD and HEAD with the kill switch, with the load line only in HEAD.

Not proven

  • Speed was measured on one RTX 5090 host only (Qwen4-35B-A3B); other GPUs, link widths and models were not timed. The B200 runs are shared local cards and prove correctness only.
  • The whole-copy branch in sched_copy_experts (a merged graph whose expert copy the scheduler did not prefetch) was not exercised: on every run here the scheduler prefetched the copies (141 (141 async) of 156 splits), and no environment setting drops the prefetch while keeping prompts eligible. It has no log line.
  • Only -np 1 style single-sequence prompts form groups (n_seqs_unq == 1); multi-sequence batches keep the usual path and were not timed.
  • HIP, Vulkan, Metal and SYCL were not built here. The change has no backend-specific code, but the scheduler and allocator changes run on every backend.
  • b13023 was not simmed. At b13024 the pin set needs common : add --moe-cache-mib auto to size the MoE expert cache from the fit #251 repinned (it no longer merges there, independent of this pin).
  • Decode was level on the 5090 run; the fork had measured -2.5% on a 3090, which was not rechecked here.

… one graph layer by layer, each host expert copied once

With a MoE cache (--moe-cache-mib) and experts in host memory, every prompt ubatch copies every host expert
it uses to the device, so a prompt of K ubatches moves the spilled experts K times. The graphs of up to
LLAMA_MOE_LAYER_MAJOR_UB_MAX consecutive prompt ubatches of one batch are now built as usual and merged
into one graph, layer by layer: piece s of every ubatch runs before piece s+1 of any, and a host weight is
copied once for the group (ggml_backend_sched_set_reuse_weight_copies). Each ubatch keeps its own graph,
inputs and kernels, so the outputs are the same as ubatch by ubatch.

On by default where a batch holds at least two ubatches and the cache does not hold every host expert;
LLAMA_MOE_LAYER_MAJOR=0 (or LLAMA_MOE_LAYER_MAJOR_NODRAFT=0) turns it off, =1 forces it.
A merged graph whose compute buffers would grow by more than LLAMA_MOE_LAYER_MAJOR_GROW_MIB (1024) or
leave less than the prefetch headroom free is split in halves; a refusal is scoped to its prompt.
The last large ubatch seeds the cache from its own routing, as the ubatch order does.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 6, 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-12-06T12:10:29.843922Z 2a096af 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 2a78b44ff5

ℹ️ 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-context.cpp
Comment on lines +4170 to +4172
if (lctx->lm_merged_active && !std::none_of(lctx->backends.begin(), lctx->backends.end(),
[backend](const ggml_backend_ptr & b) { return b.get() == backend; })) {
ggml_backend_tensor_set_async(backend, dst, src->data, 0, ggml_nbytes(src));

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 Preserve cache-aware uploads for merged expert copies

When host-weight prefetch is disabled or unavailable, this early return bypasses both moe_cache->copy_experts() and moe_cache->upload_experts() in the existing copy path. Consequently, every merged group uploads the entire expert tensor from its host mapping, including experts already cached on the device, and ignores the direct-I/O reader when enabled. With a warm cache holding 90% of the experts and a two-ubatch group, this can upload roughly five times as much data as the previous cache-aware path. Set the staged-expert mask to all experts but retain the existing cache-aware copy/upload planning instead of uploading the whole host tensor directly.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in 2a096af: the whole-copy branch only runs where the scheduler does not prefetch (backends it does not cover). In auto mode the first such group now turns layer-major prompts off, so later prompts take the usual cache-aware path; LLAMA_MOE_LAYER_MAJOR=1 still forces it.

Comment thread src/llama-context.cpp
Comment on lines +3342 to +3343
if (b - a == 1) {
const ggml_status st = run(group[a].gf);

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 Restore singleton graph sources before retrying allocation

If memory pressure causes allocation of a singleton to fail after a merged group has been split, this branch returns without restoring the graph's original sources. ggml_backend_sched_alloc_graph() has already replaced cross-backend sources with tensors owned by the scheduler's context, and the outer allocation-failure fallback subsequently resets the scheduler and retries this same group[a].gf. That retry reinitializes the scheduler context while the graph still references its old copy tensors, so it can consume overwritten tensor metadata or lose the original host-weight sources instead of cleanly reporting allocation failure. Preserve and restore singleton sources on failure, as the merged-graph branch already does, or avoid retrying a singleton that has already failed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in 2a096af: a singleton that failed to allocate is no longer retried (its sources point at scheduler copies); the decode returns the allocation error instead.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 2a096afe48

ℹ️ 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".

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.

2 participants