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 105 commits into
base/upstream-0df40737cfrom
moe-offload-prefetch-cache
Open

danielhanchen wants to merge 105 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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ith a shallow query

serialize_graph sends every tensor a node is computed from, so a query for any
node downstream of the lookup carried the lookup, the server refused it and the
client aborted. Such nodes now send only the op and the layout of its sources,
and the batched prefetch is skipped for any graph that reaches a lookup.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Dec 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Dec 3, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: b4974b36f7

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

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: b581f7a31c

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

…71 rewrites

The lookup and consumer refusal now wraps supports_op in the device interface,
the batched-probe skip sits in graph_preprocess, and the ancestry helper sits
next to add_tensor. Behaviour is unchanged: the single-op query never reaches a
lookup after the shallow copy, so prefetch only needed the check on the
graph_preprocess path.
@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: 2b88647172

ℹ️ 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 common/common.cpp
Comment on lines +1974 to +1976
dev_lookup = dev_lookup && params.moe_cache_cpu_share <= 0.0f && (trace == nullptr || *trace == '\0');
ggml_backend_dev_t cpu = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
if (dev_lookup && (env == nullptr || atoi(env) != 0) && cpu != nullptr) {

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 mmap when expert scales disable device lookup

For a model whose cacheable expert layers have weight or input scales, --cpu-moe --moe-cache-mib N --fit off can still switch AUTO loading to NONE on CUDA even though every cache group will use host lookup. The cache constructor explicitly sets g.dev_ok = false for scaled groups in src/llama-moe-cache.cpp:869-873, but this gate checks only backend capability, CPU share, and tracing; the GGUF expert-layout scan does not account for scales. Consequently, these configurations unnecessarily load the entire model into allocated RAM instead of retaining mmap, increasing startup memory use despite device lookup being unavailable. Include scale eligibility in this decision, or defer the load-mode change until eligible cache groups are known.

Useful? React with 👍 / 👎.

…t, GGML_SCHED_PREFETCH_EXPERTS=1 copies them whole ahead
…ookup copies, so they are not resident twice
danielhanchen added a commit that referenced this pull request Dec 3, 2026
* Reconcile ggml op-count asserts after the pin merges

Two pins that each add a ggml op both bump static_assert(GGML_OP_COUNT == N)
to the same N+1, and git merges the identical edits silently: ggml-org#25731
(GGML_OP_FLASH_ATTN_EXT_BANDED) plus #268 (GGML_OP_MOE_CACHE_LOOKUP)
gave an enum of 103 ops with asserts saying 102, and the tree did not compile.

scripts/unsloth/reconcile_op_count.py counts the enum entries before
GGML_OP_COUNT in ggml.h and the entries of GGML_OP_NAME and GGML_OP_SYMBOL in
ggml.c. Only when every table matches the enum does it rewrite the stale
asserts under ggml/ (ggml.c and ggml-rpc.h) to the counted value; a table that
does not match is the merge bug the assert exists for and fails with file and
line. Same for GGML_UNARY_OP_COUNT and GGML_GLU_OP_COUNT.

It runs in the nightly's resolve step right after the merge loop (before the
source tar), and in the pin preflight before merge_checks.py. pin_contract.py
no longer holds a pin to its own op-count assert line, which the rewrite
replaces. Tests in test_reconcile_op_count.py and test_pin_contract.py, run by
the pr-set lint workflow.

* reconcile_op_count: keep the RPC version guard, commit the rewrite, skip comments

The ggml-rpc.h op-count assert exists to force an RPC_PROTO version bump, so it
is no longer rewritten blindly. With --base-ref (the tag the pins merged onto)
the tool compares the op count and RPC_PROTO_{MAJOR,MINOR,PATCH}_VERSION with
the base: an op count that changed while the version did not is a pin that
forgot the bump and exits 1 with nothing rewritten. When MAJOR and MINOR are
unchanged and PATCH moved by less than the op count rose (identical per-pin
PATCH bumps merged into one), PATCH is set to base PATCH plus the op delta and
reported. Without --base-ref a stale RPC assert is refused, never rewritten.

Asserts are now found in the comment and string blanked text and edited by
offset, so a commented-out or quoted static_assert is left alone.

The nightly commits the rewrite in the merge clone, so HEAD:ggml (the
published ggml ABI key) is the tree that ships. Both workflows pass
--base-ref refs/tags/$BASE. pin_contract.py also ignores a pin's own
RPC_PROTO_PATCH_VERSION line, which the PATCH bump replaces.

* reconcile_op_count: check the RPC version against --base-ref even when the RPC assert is current

* pin_contract: exempt the op-count and RPC PATCH lines only for pins that move an op count

* reconcile_op_count: check the RPC version with --base-ref even when the RPC assert is gone

* pin_contract: exempt the RPC PATCH line only for pins that move the main GGML_OP_COUNT

reconcile_op_count.py raises RPC_PROTO_PATCH_VERSION only from the GGML_OP_COUNT delta, so a pin
that changes only the unary or GLU count and bumps PATCH keeps its PATCH line in the contract. Each
family's own op-count assert stays exempt.

* reconcile_op_count: check every family, table order and removed ops

- validate enum vs table counts for every family whose enum and tables exist, asserts or not;
  with --base-ref a family whose base had an assert and whose merge has none exits 1
- GGML_OP_NAME, GGML_UNARY_OP_NAME and GGML_GLU_OP_NAME must be the enum names in enum order
  with the prefix stripped (true for every entry upstream at b11580); with --base-ref every op
  the base had must keep its base GGML_OP_SYMBOL entry
- a falling op count is reconciled like a rising one: PATCH = base PATCH + |delta|

* reconcile_op_count: check each merged pin's RPC bump, run it in repin, tighten the parser

- check_rpc compares every merged pin against its own fork point: a pin
  that changed GGML_OP_COUNT without bumping RPC_PROTO_*_VERSION is refused
  even when another pin's bump covers the merged version, and a merged
  version equal to the base's is accepted when upstream made the same bump
  from the same fork point (PATCH is then raised as before).
- repin.py runs reconcile_op_count.py after merging the base into a pin and
  commits the rewrite, as the nightly and preflight do; a refusal is
  reported as a conflict.
- pin_contract.py: a pin's RPC_PROTO_PATCH_VERSION line is satisfied by a
  PATCH reconcile raised past it (same MAJOR and MINOR).
- the missing-assert check runs before the layout is parsed; a deleted
  ggml-rpc.h the base has is refused; preprocessor lines in a table and
  non-sequential explicit enum values are layout errors; digit separators
  are not char literals; the assert message is found past a comment; git
  errors other than "no match" are errors; files are read and written as
  UTF-8 with surrogateescape; printed paths use forward slashes.
- tests for each case, test_repin.py added to the lint workflow.

* pin_contract: hold the PATCH line as a floor, share reconcile_op_count's parsers

- Read RPC_PROTO_* off comment-blanked text (blank_comments_and_strings), as
  reconcile_op_count.rpc_version does, so a commented define is not the version.
- Keep every pin's RPC_PROTO_PATCH_VERSION line in its contract; a lost line is
  covered only by PATCH >= the pin's under the same MAJOR.MINOR, or a newer
  MAJOR.MINOR for a pin that changes the GGML_OP_COUNT enum.
- Decide that from the ggml_op enum (enum_count), not from an assert line the
  pin may only have reworded.
- Exempt every line of an op-count static_assert reconcile_op_count rewrites
  (assert_re over FAMILIES, to the closing semicolon), so a multiline assert's
  message line is not owed after reconciliation.

* pin_contract: exempt only whole-line op-count asserts reconcile rewrites

* pin_contract: a line shared with an op-count assert owes its code, not the assert

* pin_contract: compare lines with an op-count assert with the assert's digits normalized

* pin_contract: one marker per assert number, PATCH lines judged on the active version only

* reconcile_op_count: refuse a rolled-back RPC series, a lowered pin version and conditional RPC defines; pin_contract owes op-count assert lines

A merged MAJOR.MINOR below the base's, or a pin whose op change lowered RPC_PROTO_*, is refused. RPC_PROTO defines under #if or duplicated are a LayoutError in both reconcile_op_count.py and pin_contract.py (shared rpc_version_matches). Whole-line op-count asserts stay owed with their count normalized, so a resolution that deletes them fails the pin.

* reconcile_op_count: refuse a PATCH rollback with no op change, and RPC defines that are not one plain integer

* reconcile_op_count: read raw strings as literals, and judge a refreshed carry pin's RPC bump below its base merge

* reconcile_op_count: recover a refreshed pin by its op entries, not the whole header; validate a declared family with no assert

* reconcile_op_count: a pin refreshed onto upstream past the tag, with the tag's ops and RPC version, is still recovered below that merge

* reconcile_op_count: refuse a pin refreshed onto upstream past the tag instead of guessing its own RPC bump

A changed-op upstream past the tag can carry a bump that hides the pin's missing one, and an unchanged-op one cannot be told apart from it without an upstream ref. No pin in the set has this shape; repin.py refreshes onto the tag. Replaces base_side_parent.

* Reduce comments

* Reduce comments

* Reduce comments

* reconcile_op_count: run it in the base-tag trial, commit it in preflight so the Metal job builds the reconciled tree

* reconcile_op_count : refuse a pin past the base only when it moves the op enum or RPC version

A pin whose history merges upstream past the base tag was refused before its op
enum or RPC header was read, so a pin with no op or RPC change failed the nightly
and the preflight. Compare the pin's tip against the upstream commit it merged
and refuse only when the op enum or RPC version differs; point the message at a
head whose upstream merges are at or below the base, since repin.py cannot fix a
pin that already contains the base.
LeoBorcherding added a commit to LeoBorcherding/llama.cpp that referenced this pull request Dec 4, 2026
@LeoBorcherding

LeoBorcherding commented Dec 4, 2026 •

Copy link
Copy Markdown

Tested on AMD at head 85ca63fd4 against its base 0df40737c (b12939): one Radeon AI PRO R9700 (gfx1201), Ryzen 9 9950X, 62 GB RAM, Windows, ROCm 7.1. Two cells here; the remaining three (whole model on GPU, --fit, Qwen3.8-27B) are in the next comment.

Setup: Qwen3.8-Flash-Next UD-IQ1_S unless noted, llama-server -c 12288 -np 1 -fa on -t 16, greedy. 2 fresh launches per arm, arm order rotated, median (min..max), second warm pass of each prompt. Something is called faster or slower only when the two arms' ranges do not overlap.

MoE cache: -ngl 99 --n-cpu-moe 24 -ub 2048 -b 2048 --moe-cache-mib 6144

#268 on one R9700, MoE cache over experts in host RAM

arm prefill, 8K prompt (tok/s) decode (tok/s) 8K decode (tok/s) next-turn decode (tok/s) peak RSS (GiB)
base 0df40737c 556.6 (554.2..559.0) 30.4 (28.1..32.6) 37.9 (33.6..42.2) 28.2 (27.4..29.0) 36.2
#268 default 1256.4 (1255.6..1257.2) 57.4 (57.4..57.4) 54.1 (54.0..54.3) 58.6 (58.5..58.8) 37.0
#268, LLAMA_MOE_CACHE_DEVICE=0 766.0 (762.2..769.7) 29.0 (28.8..29.2) 28.8 (28.7..29.0) 34.4 (33.7..35.0) 36.1

No cache: -ngl 99 --n-cpu-moe 24 --fit off

#268 on one R9700, experts of 24 layers in host RAM

arm prefill, 8K prompt (tok/s) decode (tok/s) 8K decode (tok/s) next-turn decode (tok/s) peak RSS (GiB)
base 0df40737c 217.5 (203.0..232.1) 19.7 (19.3..20.2) 20.1 (18.8..21.3) 21.4 (20.8..22.1) 36.1
#268 default 216.5 (216.0..216.9) 19.4 (19.4..19.5) 20.7 (20.7..20.8) 21.3 (21.3..21.4) 36.1
#268, GGML_SCHED_PREFETCH_EXPERTS=1 434.0 (421.4..446.6) 20.2 (19.5..21.0) 21.4 (21.3..21.5) 19.6 (19.2..19.9) 36.9
#268, GGML_SCHED_PREFETCH=0 227.2 (203.6..250.8) 21.7 (19.5..23.9) 21.5 (19.2..23.7) 21.0 (20.1..21.8) 36.1
  • Whole-expert prefetch is a 2x prefill win on this AMD setup, and the new default leaves it off. With GGML_SCHED_PREFETCH_EXPERTS=1 the 8K prompt reads at 434.0 tok/s against 217.5 on base (+99.5%). At the default since 0e731e286, Host-weight prefetch in the scheduler, faster MoE cache prompt and decode, cache seeding under llama-server #268 reads it at base speed (216.5 vs 217.5). That is the opposite of the NVIDIA result that motivated turning it off, where prefill with weights in host RAM was 17 to 43% slower with the prefetch on.
  • The cost of turning it on: next-turn decode is 19.6 tok/s (19.2..19.9) against 21.4 (20.8..22.1) on base, about 9% lower, and peak RSS is 0.85 GiB higher.
  • Same as base: decode in every arm, and all of the default arm. GGML_SCHED_PREFETCH=0 matches base.
  • Output: greedy text is identical to base in every arm.

Suggestion: keep whole-expert prefetch on for HIP, or pick the default per backend, since it is the difference between 217 and 434 tok/s here. The rerun on the timed-default build (default, =0, =1, three rounds each) will be added here when that build is up.

n = 2 launches per arm, so the percentages are a first read; the gaps called out above are all far outside the spread.

Not covered: --cpu-moe (58 GiB of host weights on 62 GB RAM would page), Linux ROCm, Vulkan.

LeoBorcherding added a commit to LeoBorcherding/llama.cpp that referenced this pull request Dec 4, 2026
@LeoBorcherding

LeoBorcherding commented Dec 4, 2026 •

Copy link
Copy Markdown

Rest of the AMD run on 85ca63fd4 vs base 0df40737c (same machine and method as my comment above: one or two Radeon AI PRO R9700, Windows, ROCm 7.1, 2 fresh launches per arm, rotated, median (min..max), warm pass). All 28 launches finished with no errors and identical prompt token ids.

The remaining cells: same as base, except dense prefill

cell arm prefill, 8K prompt (tok/s) decode (tok/s) 8K decode (tok/s) next-turn decode (tok/s) peak RSS (GiB)
whole model on 2x R9700, -ngl 99 --fit off base 2232 (2223..2242) 42.9 (42.8..43.0) 41.6 (41.4..41.7) 42.9 (42.7..43.0) 37.2
#268 default 2238 (2230..2246) 42.8 (42.8..42.9) 41.6 (41.5..41.7) 42.5 (41.9..43.1) 37.2
one R9700, --fit on -ub 2048 -b 2048 base 310 (307..312) 20.4 (20.3..20.5) 17.7 (17.4..17.9) 20.4 (20.3..20.6) 38.0
#268 default 305 (301..309) 20.4 (20.3..20.5) 17.3 (16.7..17.9) 20.3 (20.2..20.4) 38.0
Qwen3.8-27B UD-Q4_K_XL, one R9700, -ngl 40 --fit off base 568 (563..573) 5.3 (5.1..5.5) 5.0 (4.7..5.2) 5.3 (5.1..5.5) 17.6
#268 default 657 (637..676) 5.3 (5.1..5.5) 5.1 (4.8..5.3) 5.3 (5.0..5.6) 17.6
#268, GGML_SCHED_PREFETCH_EXPERTS=1 658 (637..679) 5.3 (5.1..5.5) 5.1 (4.9..5.3) 5.2 (5.1..5.3) 17.6
  • Whole model on GPU: no change. Prefill, decode and host RAM match base on both cards. This is both cards, which matches the NVIDIA two-GPU result (unchanged). The 8% decode drop NVIDIA saw was on a single card, which I could not run: this model does not fit on one 32 GB R9700.
  • --fit on -ub 2048: no change, and the output is identical to base, so fit picked a placement that behaves the same in both builds.
  • Dense model with layers in host RAM: prefill about 16% faster (657 vs 568 tok/s, ranges apart), decode unchanged. GGML_SCHED_PREFETCH_EXPERTS makes no difference there, as expected for a model with no experts. The 27B decode figures are short (16 tokens per prompt), so read them only as "no change".
  • Output: greedy text identical to base in every arm of all three cells.

So across the run: the MoE cache cell is the big win (2.3x prefill, 1.9x decode), whole-expert prefetch is a 2x prefill win that the new default leaves off, and nothing got slower except model load time with the MoE cache (24 s vs 11 s). The rerun on the timed-default build (default, =0, =1, three rounds each, with the next-turn decode question) follows when that build is up.

Remaining cells on the R9700

@LeoBorcherding

LeoBorcherding commented Dec 4, 2026 •

Copy link
Copy Markdown

The timed default is written and tested on AMD: one commit on top of 85ca63fd4, 0d20cdb6e on branch amd/prefetch-experts-auto of my fork (74 lines in src/llama-context.cpp and .h), ready to cherry-pick.

What it does: with GGML_SCHED_PREFETCH_EXPERTS unset, the first five large ubatches of a context are the probe: the first is not timed (it pages in the mmapped experts), the next four run routed-only, whole, whole, routed-only, and the faster mode is kept for the context. =0 and =1 force a mode with no timing. Graphs with no host experts skip the probe. The ubatch that seeds the MoE cache is never a probe.

Same --n-cpu-moe 24 table on that build (Qwen3.8-Flash-Next UD-IQ1_S, one Radeon AI PRO R9700, same method as above; timed pass is the second pass of each prompt, so the probe is paid on the first):

arm prefill, 8K prompt (tok/s) decode (tok/s) next-turn decode (tok/s) peak RSS (GiB)
default (unset), launch 1 466.6 22.7 22.1 36.9
default (unset), launch 2 466.9 22.2 22.4 36.9
GGML_SCHED_PREFETCH_EXPERTS=1 464.8 22.3 22.3 36.9
GGML_SCHED_PREFETCH_EXPERTS=0 232.7 22.5 22.9 36.1
for reference, 85ca63fd4 default (2 launches, earlier run) 216.5 (216.0..216.9) 19.4 21.3 36.1
for reference, base 0df40737c (2 launches, earlier run) 217.5 (203.0..232.1) 19.7 21.4 36.1
  • The default now picks whole-expert copy on this card and matches the forced-on speed (466.6 and 466.9 vs 464.8 tok/s). =0 and =1 still force each mode (232.7 vs 464.8).
  • The first prompt pays for the probe: the untimed first pass of the 8K prompt read 345 and 359 tok/s at the default against 390 with =1.
  • Next-turn decode: no 9% drop in this run. With whole-expert copy on it reads 22.1 to 22.4 tok/s against 22.9 with it off, about 2 to 3% and one launch for the =0 arm. The earlier 19.6 vs 21.4 was 2 launches per arm, so I would treat the 9% as not confirmed rather than gone.
  • Output: greedy text identical to base in all four launches, same prompt token ids.

What was run and what was not: built with the ROCm 7.1 toolchain on Windows and run on gfx1201 only, one launch per forced arm and two at the default; base and the old default were not re-run in this session (the same code path, routed-only, read about 7% faster on prefill and 14% faster on decode here than in the earlier run, so compare within this table). Not compiled or run on CUDA. The decision's log line (prefetch_probe_end: host experts of large ubatches are copied ...) did not show in llama-server's log at the default verbosity, so the choice is shown here by speed, not by the log. Not tried: -ub 2048 (five large ubatches is then about 10K tokens, so an 8K prompt would not finish the probe), --fit with --moe-cache-mib, multiple slots.

Timed default on the R9700

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.

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