Skip to content

Add opt-in decode levers for tensor-parallel DeepSeek-V4.1 serving: graph slots, backend sampling, sampler reuse, inline yield, RPC pipelining, DSV4 verify-graph reuse - #7

Merged
lukekim merged 31 commits into
spiceai-b11803from
lukim/b11803-verify-graph-reuse
Oct 26, 2026
Merged

lukekim merged 31 commits into
spiceai-b11803from
lukim/b11803-verify-graph-reuse

Conversation

@lukekim

@lukekim lukekim commented Oct 26, 2026 •

Copy link
Copy Markdown

What this changes

Opt-in decode levers for tensor-parallel DeepSeek-V4.1 serving over the meta backend, each behind an environment variable (or a flag:<path> file re-read at runtime, as PR #5's switches are) and off by default, plus the diagnostics that found them. With every lever on, two DGX Spark ranks decode DeepSeek-V4.1-Flash (UD-Q2_K_XL, DSpark drafter, three drafts) at 39.0–40.0 tok/s pooled over the harness's eight prompts, against 32.5 tok/s for the stock build with PR #5's switches and 22.9 tok/s for plain decoding; the texts are identical to the stock build's DSpark texts on every prompt.

lever switch what it does
graph slots LLAMA_GRAPH_SLOTS=<n> (or flag:<path>), LLAMA_GRAPH_SLOTS_ALL_OUTPUTS two schedulers per context with stable meta subgraph uids and a two-slot meta graph cache with slot-owned clones, so the drafter's and the target's graphs stop evicting each other; stored graphs are forgotten on both sides of a buffer free, one meta split is kept per compute buffer, and a prompt's last chunk keeps the verify graph (one llm_graph_result per slot, chosen by slot in get_gf_res_prev, not by n_outputs > 0)
backend sampling with SPLIT_MODE_TENSOR LLAMA_TENSOR_BACKEND_SAMPLING=1, LLAMA_DRAFT_BACKEND_SAMPLING samples the target and the drafter on the backend with a mirrored output head (the requirement is stated as the meta backend checks it); a drafter chain re-attached by the flag counts as a new one
output-head gather, DSpark split LLAMA_TENSOR_LOGITS_GATHER=1, LLAMA_DSPARK_SPLIT=1 gathers a split output head's logits onto every device (with a warning), and splits the DSpark drafter's feature projection and Markov transition like the rest of the model
scheduler sync once, RPC set batching GGML_SCHED_SYNC_INPUTS_ONCE, GGML_RPC_SET_BATCH (GGML_RPC_SET_BATCH_LINGER_US) the scheduler waits for a split's backend once before setting its inputs, and RPC tensor writes go out in batches
RPC read pipelining GGML_RPC_READ_PIPELINE sends queued reads without waiting for each reply, at most 16 pipelined replies in flight
sampler reuse, full drafts LLAMA_SERVER_REUSE_SAMPLER, LLAMA_SERVER_FULL_DRAFTS keeps a greedy sampler attached across a slot's tasks instead of rebuilding it per request, and lets the drafter draft full blocks to a generation's end
inline yield LLAMA_SERVER_INLINE_YIELD (_DEBUG counts the paths) runs a yield's work inline when no queued task could be processed during the yield (server_task_type_handled_while_yielding), instead of a round trip through the task queue on every decode step
page-cache drop after load LLAMA_DROP_UPLOADED_CACHE drops the page cache of model file ranges no longer mapped once the weights are uploaded, so a 135 GiB model does not keep its file pages beside its device copy
engram prefetch LLAMA_ENGRAM_PREFETCH_FIRST starts reading a host table's rows before the other inputs are set
decode timing LLAMA_DECODE_TIMING=1 DT/DTM lines that time each decode call's main-thread phases and the server's speculative loop phases
reuse diagnostics LLAMA_DEBUG_REUSE one line per target call (DBGREUSE arch … can_reuse), and on a failed reuse the input class that refused it with the dimensions it compared (llm_graph_result::can_reuse, the DSV4 compressor plans, the V4.1 candidate pin and Engram inputs)
DSV4 compressor-plan padding LLAMA_DSV4_VERIFY_REUSE=1 pads a split ubatch's CSA/LID compressor plans to a phase-independent block count (dsv4_build_comp_plan), through the dummy block the independent-sequence padding already appends (reads a valid current-token row, writes the last cache slot while it is masked, position zero), so a 5-token verify graph reuses across decode steps

Fixes that are always on: a meta-backend compute container that runs out of room for views spills into another context instead of aborting (GGML_ASSERT(obj_new) on a stock -np 1 DeepSeek TP2 load); a rebuilt meta split points at the current simple tensors; ggml-alloc plans a graph again when its outputs are other nodes than the plan's; views a rebuild finds gone are remade.

The last two levers came from one investigation: with four drafts the 5-token verify graph was rebuilt on 1100 of 1358 target calls because the verify ubatch is five one-token coupled sequences, for which the compressor plans' completed-block counts alternate with the first position's phase (CSA ratio 2: 2 or 3 blocks; LID ratio 4: 1 or 2), while four consecutive positions always complete exactly 2 and 1, which is why three drafts reused. The padding makes the counts constant without touching a real block's indices or positions.

Evidence

DeepSeek-V4.1-Flash-1017 UD-Q2_K_XL (7 shards, 135 GiB) with the DSpark Q8_0 drafter, tensor-parallel over two DGX Spark ranks (NCCL all-reduce, 4 channels, LL), one slot, eight fixed prompts, greedy (temperature 0), pooled tok/s over the eight prompts; every arm's texts compared with the stock build's own DSpark texts (WV7), and walked against a stock plain llama-server's greedy decode with oracle_diff.py (the arm's token must be the oracle's argmax or a near tie, tau 1.0). Dates are 2026-10-25/26 UTC.

arm commit tok/s (a / b) texts = stock DSpark
stock, plain decoding (default slots) 3185bd41 22.88 reference WV8
stock, DSpark n3 with PR #5's switches 3185bd41 32.53 8/8
the branch's earlier levers on, sampler reuse off 65d296ac3 38.06 / 38.02 8/8
+ sampler reuse, full drafts 1cbe976df 38.54 / 38.84 8/8
+ inline yield 292c901a7 39.35 / 39.05 8/8
every switch on, three drafts (second load) 292c901a7 39.04 / 39.57 8/8
every switch on, three drafts (third and fourth loads) 292c901a7 39.43 / 39.54; 37.71 / 40.01 8/8
every switch on, four drafts 292c901a7 30.29 / 30.61 4/8 (four drafts differ from three on near ties; oracle walk 7/8)
four drafts, LLAMA_DSV4_VERIFY_REUSE off a8c6907b0 29.42 / 30.00 = four-draft texts 8/8
four drafts, LLAMA_DSV4_VERIFY_REUSE=1 a8c6907b0 36.15 / 36.15 = four-draft texts 8/8 (identical to the switch off)
  • Load-to-load variance on the same build and switches is about 2 tok/s (the third and fourth loads above), so single-arm deltas under that are noise; the levers were accepted on mirrored arm orders (A B B A).
  • Reuse under four drafts: DBGREUSE … tok 5 … can_reuse was 1 on 258 of 1358 target calls with a previous graph before the padding and on 1464 of 1465 after; the diagnostics' own cost was not measurable (30.35 / 30.27 with them vs 30.29 / 30.61 without).
  • Four drafts stay slower than three even with reuse (a 5-token verify costs ~9 ms more per step on these ranks than a 4-token one and earns ~0.4 tokens per step), so three drafts remain the recommended setting; the padding is what makes any odd verify length reusable.
  • Client pinning (taskset onto the X925 cores, -t 10) was measured at the same time and was inert (36.9–37.7 pinned vs 39.4–39.5 unpinned); it is not part of this PR.
  • Oracle walks: every lever arm's texts equal the stock DSpark texts, so their walk is the stock DSpark walk; the stock DSpark decode itself departs from plain greedy decoding on near ties, as the drafter's verify batch does (reported with the walk, not changed here).

What is not covered

Review

An adversarial review of the branch (4b4400d82 against spiceai-b11803) found three defects in configurations the lab did not run, fixed in the last commit; none was reproduced at runtime, and each fix narrows a lever to the configurations it was measured in:

  • With graph slots and a backend sampler that binds input tensors (the dist sampler's uniforms, the penalties' token ids and counts), a slot switch reused the other slot's graph without rebinding them, so a sampled (non-greedy) request could read stale RNG or penalty inputs. Such a chain now keeps one graph slot (llama_sampler_backend_has_inputs); a greedy chain binds none.
  • The kept-sampler key accepted temperature 0 with a dynamic range (which common_sampler_init turns into a dist sampler) and was built from the rounded print(), which leaves the dynamic range out; the key now requires exactly the greedy chain and spells every shaping parameter in its exact float form.
  • A chain detached while LLAMA_SERVER_REUSE_SAMPLER was off kept its key, so re-enabling the switch attached it again and llama_sampler_chain_backend_init asserted on the second call; detaching now clears the key.

The review did not establish a race in the inline-yield path, a lifetime violation in the compute-container spill, or a dummy-slot violation in the DSV4 padding; race freedom under concurrent slots, RPC backpressure on disconnect, and the padding's equivalence under cache saturation are not verified beyond the single-slot lab runs above.

Copilot's review of e4b936a4d (5647504516) found five more, fixed in 046d98ce5 and answered in its threads: the RPC server now reduces a meta-backend gather exactly whatever its size (the lossy bf16 host path left each rank with its own slice exact and the others rounded); a kept greedy chain is never reused by a TTS task and only by a request sampled the way the chain is attached; llama_sampler_backend_has_inputs ignores the empty sampler's no-op callback, so the default temperature-0 chain keeps both graph slots (that helper landed after the lab runs, so no measurement included it); the decode-timing state is per thread; the engram flag-file switch uses atomics. None reproduced at runtime; the lab configuration (greedy, NCCL, completions only) is unchanged by them.

Copilot's review of 046d98ce5 (5647602017) found that the backend-sampling decision, moved ahead of common_sampler_init for the kept-sampler key, no longer saw that call turn backend sampling off for a grammar or reasoning-budget chain; the Backend sampling CI job reproduced it (GGML_ASSERT(!gsmpl->grmr …) on a response_format request). 095078405 checks the decision again after the chain is built, and also drops a freed compute buffer's parked graph split in the meta backend (its previously-missed finding: recreating the schedulers left splits parked under freed buffers).

…: meta views of the other graph are dropped)
…ild finds gone

The meta backend keeps a split per compute buffer while graphs come from more than one (a context with
LLAMA_GRAPH_SLOTS=2 alternating between two schedulers), instead of reading a flag of its own that could
disagree with the context's for up to 100 ms after a flag-file toggle. A rebuild of a reused graph's split
makes again the simple tensors of views that another graph's rebuild reset when it rotated a shared buffer's
compute containers. A scheduler no longer reuses a graph result the other scheduler built since.
…); empty sources count as mirrored

LLAMA_TENSOR_BACKEND_SAMPLING=1 lets a context offload sampler chains with SPLIT_MODE_TENSOR, which holds
while the sampled logits are mirrored (an output head that is not split). LLAMA_DRAFT_BACKEND_SAMPLING=flag:<path>
keeps the DFlash/DSpark drafter's top-k chain attached only while <path> exists, so one load can A/B it. The meta
backend treats an empty source as mirrored: a ubatch without outputs pads its empty logits to one row for the
sampler chains, and that pad asserted on the source's unknown split state.
…; RPC writes go in batches (switches)

GGML_SCHED_SYNC_INPUTS_ONCE: ggml_backend_sched_copy_input synchronized the split backend before every user input.
For the meta backend over RPC servers that is a round trip through every server's dispatcher per input, about 22
per DeepSeek-V4 verify, and it kept the queued writes from ever piling up. Only the input copies reach the backend
between those waits, so one wait per split covers them.

GGML_RPC_SET_BATCH: the writes queued behind a write go to the server with it as one RPC_CMD_SET_TENSOR_MULTI, which
the server applies after one sync instead of one per write. A batch waits up to GGML_RPC_SET_BATCH_LINGER_US (100)
for the next write while the queue is empty; any other queued command ends it. Servers without the command close
the connection on it, so the switch needs servers from this build.
…s it

972b0f2 said the switch needs an output head that is not split. The requirement the meta backend enforces is on the
sampled logits: its per-row ops assert when the vocabulary axis is split. A Qwen3.5-0.8B MTP run with a vocab-split head
sampled on the backend without that assert, so the head's split alone does not decide it.
…SPLIT_MODE_TENSOR

76b91be dropped it on a report that a vocab-split head sampled on the backend without the assert. The models in that
run tie their output head to the token embeddings, which the split rules mirror, so their logits were mirrored and the
run did not test a split head. The meta backend's per-row ops assert when the vocabulary axis of the sampled logits is
split.
llama_sampler_chain_backend_init asserts when a chain is set up for the backend twice, so detaching frees the chain
and keeps a fresh one for the next attach. The factorial A/B died at its first switch to drafter backend sampling.
A graph its scheduler reused keeps the simple tensors made when it was allocated, and their sources are the simple tensors
their sources had at that moment. With two schedulers per context (LLAMA_GRAPH_SLOTS) the other scheduler's rebuilds rotate
the compute containers of a buffer both graphs view (the KV cache), so a source can be reset and its memory handed to
other tensors. Rebuilding the reused graph's split (when its parked split was dropped) then wired flash-attention nodes to
other layers' cache views: the DeepSeek-V4.1 DSpark drafter drafted only non-finite logits, or the ranks hit an illegal
memory access. Point every node's sources at the current simple tensors, remaking the missing ones, as allocating does.
…the plan's

The plan keeps a graph's outputs alive for the whole graph and lets other tensors reuse the memory of the rest, but
ggml_gallocr_needs_realloc compared only node counts and sizes. A graph of the same shape whose outputs are other nodes
then ran on a plan that had given those nodes shared memory: a backend sampler builds every sequence's chains and marks
only the drafting sequence's as outputs, so with a scheduler that only sees drafts (LLAMA_GRAPH_SLOTS) the first drafting
sequence's plan put the next sequence's four top-k outputs at one address, and every draft after a change of sequence was
garbage. Record each node's output flag in the plan and plan again when it differs.
…SOR_LOGITS_GATHER=1)

With -sm tensor, a model's output head is split by vocabulary rows, so each device computes part of the logits;
samplers and draft heads that need whole rows (top-k, argmax, the DSpark Markov head) cannot run on them, which is
why DeepSeek-V4 mirrors its head and computes all 129280 rows on every device.

ggml_backend_meta_gather() makes a copy that the meta backend holds whole on every device: each device pads its
slice with zeros to the whole tensor at the slice's offset, a partial sum that the existing all-reduce turns into
the whole tensor (adding zeros to F32 is exact). A graph that ends in such a node is all-reduced too, and reading
it back reads one device's copy.

LLAMA_TENSOR_LOGITS_GATHER=1 splits the DeepSeek-V4 head like other models' and gathers the logits of the target
and of the DFlash/DSpark drafters before their heads read them.
… (LLAMA_DSPARK_SPLIT=1)

With LLAMA_TENSOR_LOGITS_GATHER=1, LLAMA_DSPARK_SPLIT=1 splits fc.weight and markov_w2.weight of a DFlash/DSpark drafter by
output rows like the head, and gathers their results before the norm, add and argmax that read whole rows. Each device
reads half of the 84 MB projection per inject and half of the 66 MB transition per drafted position.
…t (LLAMA_ENGRAM_PREFETCH_FIRST)

DeepSeek-V4.1 gathers its Engram rows from the CPU-resident per_layer_token_embd through the mmap, and the prefetch
(madvise WILLNEED) went right before that gather, so a row not in the page cache was read from disk on the decode's
critical path with no lead time. With LLAMA_ENGRAM_PREFETCH_FIRST=1 (or flag:<path>), set_inputs first calls every
input's prefetch(), which hashes the Engram rows and starts their reads, then sets the other inputs, then the late
ones (the Engram gather, which reuses the hashed rows).
…load (LLAMA_DROP_UPLOADED_CACHE)

With mmap, the loader reads every tensor bound for another buffer (a GPU, an RPC server) through the mapping and then
unmaps those ranges, but their pages stay in the page cache. For a model with a CPU-resident table read through the
mapping while decoding (DeepSeek-V4.1's 126 GiB Engram rows), those pages crowd the table out, so its rows are read
from disk on the decode path. With LLAMA_DROP_UPLOADED_CACHE=1 the unmapped ranges are also dropped from the page cache
(posix_fadvise DONTNEED, Linux), leaving the memory to the ranges that stay mapped.
…the verify graph (LLAMA_GRAPH_SLOTS_ALL_OUTPUTS)

With LLAMA_GRAPH_SLOTS on, the graph results were still indexed by n_outputs > 0. A prompt's last chunk outputs
one token, so it shared the verify's result object even when it ran on the other scheduler, and every request's
first verify rebuilt its graph. LLAMA_GRAPH_SLOTS_ALL_OUTPUTS=1 (or flag:<path>) puts only ubatches whose every
token is an output on the second slot, and each slot now has its own result. The slot decision is made once per
ubatch. LLAMA_DEBUG_REUSE=1 prints each target call's reuse decision (DBGREUSE lines).
…ER_REUSE_SAMPLER), and draft full blocks to a generation's end (LLAMA_SERVER_FULL_DRAFTS)

Each task created a new sampler and attached it to the context, then detached it at the end. Each attach makes
the context reserve its graphs again, so every request rebuilt the target's verify graph. With -np 1 and
LLAMA_SERVER_REUSE_SAMPLER, a stateless greedy sampler (temperature <= 0; no grammar, bias, penalties, mirostat,
reasoning budget or log-probabilities) stays attached. The next task reuses it when its parameters match. A slot
tracks whether its sampler is attached. A sampler that may still be attached is detached before it is freed, so
the context never holds a freed chain. LLAMA_SERVER_FULL_DRAFTS drafts full blocks up to the last step, so the
verify keeps one shape. The tokens past the limit are dropped before they are sent. Both switches take 1 or
flag:<path>.
… another context instead of aborting

A static buffer's compute container is sized for 16 views per tensor between two evals. A buffer with few tensors,
such as an MTP head's KV cache, can need more, for instance when several graphs are reserved before the first eval;
ggml_new_tensor then aborted with GGML_ASSERT(obj_new) under ggml_gallocr_alloc_graph (seen on three DGX Sparks with
GLM-5.3 MTP 3 under llama-server and DeepSeek-V4.1 DSpark under spiced, both split three ways). Tensors past the
reservation now go to spill contexts that are freed with the rest when the container rotates. The static container
never spills: it is sized exactly, and its contexts are iterated to allocate its tensors.

Not reproduced on a Mac (Qwen3.5-0.8B MTP 3 and 4 over three RPC ranks ran before and after); the lab runs decide it.
…INLINE_YIELD)

yield_to_queue() hands the task queue to a worker thread for the length of a decode, and takes it back after.
That is two thread wake-ups per yield. A speculative pass yields three times (verify, drafter inject, draft),
which costs 0.2-0.4 ms each at P50 on the two-rank DeepSeek client. With LLAMA_SERVER_INLINE_YIELD=1 (or
flag:<path>), a yield with no task waiting runs its work directly. A task that arrives meanwhile is processed
by the main loop between two updates of the slots.
…ing the yield

The slot update posts a NEXT_RESPONSE task before it decodes, and requests waiting for a slot are queued too, so
the earlier rule (an empty queue) never ran a yield inline: with LLAMA_SERVER_INLINE_YIELD_DEBUG=1, all 1096
yields of a 4-request run on the Mac reported normal. A yield's worker processes only the tasks that read the
server state (METRICS, SLOT_GET; now one rule, server_task_type_handled_while_yielding) and declines the rest, so
the inline path now runs unless such a task is queued. A task that arrives during the work waits for the yield to
end. Same run after: every yield inline, 4 concurrent requests and a disconnected client handled, /metrics and
/slots answered during a decode, texts equal to stock llama-server.
…t compared, under LLAMA_DEBUG_REUSE

Diagnostics only, printed when a reuse check fails and LLAMA_DEBUG_REUSE is set: the graph-parameter comparison (old/new ubatch layout, outputs, input modes, sampler equality), the failing input's class with the ubatch dimensions and first position, and for the DeepSeek-V4 inputs every compressor index tensor's old/expected length, the raw and compressed n_kv and stream counts, and the V4.1 candidate-pin and Engram dimensions. No comparison result, graph operation or tensor changes; nothing is evaluated when the variable is unset or the check passes.
…t block count (LLAMA_DSV4_VERIFY_REUSE)

A speculative verify ubatch arrives as several one-token sequences of one id at consecutive positions. The compressor plans pad each sequence to ceil(n_seq_tokens/ratio) blocks, which is one block for such a layout, so the number of completed CSA (ratio 2) and LID (ratio 4) blocks in the plan follows the first position's phase: 2 or 3 and 1 or 2 for five tokens, where four tokens always complete exactly 2 and 1. The graph's input shapes then differ between consecutive decode steps and llm_graph_input_dsv4::can_reuse refuses the previous graph on most of them (1100 of 1358 target calls with four drafts; none with three).

With LLAMA_DSV4_VERIFY_REUSE=1, a ubatch that is one id's consecutive one-token sequences is padded to ceil(n_tokens/ratio) blocks, through the same dummy block the independent-sequence padding appends: it reads a valid current-token row, writes the last cache slot, which is masked while the plan's n_kv stays below the cache size, and carries position zero, so the real blocks' indices and positions are unchanged and no output changes. Off by default; the variable is read once.
…one graph

Three review findings on the lever branch, each a configuration the lab did not run (its arms sampled greedily and never flipped the reuse switch mid-load):

- A backend sampler that binds input tensors (the dist sampler's uniforms, the penalties' token ids and counts) binds them to the graph it is built into, and a graph-slot switch reused the other slot's graph without rebinding them, so its inputs were set in one graph and read in the other. Such a chain now keeps one graph slot (`llama_sampler_backend_has_inputs`), as without LLAMA_GRAPH_SLOTS; a greedy chain binds none and keeps both.
- The kept-sampler key accepted a temperature of 0 with a dynamic range, which common_sampler_init turns into a dist sampler, and was built from the rounded `print()` that leaves the dynamic range out, so two requests with different dynamic temperatures could share one chain. The key now requires exactly the chain common_sampler_init makes greedy (temperature 0 with no dynamic range, or top-k 1, last; no adaptive-p, XTC, distribution or stateful sampler) and spells every shaping parameter in its exact float form.
- A chain detached while the reuse switch was off kept its key, so the next task with the switch on attached it again and the chain's backend_init asserted on its second call. Detaching now clears the key, and the next task builds a new chain.

These were found by reading, not reproduced at runtime; each fix narrows a lever to the configurations it was measured in, and leaves the others on the stock path.
Copilot AI balanced review requested due to automatic review settings October 26, 2026 04:33

Copilot AI 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.

🟡 Changes recommended

Unresolved sampling correctness defects and shared-state data races prevent safe approval.

5 open issues
What changed in this PR

Adds opt-in decode optimizations for tensor-parallel DeepSeek-V4.1 serving, extending the earlier RPC and CUDA switches with graph reuse, backend sampling, and reduced scheduling overhead.

Changes:

  • Adds graph slots, logits gathering, sampler reuse, inline yield, and RPC batching and pipelining.
  • Adds Engram prefetching, uploaded page-cache dropping, compressor-plan padding, and decode diagnostics.
  • Fixes allocation-plan invalidation and meta-backend tensor lifetime handling.
File Description
tools/​server/​server-task.h Centralizes which tasks may run during yields.
tools/​server/​server-queue.cpp Adds opt-in inline yield execution.
tools/​server/​server-context.cpp Adds sampler reuse, full drafts, and timing markers.
src/​models/​dflash.cpp Gathers split drafter projections and logits.
src/​models/​deepseek41.cpp Adds Engram prefetching and reuse diagnostics.
src/​llama-sampler.h Declares sampler input-binding detection.
src/​llama-sampler.cpp Implements sampler input-binding detection.
src/​llama-model.h Declares output-gather and drafter-split switches.
src/​llama-model.cpp Configures optional output and drafter weight splitting.
src/​llama-model-loader.cpp Optionally drops uploaded model file pages.
src/​llama-kv-cache-dsv4.cpp Pads compressor plans for verify-graph reuse.
src/​llama-graph.h Adds prefetch hooks and logits-gather state.
src/​llama-graph.cpp Implements prefetch ordering, gathering, and diagnostics.
src/​llama-cparams.h Adds the logits-gather context option.
src/​llama-context.h Adds alternate scheduler and graph-slot state.
src/​llama-context.cpp Integrates graph slots, tensor backend sampling, and timing.
ggml/​src/​ggml-rpc/​ggml-rpc.cpp Adds batched writes, pipelined replies, and cache invalidation.
ggml/​src/​ggml-backend.cpp Optionally synchronizes input copies once per split.
ggml/​src/​ggml-backend-meta.cpp Adds gather support, cached splits, and tensor lifetime fixes.
ggml/​src/​ggml-alloc.c Replans allocations when output flags change.
ggml/​include/​ggml-backend.h Exposes the meta-backend gather operation.
common/​speculative.cpp Adds runtime drafter sampler toggling and timing markers.

Review effort: Balanced

Comment thread ggml/src/ggml-backend-meta.cpp Resolved
Comment thread tools/server/server-context.cpp Resolved
Comment thread src/llama-context.cpp Resolved
Comment thread src/llama-graph.cpp Resolved
Comment thread src/llama-sampler.cpp Resolved
@lukekim lukekim self-assigned this Oct 26, 2026
…e sampling it was attached for, and race-free diagnostics

Five review findings on the lever branch, none reproduced at runtime:

- The RPC server rounded large host-path partials to bf16, so a meta-backend gather (the split output head's logits) left each rank with its own slice exact and the others rounded, and ranks could disagree on the argmax; a gather is now reduced exactly whatever its size.
- A kept greedy chain could be reused by a TTS task, which samples on the CPU and would skip the chain's offloaded samplers, and then be attached again; the backend-sampling decision now precedes the keep decision, TTS never reuses a chain, the key carries that decision, and a chain is reused only when its attachment matches.
- `llama_sampler_backend_has_inputs` counted the empty sampler, whose backend_set_input is a no-op, so the default temperature-0 chain (disabled penalties and DRY as empty samplers) would have lost its second graph slot; the empty sampler binds nothing.
- The decode-timing diagnostics kept one global state for every context; it is per thread now.
- The engram prefetch flag-file switch read and wrote plain statics from every context; they are relaxed atomics, as the server's switches are.
Copilot AI balanced review requested due to automatic review settings October 26, 2026 04:51
@lukekim

lukekim commented Oct 26, 2026

Copy link
Copy Markdown
Author

Addressed #7 (review) in 046d98c. Its five threads are answered in place and resolved; they cover the headline's two topics (sampling correctness: the kept-chain/TTS path and the empty-sampler check; shared-state races: the decode-timing state and the flag-file statics) plus the exact reduction of a gather on the host path. None of the five was reproduced at runtime: each is a reading-derived fix that narrows a lever to the sampling it was measured with or removes a shared mutable, and the lab configuration (greedy, NCCL, completions only) is unchanged by them. Compile-checked on 046d98c: cmake --build build-cpu --target llama-server ggml-rpc-server exit 0. The windows check on e4b936a failed in unit/test_router.py::test_router_delete_model because its model download from Hugging Face failed with status code -1 after 3 attempts (common_download_file_single_online: download failed after 3 attempts), not from this branch; the push re-runs it.

Copilot AI 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.

🟡 Changes recommended

Sampler initialization can bypass required CPU fallback, and scheduler recreation can retain retired graph-cache allocations.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Medium severity Clear parked graph cache when recreating schedulers

ggml/​src/​ggml-backend-meta.cpp:1989

sched_reserve() recreates the schedulers, but freeing their compute buffers does not remove the graph contexts and clones retained in parked. With graph slots enabled and injection/draft graphs alternating, the idle eviction does not run, so repeated backend-sampling flag toggles can grow this cache whenever replacement buffers have distinct addresses. Invalidate retired slots when their buffers are freed, or safely clear the cache when recreating the schedulers.

5 resolved since last review

Review effort: Balanced

Comment thread tools/server/server-context.cpp Resolved
@lukekim
lukekim merged commit 59d5123 into spiceai-b11803 Oct 26, 2026
16 of 38 checks passed
@lukekim

lukekim commented Oct 26, 2026

Copy link
Copy Markdown
Author

Addressed #7 (review) in 0950784. Its thread (backend sampling decided before common_sampler_init could turn it off for a grammar or reasoning budget) is answered in place and resolved; the Backend sampling CI job on 046d98c had reproduced it (GGML_ASSERT(!gsmpl->grmr ...) in test_completion_with_response_format), and the job on 0950784 is the after-evidence. The finding under previously missed issues, Clear parked graph cache when recreating schedulers (ggml-backend-meta.cpp:1989): fixed. A compute buffer being freed, as when sched_reserve recreates the schedulers, now drops the split parked under it and the active split's claim on it (ggml_backend_meta_forget_buffer, through a registry of the live meta backends), so toggling a lever that recreates the schedulers no longer grows the cache by a split per distinct buffer address. Not reproduced at runtime; no test toggles backend sampling under graph slots. Compile-checked on 0950784: cmake --build build-cpu --target llama-server ggml-rpc-server exit 0.

@lukekim

lukekim commented Oct 26, 2026

Copy link
Copy Markdown
Author

Note: this PR merged at 05:03Z with head 046d98c, before the second review round's commit 0950784 was pushed to the branch, so that commit is not in spiceai-b11803. Its content is in #9 as a follow-up: the backend-sampling decision re-checked after common_sampler_init (the grammar/response_format abort the Backend sampling job reproduced on 046d98c) and the parked-split cleanup.

lukekim added a commit that referenced this pull request Oct 26, 2026
lukekim added a commit that referenced this pull request Oct 26, 2026
…holds its tree (#7's final commit, merged above)
lukekim added a commit that referenced this pull request Oct 27, 2026
…freed compute buffer's parked graph split (follow-ups to #7) (#9)

* server: decide backend sampling again after the sampler is built; meta: a freed compute buffer drops its parked split

The backend-sampling decision moved ahead of common_sampler_init in 046d98c so the kept-sampler key could carry it, but common_sampler_init turns backend sampling off for a chain it builds with a grammar or a reasoning budget, which the backend cannot sample; the chain was attached anyway and `GGML_ASSERT(!gsmpl->grmr && "using grammar in combination with backend sampling is not supported")` aborted the server on a response_format request (the Backend sampling CI job, unit/test_chat_completion.py::test_completion_with_response_format). The decision is checked again after the chain is built.

A meta backend keeps one graph split per compute buffer while graphs come from two schedulers (graph slots). Recreating the schedulers freed their compute buffers without touching the splits parked under them, so toggling a lever that recreates the schedulers grew the cache by a split per distinct buffer address. A buffer being freed now drops the split kept for it, through a registry of the live meta backends.

* meta: lock the graph-slot state a buffer free touches from another context's thread, and the device and buffer-type registries

A meta buffer that is freed tells every live meta backend to forget the split kept for it, and the freeing thread can be
another context's compute thread (a model unloaded while a second model decodes, a drafter's scheduler recreated while the
target computes). That notification read active_buf and erased from parked while the owning context's compute path was
switching slots: a data race on the slot state. The slot state now has a mutex that both paths take; the compute path holds
it for the slot bookkeeping only.

The meta device registry (ggml_backend_meta_device) and the per-device buffer-type registry were static maps with no lock,
so two models loading on threads of their own, or a model and its drafter, raced on them too. Both take a mutex now; their
entries are std::map nodes, so the pointers they hand out stay valid after the lock is released.

test-meta-graph-slots drives the interleaving on a meta device over the CPU device: one meta backend alternates graphs
from two compute buffers while another, on a second thread, allocates, computes and frees graphs of its own. Under
ThreadSanitizer it reported the slot-state race on the previous commit and the registry races once that was locked, and
reports nothing with this one; on every build it checks both backends keep computing the right values.

* meta: own the buffer-type registry's contexts so they are freed at exit

The buffer-type registry held each context as a raw pointer allocated with new and never freed, so under
LeakSanitizer the meta-graph-slots test (label main, run by the address-sanitizer job) reported 64 bytes leaked in
2 allocations from ggml_backend_meta_device_get_buffer_type and exited 1. The registry now owns the contexts with
unique_ptr, as the meta-device registry beside it already does; the test exits 0 under AddressSanitizer and
ThreadSanitizer.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants