Repository navigation
Host-weight prefetch in the scheduler, faster MoE cache prompt and decode, cache seeding under llama-server - #268
danielhanchen wants to merge 105 commits into
Conversation
…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
This reverts commit 521ca75.
…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.
…rs take the per-copy path
… supports_op queries
…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.
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…Unix, no backend DL), linking ggml-rpc
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 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".
| 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) { |
There was a problem hiding this comment.
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
* 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.
|
Tested on AMD at head Setup: Qwen3.8-Flash-Next UD-IQ1_S unless noted, llama-server MoE cache:
|
| 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 |
- Faster with Host-weight prefetch in the scheduler, faster MoE cache prompt and decode, cache seeding under llama-server #268: prefill 2.3x (1256.4 vs 556.6 tok/s), decode 1.9x (57.4 vs 30.4), decode at 8K context 1.4x (54.1 vs 37.9), and decode on the turn after a cached prompt 2.1x (58.6 vs 28.2). All far outside the spread.
- The device lookup is where the decode gain comes from. With
LLAMA_MOE_CACHE_DEVICE=0decode is back at base (29.0 vs 30.4, ranges overlap) and 8K decode is below it (28.8 vs 37.9), while prefill keeps part of the gain (766.0, +38%) and next-turn decode a smaller part (34.4, +22%). - Host RAM: peak RSS is 37.0 GiB with Host-weight prefetch in the scheduler, faster MoE cache prompt and decode, cache seeding under llama-server #268 against 36.2 on base, +0.8 GiB, and 36.1 with the lookup off. The NVIDIA report on the earlier head
fd7489efbsaw 37.4 -> 67.2 GiB with the device lookup. This head has85ca63fd4, which releases the mapped pages of the experts the lookup copies, so the two are not like for like, but the growth it was written to fix is not there on this setup. - Slower with Host-weight prefetch in the scheduler, faster MoE cache prompt and decode, cache seeding under llama-server #268: the model takes 24.0 s to load (22.0 and 26.0) against 10.9 s on base and 11.4 s with the lookup off.
- Output: greedy text is identical to base in all three arms.
No cache: -ngl 99 --n-cpu-moe 24 --fit off
| 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=1the 8K prompt reads at 434.0 tok/s against 217.5 on base (+99.5%). At the default since0e731e286, 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=0matches 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.
|
Rest of the AMD run on The remaining cells: same as base, except dense prefill
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, |
|
The timed default is written and tested on AMD: one commit on top of What it does: with Same
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 ( |
…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.
…ce address with cudaMemcpyAsync) (#482)




Faster MoE and dense inference when weights live in host memory (partial
-ngl,-ot/--cpu-moe,--fitspill), and a faster--moe-cache-mibcache. 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.pymay 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 in0e731e286d7and85ca63fd41f:--load-mode none) on PCIe 5, where it paid off.GGML_SCHED_PREFETCH_EXPERTS=1restores the whole-expert copy ahead. The prefetch of dense host weights (e.g.-ngl N) is unchanged.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:GGML_SCHED_PREFETCH=0--cpu-moe--n-cpu-moe 20--n-cpu-moe 20--cpu-moe--n-cpu-moe 20--cpu-moe--n-cpu-moe 20Upstream'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=0arm. 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)
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.--cpu-moeand--n-cpu-moewithout the MoE cache (table above); the whole model on the GPU (--fit onon the A100: 3342 vs 3345 tok/s prompt at ub 512, 4298 vs 4305 at ub 2048, decode 91.2 vs 91.3).-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.--n-cpu-moe 20 --moe-cache-mib 4096, ub 2048):-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:--moe-cache-cpu-share, ggml-org#30966), quant scale banks (ggml-org#28898), and the cache graph code inllama_moe_cache::build_lookup/build_experts(ggml-org#32157).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, withLLAMA_MOE_CACHE_TRACE, and for layers that read the same experts.add_extra_memoryandplan()signatures. With common : add --moe-cache-mib auto to size the MoE expert cache from the fit #251 pinned,llama-fit-paramsprints 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)--fitand the memory breakdown count it (Qwen3.8-Flash-Next: 1275 MiB).GGML_SCHED_PREFETCH_EXPERTS=1copies 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.GGML_SCHED_PREFETCH=0.2. MoE cache, prompt path (
src/llama-moe-cache.cpp,ggml-cuda/copy-regions.cu)cudaMemcpyBatchAsyncplus a copy-regions kernel per expert tensor.GGML_CUDA_COPY_QUEUE_KERNEL=0/1overrides 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)LLAMA_MOE_CACHE_DEVICE=0falls back to the host lookup.4. Cache seeding at the end of a prompt
LLAMA_MOE_CACHE_SEED=0disables it.LLAMA_MOE_CACHE_SEED_CHECK=1verifies 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)
-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.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):
The prefetch arms equal the
GGML_SCHED_PREFETCH=0arms 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). WithGGML_SCHED_PREFETCH=0both 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:
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.LLAMA_MOE_CACHE_SEED=0with 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-moewithout the cache,--cpu-moewith a 4 GiB cache, and-ngl 20;--load-mode noneand mmap.In every run, the
llama-perplexitylogits and the 128-token greedy text after a 2k prompt are byte-identical to upstream b12939, with the features on and with each ofGGML_SCHED_PREFETCH=0,LLAMA_MOE_CACHE_DEVICE=0andLLAMA_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
--fitmodes, 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-archspasses 162/162, as dotest-allocandtest-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_contractreports 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
--fit on(split) on this base. The B200 numbers from the b11577 version of this PR were not re-measured.Base is upstream b12939
0df40737c. Like every pin inscripts/unsloth/pr-set.json, this is merged onto the aged upstreamb####tag for the prebuilt and dropped once upstream has the equivalent.