Skip to content

Host-weight prefetch in the scheduler, faster MoE cache prompt and decode, cache seeding under llama-server - #268

Open
danielhanchen wants to merge 113 commits into
base/upstream-0df40737cfrom
moe-offload-prefetch-cache
Open

danielhanchen wants to merge 113 commits into
base/upstream-0df40737cfrom
moe-offload-prefetch-cache

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Faster MoE and dense inference when weights live in host memory (partial -ngl, -ot/--cpu-moe, --fit spill), and a faster --moe-cache-mib cache. Everything is generic across architectures and on by default, with kill switches.

The unslothai/llama.cpp prebuilts are upstream ggml-org/llama.cpp, an aged b#### release tag, plus a short list of pinned PRs merged on top. Some pins are our own PRs to ggml-org/llama.cpp, such as Inkling (ggml-org#25731) and DiffusionGemma (ggml-org#24423). The rest are small custom PRs on unslothai/llama.cpp, like this one. Each pin is upstream plus that one change and nothing else. The nightly merges them in order with plain git, and additive_merge.py may resolve a conflict only when both sides purely added lines at the same spot. We never carry a full fork of the code: when upstream takes a change, its pin is deleted.

Update 12-03 (2): no slower than upstream with weights in CPU RAM

Prompt processing with host weights was 15 to 30% slower than upstream at ub 512 on consumer and datacenter cards with the default mmap load (--cpu-moe, --n-cpu-moe, -ngl N). Fixed in 0e731e286d7 and 85ca63fd41f:

  • Cause: large ubatches copied every host expert whole, ahead of the routing. A prompt ubatch routes to far fewer experts than that (about 64% at ub 512 in the measured case), and where the host link is the bottleneck the extra bytes cost more than the overlap saves. The earlier RTX PRO 6000 numbers used pinned host weights (--load-mode none) on PCIe 5, where it paid off.
  • Fix: large ubatches copy only the routed experts by default, like upstream. GGML_SCHED_PREFETCH_EXPERTS=1 restores the whole-expert copy ahead. The prefetch of dense host weights (e.g. -ngl N) is unchanged.
  • Host memory: when the device lookup has to copy memory-mapped experts it could not map, it now releases their mapped pages, so they are no longer resident twice (a 255 MiB tensor: +255 MiB of RSS before, +0 MiB now).

Qwen4-35B-A3B UD-Q2_K_XL, llama-server -c 32768 -np 1 -fa on, default mmap load, one 8192-token prompt, 2 interleaved launches per arm, upstream twice (A/A). Prompt tok/s, median, % vs upstream:

GPU placement ub upstream before (2b88647) before, GGML_SCHED_PREFETCH=0 now
A100 40 GB --cpu-moe 512 262 183 (-30.1%) 263 (+0.1%) 262 (-0.2%)
2048 732 686 (-6.3%) 730 (-0.2%) 732 (-0.1%)
--n-cpu-moe 20 512 461 345 (-25.1%) 461 (+0.2%) 460 (-0.1%)
2048 1217 1183 (-2.8%) 1218 (+0.1%) 1216 (-0.1%)
RTX PRO 6000 --n-cpu-moe 20 512 2049 1740 (-15.1%) 2045 (-0.2%) 2050 (0.0%)
2048 4671 4993 (+6.9%) 4665 (-0.1%) 4660 (-0.2%)
L4 --cpu-moe 512 263 187 (-28.9%) 263 (0.0%)
2048 671 696 (+3.7%) 673 (+0.3%)
--n-cpu-moe 20 512 444 339 (-23.6%) 443 (-0.2%)
2048 1016 1065 (+4.8%) 1016 (0.0%)
T4 --cpu-moe 512 222 182 (-18.0%) 222 (-0.2%)
2048 519 613 (+18.0%) 517 (-0.4%)
--n-cpu-moe 20 512 332 296 (-10.8%) 333 (+0.3%)
2048 685 777 (+13.5%) 682 (-0.4%)

Upstream's two arms were within 0.4% of each other in every cell; on the L4 and T4 the first launch of each VM ran on a cold system and is left out of upstream's median (226 and 198 tok/s at ub 512). The L4 and T4 runs had no GGML_SCHED_PREFETCH=0 arm. The first 64 greedy tokens of every launch (prompt and next turn) are identical across all arms.

An external retest at 85ca63fd4 (RTX 3090 with weights in CPU RAM, RTX 6000 Ada with the whole model on the GPU) confirmed the earlier regressions fixed. The two items it raised, Qwen3.8 whole-model prefill 9% lower on one run and 2 of 4 greedy texts differing with the MoE cache under --fit on, did not reproduce on an A100 80 GB: whole-model prefill within 0.5% of upstream at ub 512 and 2048 with no prefetch engaged, and identical greedy text under --fit on (same placement) and with a fixed placement, with the card held at 24 GB free.

Worse / Same / Better (now vs upstream)

  • Worse: nothing measured. The ub 2048 gains of the whole-expert copy (RTX PRO 6000 +7%, L4 +4 to +5%, T4 +13 to +18%) now need GGML_SCHED_PREFETCH_EXPERTS=1; the same holds for the cache-mode 8k prompt gains at ub 4096 in the tables below, which were measured with it on.
  • Same: prompt and decode with --cpu-moe and --n-cpu-moe without the MoE cache (table above); the whole model on the GPU (--fit on on the A100: 3342 vs 3345 tok/s prompt at ub 512, 4298 vs 4305 at ub 2048, decode 91.2 vs 91.3).
  • Same: the whole model on the GPU on the RTX PRO 6000 and the L4 (-ngl 99, ub 512): prompt 7906 vs 7905 and 2187 vs 2185 tok/s, decode 167.8 vs 167.8 and 56.1 vs 56.0.
  • Better: with the MoE cache (--n-cpu-moe 20 --moe-cache-mib 4096, ub 2048):
    • A100: prompt 3151 vs 1462 tok/s (+116%), decode 85.9 vs 61.7 (+39%), next-turn decode 89.3 vs 81.6 (+9%), peak RSS 12.1 vs 19.2 GiB.
    • RTX PRO 6000: prompt 8773 vs 5183 (+69%), decode 161.5 vs 136.2 (+19%), next-turn decode 165.3 vs 154.1 (+7%).
    • L4: prompt 2018 vs 1181 (+71%), decode 53.8 vs 43.6 (+23%), next-turn decode 54.6 vs 52.4 (+4%).
  • Better: -ngl 20 (dense host weights still prefetched, A100): prompt 349 vs 338 tok/s at ub 512 (+3.3%), 969 vs 927 at ub 2048 (+4.6%).

Update 12-03: merged upstream b12939

The branch now merges b12939 (0df40737c, the base the nightly picks) instead of b11577. Upstream rewrote the MoE cache in between, so the cache half of this PR was re-applied on top of upstream's version rather than carried:

  • Kept from upstream as is: the ClassLRU eviction (ggml-org#31233), misses computed on the CPU (--moe-cache-cpu-share, ggml-org#30966), quant scale banks (ggml-org#28898), and the cache graph code in llama_moe_cache::build_lookup / build_experts (ggml-org#32157).
  • Dropped, now upstream: the asynchronous upload of host split inputs (ggml-org#30685 does the same).
  • Device lookup (GGML_OP_MOE_CACHE_LOOKUP): the device state is converted to upstream's slot convention when it moves back to the host, and loaded into the ClassLRU there. It stays on the host lookup (upstream behaviour, logged once) when misses go to the CPU (cpu_share > 0), for layers with weight or input scales, with LLAMA_MOE_CACHE_TRACE, and for layers that read the same experts.
  • Seeding admits experts through upstream's eviction policy, and a seed now also fills the scale rows of the seeded slots.
  • Pinned together with common : add --moe-cache-mib auto to size the MoE expert cache from the fit #251 and llama : one MoE cache entry per expert weight for looped layers #421: this PR leaves their lines untouched and compiles against their changed add_extra_memory and plan() signatures. With common : add --moe-cache-mib auto to size the MoE expert cache from the fit #251 pinned, llama-fit-params prints the fitted --moe-cache-mib (this PR no longer edits that line).

What changes

1. Host-weight prefetch in ggml_backend_sched (ggml/src/ggml-backend.cpp)

  • Problem: weights kept in host memory are uploaded on the compute stream right before the split that uses them, so the GPU idles during every copy.
  • Copy queue: each GPU backend gets a copy-only instance on the same device. With the default depth of 2, split k+1 uploads while split k computes. A slot is reused only after the compute that read it records its retire event.
  • Staging arena: outside gallocr, sized for the largest pair of consecutive splits, added to the reserve size so --fit and the memory breakdown count it (Qwen3.8-Flash-Next: 1275 MiB).
  • MoE ubatches: host experts are copied only for the routed experts, once the routing is known (like upstream). GGML_SCHED_PREFETCH_EXPERTS=1 copies whole expert tensors of large ubatches (GGML_SCHED_PREFETCH_MIN_BATCH, default 256) ahead without the routing-ids sync, which only pays off on a fast host link with pinned weights.
  • Unchanged otherwise: splits that are not prefetched keep upstream's behaviour exactly. Excluded: user inputs (also through views), host weights a split writes, splits with SYNC copies, SYCL, and inputs upstream does not copy (nodes that are not computed).
  • Allocation failures: the copies are unbound in place and the allocation is retried without prefetch.
  • Switch: GGML_SCHED_PREFETCH=0.

2. MoE cache, prompt path (src/llama-moe-cache.cpp, ggml-cuda/copy-regions.cu)

  • Large ubatches fill the staged expert tensor with device-to-device copies for cached experts and host-to-device copies for misses, batched into one cudaMemcpyBatchAsync plus a copy-regions kernel per expert tensor. GGML_CUDA_COPY_QUEUE_KERNEL=0/1 overrides the copy-queue choice (kernel except on compute capability 10.x).

3. MoE cache, decode path (GGML_OP_MOE_CACHE_LOOKUP, ggml-cuda/moe-cache.cu)

  • The slot map and lookup are on the device with CLOCK eviction, so routing is never read back per layer. Misses are read from the mapped pinned host copy.
  • LLAMA_MOE_CACHE_DEVICE=0 falls back to the host lookup.

4. Cache seeding at the end of a prompt

  • The experts the prompt routed to are admitted from copies already on the device, so decode starts warm, also under llama-server (checkpoint tail as a separate small batch).
  • LLAMA_MOE_CACHE_SEED=0 disables it. LLAMA_MOE_CACHE_SEED_CHECK=1 verifies every seeded slot byte for byte.

The four new files carry the Unsloth AGPL-3.0 SPDX header. Upstream files keep their license.

Results on b12939 (RTX PRO 6000 Blackwell, Colab G4)

  • Setup: llama-server, greedy, ctx 12288, -fa on, --load-mode none. Cells: chat = 2048 prompt + 512 generated, 8k = 8192 prompt + 128 generated. Cache mode is -ngl 99 --cpu-moe --fit off --moe-cache-mib <cap - margin>, with a GPU ballast holding the card at the cap.
  • Method: 3 interleaved fresh-process launches per arm, upstream b12939 run twice (A/A). Medians, % vs upstream.
model, cap ub cell prompt vs upstream decode vs upstream
Qwen3.8-Flash-Next UD-IQ4_XS, 49.5 GiB 2048 chat +66.8 to +67.4% +11.5 to +12.1%
2048 8k +57.9 to +59.4% +0.7 to +13.2%
4096 chat +64.7 to +67.0% +12.2 to +12.5%
4096 8k +44.4 to +45.0% +6.8 to +11.3%
Qwen3.8-Flash-Next UD-IQ4_XS, 35.5 GiB 2048 chat / 8k +25.6% / +27.9% +6.6% / +2.3%
4096 chat / 8k +23.0% / +26.2% +5.9% / +2.1%
Qwen3.6-35B-A3B UD-Q4_K_XL, 12 GiB 2048 chat / 8k +17.3% / +36.7% +6.1% / +9.3%
4096 chat / 8k +10.7% / +25.0% +0.9% / +3.0%
Qwen3.6-35B-A3B UD-Q4_K_XL, 16 GiB 2048 chat / 8k +35.6% / +45.0% +11.1% / +7.1%
4096 chat / 8k +27.1% / +31.9% +9.5% / +8.8%

Ranges are over two separate VMs. Upstream's own A/A spread was under 1% in most cells and up to 6% for Flash-Next 8k decode.

  • A100 40 GB (Qwen3.6-35B-A3B, same method):

    • cap 16 GiB: chat prompt +18.6 to +28.4%, 8k prompt -1.8 to +5.0%, decode +6.9 to +10.4%;
    • cap 12 GiB: ub 2048 is +2.1 to +6.3% prompt and +2.7 to +14.3% decode; ub 4096 chat is -0.4% prompt and -1.8% decode, ub 4096 8k is +2.2% / +4.9%.

    The prefetch arms equal the GGML_SCHED_PREFETCH=0 arms on this card, so the A100 differences come from the cache paths.

  • Split under --fit on (Qwen3.6-35B-A3B, 12 GiB, ub 2048): prompt +14.0% (chat) and +13.7% (8k), decode -0.1% and -0.5% (inside upstream's spread). With GGML_SCHED_PREFETCH=0 both match upstream.

  • Cache mode with GGML_SCHED_PREFETCH=0: the chat prompt gains are unchanged; the 8k prompt gain is lower at ub 4096 and at the smaller caps (Flash-Next 49.5 GiB ub 4096: +24% instead of +45%); decode is +2 to +14%.

  • Known cost, 8k decode with prefetch on:

    • Decode after a multi-ubatch prompt is 0.5 to 7% below the same build with GGML_SCHED_PREFETCH=0: 94.2 vs 101.5 tok/s on one VM and 98.9 vs 100.0 on another, for Flash-Next at ub 2048. It stays above upstream.
    • Cause: with prefetch on, the last large ubatch seeds the cache from the routing of the ubatch before it, so its own copies do not wait for its routing.
    • Seeding from its own routing was tried and reverted: it cost 14% of the 8k prompt at ub 4096 (3985 vs 4630 tok/s) for no measurable decode gain.
  • LLAMA_MOE_CACHE_SEED=0 with the device lookup is 2.5 to 4% below upstream's decode. Seeding is what makes the device lookup pay off, so keep it on.

Correctness

  • Logits and text on GPU (48 runs each on an L4 at this head and on an RTX PRO 6000 one commit earlier): Qwen3.6-35B-A3B in 12 configurations:

    • --cpu-moe without the cache, --cpu-moe with a 4 GiB cache, and -ngl 20;
    • ub 512 and 2048;
    • --load-mode none and mmap.

    In every run, the llama-perplexity logits and the 128-token greedy text after a 2k prompt are byte-identical to upstream b12939, with the features on and with each of GGML_SCHED_PREFETCH=0, LLAMA_MOE_CACHE_DEVICE=0 and LLAMA_MOE_CACHE_SEED=0. The prefetch line is logged in every Host-weight prefetch in the scheduler, faster MoE cache prompt and decode, cache seeding under llama-server #268 run with prefetch on, and the device lookup in every cache run.

  • Seed check: 0 mismatches over 21300 verified expert copies (L4) and 21294 (RTX PRO 6000).

  • Every timing launch above: the first 64 greedy tokens of every cell equal upstream's (Flash-Next and Qwen3.6, cache and --fit modes, all arms).

  • CPU: Qwen3-0.6B perplexity logits and greedy text are byte-identical to upstream at ub 512 and 2048, with every switch. test-llama-archs passes 162/162, as do test-alloc and test-moe-cache-*.

  • Pin set: a window sim of b12942 to b12957 with the 46 current pins and this PR last is green: every pin merges clean or additive, and pin_contract reports all 47 intact. Pinned next to Inkling's banded FA op, the op-count asserts need unsloth: reconcile ggml op-count asserts after the pin merges #274 (one more ggml op each). With it, the merged tree builds.

Not covered

  • Flash-Next on the A100 (it needs the 80 GB card), and Flash-Next with --fit on (split) on this base. The B200 numbers from the b11577 version of this PR were not re-measured.
  • Vulkan and Metal take the existing path; SYCL is excluded. ROCm, MUSA, multi-GPU and Windows were not run.
  • The device-to-host state handoff approximates the eviction order (CLOCK reference bits plus last use, not true frequency); this only changes which experts stay cached, not results.
  • Follow-ups: seed asynchronously from the last ubatch's router output, which would remove the 8k decode cost without the prompt cost.

Base is upstream b12939 0df40737c. Like every pin in scripts/unsloth/pr-set.json, this is merged onto the aged upstream b#### tag for the prebuilt and dropped once upstream has the equivalent.

…for large ubatches, seed the cache from the end of a prompt
…sched

Weights in host buffers that are used by GPU splits were uploaded on the
compute stream after a full synchronization, so the transfers never
overlapped compute.

The scheduler now binds the weight copies of each such split to one of
`depth` staging slots of a device arena it owns (outside of the graph
allocator, so the copies never alias other tensors) and uploads them on a
second backend instance of the same device, up to depth - 1 splits ahead.
A copy into a slot waits for the event recorded after the last compute
that read the slot, and the compute waits for the event recorded after
the copy. Slot addresses are fixed per graph, so graph reuse and CUDA
graphs are unaffected.

- enabled for CUDA, ROCm and MUSA devices with async copies and events,
  GGML_SCHED_PREFETCH=0 disables it, =2 allows any backend with the caps
- GGML_SCHED_PREFETCH_DEPTH (default 2) staging slots per backend
- with a copy callback, MUL_MAT_ID weights of batches smaller than
  GGML_SCHED_PREFETCH_MIN_BATCH (default 256) keep the callback, which
  uploads only the routed experts (into the slot)
- copies read by more than one split stay with the graph allocator
- disabled with pipeline parallelism (n_copies > 1)
- the staging memory is included in ggml_backend_sched_reserve_size and
  ggml_backend_sched_get_buffer_size
- new ggml_backend_sched_set_prefetch_callback to exclude host tensors
  that change between graph computations; llama uses it to exclude the
  MoE cache slot maps
With the MoE cache on, the scheduler prefetch uploaded every host expert
tensor whole from host memory for large ubatches, so the experts already
held in the cache were sent over PCIe again.

The prefetch callback now returns a mode per weight (NONE, SYNC, ASYNC),
and ASYNC copies go through the copy callback on the copy queue backend.
For experts, llama copies the cached ones device to device from the cache
banks and uploads only the others, issued ahead of the split like any
prefetch. Its ids-free predicate (sched_copy_all_experts) decides both the
mode and the copy, so an ASYNC copy never reads the routing ids.

- the ubatch that seeds the MoE cache (outputs, > 32 tokens) needs the
  routing counts, so its cached experts are SYNC: they stay in the staging
  slot and are filled at the split after the ids readback, as before
- GGML_SCHED_PREFETCH_MIN_BATCH moved to llama (it is a property of the
  copy callback); GGML_SCHED_PREFETCH=0 restores the ids-based copy
- the copy queue waits for an event recorded on the compute backend at
  the start of each graph, so copies that read device memory (cache banks)
  are ordered after the writes of earlier graphs
…r large batches, issue them before the uploads
The MoE cache resolved each layer of a decode step on the host: the slot map
was a host weight, so every MoE layer started a new split (a full sync in
ggml_backend_sched_copy_input), then the copy callback read the routing ids
back (a second sync), planned the LRU and uploaded the misses from pageable
memory. Decode ran at ~11 ms/token whatever the hit rate.

Add GGML_OP_MOE_CACHE_LOOKUP (CUDA only): one warp looks up the slots of the
selected experts in a device slot map, gives the misses a slot with a CLOCK
sweep (hits and this lookup's slots are never evicted) and a second kernel
copies the missing experts from mapped pinned host memory into their slots.
The matmuls read the banks with the returned slots as before, so the results
are bit-identical to the host lookup. No host round trip, no split per layer:
one CUDA graph per token.

- llama_moe_cache::lookup builds the op for ubatches of <= 32 tokens (decided
  by the ubatch size, so the output-only last layer agrees with the others);
  prepare() moves the state between the host LRU (still used by large
  batches) and the device when the path changes.
- host experts are mapped with cudaHostRegister(Mapped|ReadOnly) or used as is
  if already pinned; pageable (HMM) access is refused, it is ~10x slower.
  mmap'ed files usually cannot be pinned, so --moe-cache-mib loads the model
  without mmap when the load mode is auto.
- LLAMA_MOE_CACHE_DEVICE=0 restores the host lookup; backends without the op
  or failed mapping fall back to it.
With --cpu-moe the per-expert scales (gemma4 ffn_down_exps.scale) and biases
of the cached layers stay in host memory, so their get_rows ran on the CPU
and every MoE layer of a decode step went back to the host. The cache now
keeps a device copy of these small tensors and the lookup path of small
batches reads them, bit-identical values, no host round trip.
- the device lookup is decided per cache group (one per device and expert
  layout): a group whose backend lacks the op or the ggml_backend_host_map
  proc keeps the host lookups, the others use the device, so mixed and
  multi-GPU setups work
- the host mapping is exposed as the generic ggml_backend_host_map /
  ggml_backend_host_unmap procs; the CUDA implementation builds for CUDA,
  HIP and MUSA (vendor aliases added); pinned memory is detected with the
  pointer attributes, pageable memory is registered, never read through HMM
- device copies of per-expert scales and biases have no size limit
- --moe-cache-mib with load mode auto loads without mmap only if the model
  files take at most 80% of system memory, larger models keep mmap and the
  host lookups
…che D2D and uploads) in the stats

With the scheduler prefetch the expert fill runs on the copy queue, so the number of copy calls per ubatch is the cost to watch: the 4 MiB minimum cache run keeps it near one upload per gap instead of one per scattered expert.
… expert tensor

After seeding, the cached experts sit in scattered slots, so using them for a
large ubatch needs one device copy per cached run plus one upload per gap
(thousands of copies per ubatch). The 4 MiB minimum run avoids that by
uploading almost everything from host again, so the cache did not cut PCIe
bytes on the prompt path.

New ggml_backend_tensor_copy_regions_async: queues many (src, offset, dst,
offset, size) copies as one call. CUDA implements it with cudaMemcpyBatchAsync
(CUDA >= 12.8) for device sources of the same device and pinned host sources,
in stream order; it returns false (nothing copied) otherwise (HIP, MUSA,
older CUDA, pageable host memory, GGML_CUDA_COPY_BATCH=0), and the callers
keep the previous per-copy path.

llama issues the fill of each expert tensor (every cached run from the
cache banks plus the uploads of the rest) as one batch, on the backend the
scheduler passes (the copy queue when prefetched), and the seed fills of the
cache slots as one batch per tensor. The stats report copies and batched
calls per ubatch.
Conflict in src/llama-moe-cache.cpp: keep the large-batch helpers of the
prompt path (count_batch, count_upload, seed, seed_end) next to the device
lookup, and log_stats becomes non-const (it reads the device counters).

seed() admits experts through moe_cache_lru::plan, which bumps lru.gen, so
the next device lookup uploads the seeded host state; the seed_end rollback
now bumps lru.gen too.
- user inputs reached through views (view_src chain with
  GGML_TENSOR_FLAG_INPUT) are never prefetched: they may be overwritten as
  soon as the computation is queued (B200 probe: stale result 99 vs 1)
- host weights written by the graph itself (a node or a view of one) are
  never prefetched: the copy must follow the writer (probe: stale 720)
- a computation that stops on an error drains the copy queues before
  returning, so a copy issued ahead cannot write a slot after it is reused
- if the graph allocator fails after the staging arena was allocated, the
  arena is freed, prefetch is disabled on that backend and the allocation
  is retried without it (reserve and alloc_graph)
- only splits whose copies are all issued ahead get a slot; splits with
  SYNC copies use the graph allocator, as without prefetch, so no staging
  memory or copy queue is created for them
- a copy or prefetch callback set after the graph was allocated: its bound
  copies use the regular path (current callbacks) until the next
  allocation binds again
- SYCL always keeps the regular path (pinned staging workaround for mmap,
  per-tensor extras that the arena would accumulate)
- ggml_backend_host_map (CUDA) reference counts the buffers it registers,
  so a second context mapping the same buffer holds its own reference and
  the first context's unmap no longer unregisters memory still in use
- registration tries read-only first and falls back to a read-write
  registration (B200 reports HostRegisterReadOnlySupported=0, so pageable
  buffers were never mapped)
- memory measurement (no_alloc) enables the device lookup only for groups
  whose device has the host_map procs and supports the op, like the real
  initialization
- the slot sizing counts the device copies of the per-expert scales and
  biases and the lookup map/state inside the cache budget
- get_slot_map takes the ubatch size: only ubatches that use the device
  lookup skip the host slot map, so the output-only last layer of a large
  ubatch reads the cache again as on master (first-token logits now match
  master byte for byte)
- copies from the cache and seeding skip a group whose device state is
  newer than the host LRU (e.g. a warmup ubatch of 32 tokens that did not
  use the device lookup), instead of reading stale slots
- lookup kernel: 32-bit epoch wrap clears the pins, out-of-range ids read
  expert 0; ggml_moe_cache_lookup asserts that the distinct experts fit in
  the slots
- ggml-rpc.h: GGML_OP_COUNT 102, RPC_PROTO_PATCH_VERSION 1
- load mode auto: the RAM check uses the available system memory
  (MemAvailable on Linux, free + inactive + purgeable pages on macOS), the
  CPU backend reports free = total there
…ough views or host weights written by the graph

A view of a GGML_TENSOR_FLAG_INPUT tensor was prefetched on the copy queue,
so an overwrite by the caller after graph_compute_async returned changed the
result. A host weight written by a node of the graph (e.g. a ggml_cpy into a
weight view) was uploaded before the split that writes it ran.

The candidate check now walks the view_src chain for the input flag and
skips host weights that any non-empty node writes, directly or through a
view, so these copies keep the regular path after their producer.
…th SYNC copies

A split whose copies need results of earlier splits (SYNC, e.g. the routed
experts of a small MoE batch) still took a staging slot: depth slots sized
for it and a copy queue that never issued anything. Such splits are no
longer bound, their copies are allocated by the graph allocator as without
prefetch, so the slots are sized only for the splits whose copies are issued
ahead and the copy queue is created only if there is one.
…ging memory

If the staging arena was allocated but the graph allocator then failed,
reserve and alloc_graph returned false while still holding the arena, unlike
a failed arena allocation, which falls back to the regular path. The copies
are now unbound, the arenas freed and prefetch disabled, and the graph
allocation is retried once, on both the reserve and the alloc_graph paths.
…on stops early

compute_splits returned on a compute error or abort with copies already
issued up to depth - 1 splits ahead. They kept writing their slots after
the scheduler was reset and could land after a later write to the same slot,
or read host memory after the caller regained control. The copy queues are
now synchronized before returning the error.
…after the graph was allocated

The copies to prefetch are selected when the graph is allocated, so a copy or
prefetch callback set afterwards was ignored for that graph (e.g. a prefetch
callback returning NONE for a weight the caller overwrites). When a callback
changes, the bound copies of the allocated graph are made by the regular
path with the current callbacks, into their slots, until the next
allocation selects them again.
…he arena on each bind

SYCL could be opted in with GGML_SCHED_PREFETCH=2, but the async copies skip
the pinned staging that its set_tensor uses for weights in mmap'ed memory,
so SYCL now always keeps the regular path. The staging arena is also reset
before the copies of a new graph are bound, as the graph allocator does with
its buffers, so per-tensor state set by init_tensor does not accumulate.
…tive splits

With depth 2 the arena held two slots of the largest prefetched split, but
only two consecutive splits are live at once (the copy of split k + 1
overlaps the compute of split k). Even ordinals are now placed at the start
of the arena and odd ordinals end at its end, so the arena only needs the
largest sum of two consecutive splits. E.g. a MoE layer with 425 MiB
gate/up and an 850 MiB Q8_0 down tensor needs 1275 MiB instead of 1700 MiB,
with the same overlap. Other depths keep uniform slots. The log line reports
the staging size and the largest split.
…nce per split

Without pipeline parallelism each user input of a split was copied with a
backend synchronize plus a synchronous tensor_set (2 host syncs per input).
Queue the host-resident inputs as async uploads on the split backend and
synchronize once after all of them, before host weights are copied.
For a hybrid MoE model with ~30 graph inputs this drops decode from 82 to 9
stream synchronizations per token.
… batch

ggml_backend_tensor_copy_regions_async put the device-to-device copies of
a MoE cache fill (runs of cached experts) in the same cudaMemcpyBatchAsync
as the uploads, so they took copy-engine time from the uploads: nsys of a
warm 9.3k prompt (gemma-4-26B-A4B, 4000 MiB cache) shows 65.8 GB D2D using
the copy engines for 658 ms next to 2.16 s of uploads.

The device copies of a call now run as one kernel (variable-size regions,
pointers in the kernel parameters, 128 regions per launch, vector width
from the common alignment, at most one 256-thread CTA per SM), issued
before the batched uploads on the same stream; the regions are disjoint,
so their order does not matter. GGML_CUDA_COPY_REGIONS_KERNEL=0 puts them
back in the batch.

Host memory registered through ggml_backend_host_map (reference counted)
also counts as pinned for the uploads, not only CUDA host buffers.
…uted experts, small ubatches are not prefetched

- the copy of all experts without reading the ids is only for the copies the scheduler issues ahead on its copy
  queue; on the regular path (GGML_SCHED_PREFETCH=0, a staging arena that did not fit, or a split that is not
  prefetched) the ids are read and only the routed experts are copied, as on master. Copying every expert of a
  2048-token ubatch made prompt processing ~7% slower with prefetch off (since the moe-cache prompt path).
- ubatches smaller than GGML_SCHED_PREFETCH_MIN_BATCH (default 256) bind no host weights to the staging arena,
  so generation does no staging, event or copy queue work.
- the copy queues are synchronized only when work was queued on them since the last synchronization.
The prefetch copy queue of the scheduler is a second CUDA backend instance that never computes a graph. Its batched
copies now keep the device-to-device regions on the copy engines (cudaMemcpyBatchAsync) instead of the SM kernel.
With the kernel there, generation after a prefetched prompt was ~5% slower (Qwen3.8-Flash-Next IQ4_XS, MoE cache
42688 MiB, ub 2048, B200: 71.9 -> 76.1 tok/s, equal to GGML_SCHED_PREFETCH=0), at the same prompt speed. Compute
instances (the regular copy path) keep the kernel.
…its it

The prompt seed only ran on a large ubatch with outputs. llama-server runs the last
tokens of a prompt as a separate small batch for recurrent and SWA models (context
checkpoints), so the ubatch with outputs had <= 32 tokens and the cache was never
seeded there.

The last large ubatch of each batch now seeds the cache, with or without outputs.
The seed still fills the slots from the experts staged for that ubatch (no extra
uploads). To keep multi-batch prompts from waiting for the ids of every batch, the
routing of each large ubatch of a cached layer is kept as a graph output and read
before the next graph: a later batch of the same prompt seeds from it while its
copies of all of the experts stay asynchronous. Only a batch with outputs, or the
first large batch of a prompt, reads its own ids first.

The stored routing is dropped at any ubatch with outputs, a multi-sequence ubatch,
a position jump (context switch, checkpoint restore) or a failed ubatch, and at
every graph build. The graph is rebuilt when the seed mode changes, as the
scheduler plans the expert copies with it. LLAMA_MOE_CACHE_SEED=0 disables the seed.
The seed of a prompt end copies slots from the experts staged on the device for its ubatch. With the scheduler
prefetch fix, the regular path (prefetch off, a ubatch below GGML_SCHED_PREFETCH_MIN_BATCH, a split that is not
prefetched) stages only the routed experts, so:
- a seed uses the stored routing of an earlier ubatch only when the copies staged every expert (prefetched), otherwise
  the ids of the ubatch itself;
- seed() takes the staged experts: the plan admits only those, and an expert tensor of the layer that did not stage a
  planned expert does not fill (the layer is dropped by seed_end);
- a last large ubatch below the prefetch threshold seeds from its own ids, the routing is not recorded with
  GGML_SCHED_PREFETCH=0 (no extra sync);
- LLAMA_MOE_CACHE_SEED_CHECK=1 (debug) compares the seeded slots with the host experts after each seeding ubatch.
…unless the device has HBM

90a34bc moved the device copies of the prefetch copy queue to the copy engines, which helped generation on a B200
(~5%) at the same prompt speed. On an RTX PRO 6000 (GDDR7, sm_120) the copy engines made a prefetched 8k prompt with
the MoE cache 16% (ub 2048) / 9% (ub 4096) slower, with no generation change (2k: 90.3 vs 90.2 tok/s). The copy queue
now uses the kernel unless the memory bus is at least 2048 bits wide (HBM); GGML_CUDA_COPY_QUEUE_KERNEL=0/1 overrides.
danielhanchen added a commit that referenced this pull request Dec 4, 2026
 on master (#474)

* pr-set : pin #268 (host-weight prefetch and MoE cache paths), needs #274 on master

* pr-set : repin #268 for the offload prefill fix
LeoBorcherding added a commit to LeoBorcherding/llama.cpp that referenced this pull request Dec 4, 2026
…nother address with cudaMemcpyAsync

On WSL2 (cudaDevAttrCanUseHostPointerForRegisteredMem = 0) the device address of memory registered with
cudaHostRegister differs from its host address. cudaMemcpyBatchAsync then reads the host address and faults with
an illegal memory access, while cudaMemcpyAsync translates it. This crashed the first large ubatch with the MoE
cache over memory-mapped host experts (--load-mode mmap), which the device lookup registers. Such regions are now
copied one by one with cudaMemcpyAsync on the same stream; pinned memory the device reads at its host address
(CUDA host buffers, registered memory on Linux) stays in the batch.
@oobabooga

oobabooga commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

I retested this PR at 1d1e4f549 against what master ships, and pushed one fix, 3ff4d7c92.

The tables below compare three builds:

  • master: upstream b12977 plus every pin in master's pr-set.json except this PR, merged the way the nightly does.
  • before: the same tree plus this PR at 1d1e4f549.
  • after: the same tree plus this PR at 3ff4d7c92.

The prompt and decode columns are tok/s over the 4-turn agentic scenario. Bold marks the best value in each row: highest tok/s, lowest VRAM, load time and RSS.

Summary

  • MoE cache (--moe-cache-mib): much faster than master, with agent prompt +53 to +83% and decode +6 to +26%. The fix does not change this.
  • Without the cache: prompt and decode speed are the same as master.
  • Before the fix: every MoE load with experts spilled to the CPU used 160 to 520 MiB more VRAM than master, for no speed gain. After the fix, VRAM is back to master's level.
  • Still worse: loads with the MoE cache are slower, and the host experts become page-locked RAM. On gpt-oss-120b this costs a lot.

The fix: VRAM with experts in host memory

With experts in host memory, a large ubatch copies only the routed experts, after the routing is known. Master does the same; these are SYNC copies. Whenever a backend also had ASYNC (prefetched) splits, ggml_backend_sched_prefetch_bind put the SYNC copies in the staging arena too, sized for two consecutive splits. --fit does not count that arena.

3ff4d7c92 keeps staging slots only for ASYNC splits and leaves SYNC copies in the graph allocator. A graph with only SYNC copies reuses an existing arena only if they fit in it.

Qwen4-35B-A3B with --fit. Each cell is agent prompt / decode, then peak VRAM in MiB:

setup master before after
UD-Q2_K_XL, 12 GB card, ub 512 1111 / 69.0, 11010 1116 / 69.0, 11165 1118 / 69.2, 11005
UD-Q2_K_XL, 12 GB card, ub 2048 2362 / 66.8, 11112 2346 / 66.8, 11340 2367 / 66.5, 11119
UD-Q4_K_XL, RTX 3090, ub 512 1658 / 97.0, 23159 1662 / 98.5, 23401 1657 / 97.9, 23163
UD-Q4_K_XL, RTX 3090, ub 2048 2358 / 92.4, 23241 2357 / 93.3, 23760 2363 / 93.3, 23245
UD-Q4_K_XL, RTX 3090, -np 4 --kv-unified -ub 2048 + MTP 1195 / 94.8, 23447 1195 / 95.6, 23623 1195 / 96.1, 23447

Supporting checks:

  • In the first row, the staging arena is 234 MiB before the fix and 2.7 MiB after.
  • 1d1e4f549 with GGML_SCHED_PREFETCH=0 gives the same speed as with prefetch on (2364 vs 2366 tok/s at ub 2048), so that VRAM bought nothing.
  • test-alloc (38/38) and the test-moe-cache-* tests pass.
  • llama-perplexity gives PPL 2.3101 on all three builds, with both --n-cpu-moe 20 and --cpu-moe --moe-cache-mib 4096.

MoE cache: faster than master

Each cell is agent prompt / decode:

model, setup master before after
Qwen4 UD-Q2_K_XL, 12 GB card, --moe-cache-mib auto 1064 / 105.6 1604 / 112.7 1625 / 112.3
Qwen4 UD-Q4_K_XL, 12 GB card, --moe-cache-mib auto 479 / 65.2 779 / 75.5 799 / 75.3
same, 32 GB RAM, cold page cache 471 / 64.2 743 / 73.0 752 / 74.0
same, 24 GB RAM, cold page cache 420 / 58.3 749 / 73.1 770 / 73.2
Qwen3.6-35B-A3B UD-Q4_K_XL, 12 GB card, --cpu-moe --moe-cache-mib 6144 507 / 69.6 842 / 85.9 843 / 85.6
gpt-oss-120b UD-Q4_K_XL, 48 GB card, --moe-cache-mib auto, 1 run 488 / 76.2 862 / 83.3 * 853 / 81.9

* 1d1e4f549 on gpt-oss-120b: 3 runs with another CPU-heavy job on the machine.

  • Short chat prompts gain more than the agentic numbers above:
    • Qwen4 Q4_K_XL, 12 GB card: chat prompt 113 -> 214 tok/s.
    • gpt-oss-120b: chat decode 62.1 -> 106.1 tok/s.
  • GGML_SCHED_PREFETCH=0 keeps the same gains, so they come from the cache paths.
  • Under the 24 GB RAM limit, master's memory-mapped experts are evicted and re-read, while the PR's copied experts stay resident.

The prefetch itself helps a dense model with spare VRAM. Qwen3.6-27B, -ngl 40 --fit off, 25 of 65 layers on the CPU, 48 GB card:

  • agent prompt: 629 on master, 685 before, 669 after; 599 with GGML_SCHED_PREFETCH=0;
  • decode: 4.8 / 4.6 / 4.9.

Same as master

Each cell is agent prompt / decode, then peak VRAM in MiB. "-" means the build was not run in that cell. Launch-to-launch spread is 1 to 5%; Qwen3.8 at 48 GB is ±9%.

model, setup master before after
Qwen4 UD-Q2_K_XL, 48 GB, whole model on the GPU 5009 / 135.6, 16636 5011 / 140.6, 16396 -
Qwen4 UD-Q2_K_XL, RTX 3090, whole model on the GPU 3115 / 112.5, 16236 3108 / 114.3, 16128 -
Qwen4 UD-Q2_K_XL, 16 GB --fit 3189 / 107.8, 15056 3210 / 108.8, 15275 -
Qwen4 UD-Q2_K_XL, 8 GB --fit 636 / 47.0, 7027 620 / 46.3, 6870 -
Qwen4 UD-Q2_K_XL, 8 GB --cpu-moe 483 / 38.8, 3846 487 / 38.6, 3760 -
Qwen4 UD-Q2_K_XL, 16 GB, q8_0 KV 3748 / 115.5, 15062 3728 / 117.0, 15274 -
Qwen4 UD-Q2_K_XL, 12 GB, Studio flags + MTP 1899 / 73.6, 11314 1936 / 75.4, 11669 -
Qwen4 UD-Q4_K_XL, 48 GB, whole model on the GPU 4996 / 125.9, 24332 5014 / 127.9, 24378 -
Qwen4 UD-Q4_K_XL, 16 GB --fit 643 / 52.7, 14968 661 / 54.7, 15474 685 / 55.5, 15002
Qwen4 UD-Q4_K_XL, 16 GB, q8_0 KV 696 / 56.2, 15164 694 / 56.4, 15170 710 / 55.2, 15017
Qwen3.6-27B (dense), 48 GB, whole model on the GPU 1599 / 42.0, 19038 1690 / 42.2, 19029 -
Qwen3.6-27B (dense), 16 GB --fit 803 / 6.2, 14898 812 / 5.9, 15289 831 / 5.9, 14886
Qwen3.8-Flash-Next UD-IQ1_S, 48 GB --fit 2120 / 94.5, 37382 2240 / 95.5, 37382 2314 / 95.4, 37382
Qwen3.8-Flash-Next UD-IQ1_S, 48 GB --fit --moe-cache-mib auto 2439 / 96.0, 37382 2362 / 96.1, 37382 2337 / 95.3, 37382
Qwen3.8-Flash-Next UD-IQ1_S, RTX 6000 Ada + RTX 3090 --fit 2667 / 87.6, 38190 2830 / 89.7, 38190 2658 / 88.0, 38190

Greedy text matched master in every cell, except where --fit picked a different layer split. That happens when free VRAM differs by about 16 MiB between launches, and master's text changes the same way.

Still worse (not changed by the fix)

  1. MoE cache load time. materialize_mapped copies the memory-mapped host experts into anonymous memory before registering them. Peak RSS does not grow, but 12 to 57 GB of file-backed pages become page-locked memory.

    model, setup master load after load master anon RSS after anon RSS
    Qwen4 UD-Q2_K_XL, 12 GB card, warm page cache 1.6 s 3.6 s 2.1 GB 14.5 GB
    Qwen4 UD-Q4_K_XL, 12 GB card, warm page cache 1.6 s 6.1 s 2.1 GB 22.0 GB
    Qwen4 UD-Q4_K_XL, 32 GB RAM, cold page cache 19.2 s 27.1 s 2.1 GB 22.0 GB
    gpt-oss-120b, 48 GB card, 94 GB RAM 3.3 s 93 s 0.7 GB 57.2 GB

    On gpt-oss-120b, the 62 GB file and the 57 GB copy do not both fit in 94 GB, so the copy of 58092 MiB re-reads evicted pages for 27 to 48 s. A multi-threaded copy saved only 0.7 s of 4.9 s on Qwen4 Q4_K_XL, because the copy is bound by page faults.

  2. Dense --fit partial offload. The prefetch adds about 108 MiB on top of the fit's margin (117.5 MiB of staging, minus 10 MiB in the graph allocator). In 1 of 4 Qwen3.6-27B launches on 16 GB, the headroom check dropped the prefetch after the arena was allocated, and peak VRAM was 15675 vs 15070 MiB on master. Speed matched master.

Setup

  • Hardware:
    • RTX 6000 Ada 48 GB on PCIe 4.0 x16, and RTX 3090 24 GB on PCIe 3.0 x4.
    • i9-14900K, 94 GB RAM.
    • The 16, 12 and 8 GB cards are the Ada with the rest of its memory held by another process.
    • RAM limits are cgroups without swap, with the model files evicted from the page cache first.
  • Server: each launch is a fresh llama-server with defaults, -fa on -c 32768 and greedy sampling. Builds are interleaved, and each figure is the median of 2 launches.
  • Scenarios:
    • Chat: 3 turns from a ~200-token prompt.
    • Agentic: 4 turns of 11k, +3.6k, +6.4k and +2.5k prompt tokens with prefix reuse, and 300 to 500 generated tokens per turn.

Not covered:

  • PCIe 5, GGML_SCHED_PREFETCH_EXPERTS=1, ROCm, Windows, WSL.
  • Parallel requests with the cache (failed in my harness).
  • gpt-oss-120b's greedy text differed from master in its single clean run; I did not check whether the placement differed.

scripts/unsloth/pr-set.json on master still pins 1d1e4f549.

MiB is int64_t in this function, so size_t/MiB is unsigned long long on macOS
(int64_t is long long there) and -Wformat rejects it under -Werror.
The MoE cache keeps the host lookup for expert groups with weight or input scales, so loading such layers without mmap gains nothing.
The GGUF expert scan now marks layers with ffn_*_exps scale or input_scale tensors and the load mode check skips them.
The MoE cache keeps the host lookup for expert groups with weight or input scales, so loading such layers without mmap gains nothing.
The GGUF expert scan now marks layers with ffn_*_exps scale or input_scale tensors and the load mode check skips them.
@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. Swish!

Reviewed commit: 966fa75bed

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

danielhanchen added a commit to LeoBorcherding/llama.cpp that referenced this pull request Dec 5, 2026
…ts device lookup counters

Conflicts resolved by keeping both sides: llama_perf_context_data keeps upstream's n_reallocs_same / n_reallocs_diff and adds the MoE cache fields after them; llama-moe-cache.h keeps unslothai#268's declarations and adds llama_moe_cache_stats.
danielhanchen added a commit to LeoBorcherding/llama.cpp that referenced this pull request Dec 5, 2026
On the pinned unslothai#268 cache, ubatches of up to 32 tokens look up their experts on the device and count hits and misses in each group's state tensor, so the host-only stats reported 0 for decode. get_stats now adds them (the exit log reads the same counters). The misses help text also covers misses computed on the CPU.
danielhanchen added a commit to LeoBorcherding/llama.cpp that referenced this pull request Dec 5, 2026
…as it is

pin_contract checks that a later pin keeps every line an earlier pin adds.
ggml_backend_cuda_copy_regions_async returned false on HIP and on CUDA
older than 12.8. The MoE cache prompt path then copied only long runs of
cached experts from device memory and uploaded every other used expert
from the host again. On a warm cache that made large ubatches slower than
upstream, which reads cached experts from the device (R9700 ROCm,
Flash-Next --cpu-moe with a 16 GB cache, ub 4096: warm prompt 648 vs
793 tok/s).

Without the batch API the device copies still run as one copy-regions
kernel, and uploads from pinned host memory become one cudaMemcpyAsync
per region, so every cached expert is copied from the cache. Builds with
the batch API are unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

On ROCm, prompt processing with a warm MoE cache was slower than upstream. HIP has no cudaMemcpyBatchAsync, so the region copy call returned false. The large-ubatch path then copied from the cache only the cached runs of at least 4 MiB, and uploaded every other used expert from host memory again. On the R9700 below, that was 0 copies from the cache and 9980 uploads per ubatch.

38c73159024 runs the region copies without the batch API too (HIP, and CUDA older than 12.8). Device copies go through the copy-regions kernel, and uploads from pinned memory are one async copy each. Builds with the batch API take the same path as before. GGML_CUDA_COPY_BATCH=0 turns it off.

Radeon AI PRO R9700 (gfx1201, ROCm), Qwen3.8-Flash-Next UD-IQ4_XS, -ngl 99 --cpu-moe --load-mode none --moe-cache-mib 16000 -b 4096 -ub 4096 -c 8192, second (warm) prompt, tok/s:

build prompt 3.6k prompt 7k decode cache copies per ubatch
upstream 793 799 30.0
this PR before 648 532 29.9 0 from the cache, 9980 uploads
this PR now 767 783 30.6 13130 from the cache, 17910 uploads

Greedy text is identical in every arm.

Turning off the seed (LLAMA_MOE_CACHE_SEED=0), the device lookup or the prefetch did not recover the speed; this change did.

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.

3 participants