Repository navigation
llama : layer-major MoE cache prompts: one graph per batch, each host expert copied once - #517
danielhanchen wants to merge 4 commits into
Conversation
… 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.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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)); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if (b - a == 1) { | ||
| const ggml_status st = run(group[a].gf); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…f when copies are not prefetched
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Summary
The unslothai/llama.cpp prebuilt is an aged upstream
b####tag plus the pins listed inscripts/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 head6be5908e42fis merged in) and must come right after #268 inpr-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 toceil(n_batch / n_ubatch), at mostLLAMA_MOE_LAYER_MAJOR_UB_MAX= 16) todecode_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_copieskeeps 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).ggml_backend_sched_set_alloc_limitrefuses a merged graph that would grow a device compute buffer by more thanLLAMA_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.n_batch >= 2*n_ubatch. Kill switchLLAMA_MOE_LAYER_MAJOR=0(orLLAMA_MOE_LAYER_MAJOR_NODRAFT=0);=1forces it. Load line (info level):MoE cache: layer-major prompts, up to N ubatches of M tokens per graph; per group withLLAMA_MOE_LAYER_MAJOR_LOG=1:decode_layer_major: N ubatches ....--moe-cache-mibnothing 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.jsonwith #268 at6be5908e42f+ 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 at38c73159024, HEAD71552e1fc4c) 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 twoGGML_OP_COUNTasserts inggml.cwere set to 103 (whatreconcile_op_count.pydoes in the nightly; the candidate set adds an op).llama_pinset.py simb13016, master pr-set + this pin after #268pin_contract: all 51 intact,merge_checks: cleanllama_pinset.py simb13016 and b13019, + all open candidatespin_contract: all 67 intact,merge_checks: cleanllama_pinset.py simb13024, #268 at6be5908e42f, + all open candidatesmerge_checksclean. #251 does not merge at b13024 (common/common.h, not touched by this pin), which is the onlypin_contractfailure-DGGML_CUDA=OFF, tests on) of HEADtest-allocpassestest-backend-schedandtest-allocexit 0 on a B200 in bothtest-backend-ops -b CUDA0on HEAD (B200)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 thedecode_layer_major: N ubatcheslines, "load" theMoE cache: layer-major promptsline:LLAMA_MOE_LAYER_MAJOR=0-ncmoe 48 --moe-cache-mib 10244f938d874f938d874f938d87(LLAMA_MOE_LAYER_MAJOR_NODRAFT=0:4f938d87)-ub 2564f938d874f938d87-ncmoe 40 --moe-cache-mib 25643dceeb843dceeb843dceeb8-ncmoe 48without a cache (feature off)4f938d874f938d874f938d874f938d87b8be7d09b8be7d0964b8a1e764b8a1e76e941b566e941b5643dceeb843dceeb8The 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):LLAMA_MOE_LAYER_MAJOR=0--moe-cache-mib, BASE 847 vs HEAD 842 prompt tok/s, decode 27.9 in both, same md5.--moe-cache-mib 2048: equal on Qwen4-35B-A3B (-ncmoe 10full,-ncmoe 20spilled), Qwen3.8-Flash-Next UD-IQ1_S (--cpu-moe), Inkling-2-Mini UD-IQ1_S (full, and-ncmoe 99spilled) and Qwen3.8-27B (full). Spilled HEAD runs log the load line once and 3-4decode_layer_majorgroups.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
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 156splits), and no environment setting drops the prefetch while keeping prompts eligible. It has no log line.-np 1style single-sequence prompts form groups (n_seqs_unq == 1); multi-sequence batches keep the usual path and were not timed.