Repository navigation
server: preemption notices, asynchronous parks and exact concurrency together - #197
danielhanchen wants to merge 282 commits into
Conversation
…is kept alive Found by putting #190 and #192 together and then looking for the keepalive that #190 promises. It never arrives. Live, the 4B on one B200, two streaming completions that do not fit together so one is parked until the other finishes, every SSE line timestamped as it arrives: 6.19s B : preempted 16.82s B : resumed A 10.63 s silence on a stream whose whole point is that it says ": preempt- keepalive" every 2 s. Four-chat runs at -c 8192 and -c 4096 show the same: parks of up to 14.59 s by the server's own "resumed after" line, and not one keepalive on any stream in any run. server_response::send() notify_all()s a single condition variable for every result of every task, and server_response::recv_with_timeout() waited with wait_for(), which restarts on every wakeup. A reader waiting on a task that is producing nothing is therefore woken by every token every other task produces, and its wait_for() never elapses. On a server with any traffic at all the timeout is not a timeout: whoever waits for a quiet task waits indefinitely. A parked slot is the worst possible case for this, because a slot is only ever parked while the others are busy, so the keepalive was unreachable by construction. The same applies to the ordinary --sse-ping, which likewise only fired on an otherwise idle server, and to the should_stop polling in server_response_reader::next(), whose own comment says it happens every polling_interval_seconds and did not. Compute the deadline once and wait_until() it. Spurious wakeups then re-check the queue and go back to waiting for the same instant, which is what every caller already reads the argument as meaning. After, the same two streams: 6.26s B : preempted 9.26s B : preempt-keepalive 12.26s B : preempt-keepalive 14.26s B : preempt-keepalive 16.75s B : resumed Three keepalives across a 10.49 s park, at the 2 s period plus the reader's 1 s polling granularity. The probe is scripts/integ_keepalive_probe.py. No harness test: stories260K generates several hundred tokens a second, and at the context sizes the harness uses a park lasts two or three seconds, which is the keepalive period itself. Every sizing I tried either parked for milliseconds at a time as the pool oscillated around full, or did not park at all. A test that straddles the period it is testing would be worse than none, so the regression is pinned by the live probe above.
… needs A review of #192 pointed at the victim loop in update_preemption(). When the pool has no room for the step about to be built and no park is in flight, the loop issues the victim's asynchronous park and breaks. The cells are held until the copy lands, so the batch is built into a pool that has not got smaller, llama_decode returns 1, and the retry ladder halves n_batch to 1 in microseconds without ever polling the copy, ending in "Context size has been exceeded" for every slot. The synchronous path freed the cells before returning, so it could not do this. I could not reproduce it. Six live rounds on the 4B at -c 8192, four chats with 1000-token prompts and 2048 tokens each, with the fourth chat's prompt held back 20 s so it arrives into a pool the other three have filled, exact mode on and off, on a binary without this change: 4 of 4 every round, no context errors, and the retry ladder was not entered once ("failed to find free space" appears zero times in both server logs). The reason is that preempt_kv_reserve() counts an incoming prompt chunk before it is allocated, so the planner crosses the lookahead threshold an iteration before the pool actually fills, and every park in those runs was issued with the 80 cells of asynchronous runway still ahead of it, never at the hard threshold this is about. Committing it anyway, because the described state is real even if these workloads do not reach it, and the change is inert unless it is reached: * The victim loop goes round again instead of leaving, but only when n_used + PREEMPT_N_MARGIN > n_cells, that is when there is no room for the step itself rather than merely less than the asynchronous lookahead wants. The next pass reaches preempt_wait_in_flight() and waits for the park just issued, which is what that function was written for and no worse than the synchronous path. Short of the lookahead only, it still breaks, because parking early and letting the copy run beside the decode is the entire point of #192. * On llama_decode returning 1, an outstanding park is waited for before any batch width is given up. Halving n_batch returns no cells, so without this the ladder can walk to n_batch == 1 and end every request while the room it needed was one event query away. Safe at that point because the slot was detached before the batch was built, so completing its park cannot change what is about to be retried; that is also why update_preemption() itself is not called from here. New test, test_a_prompt_arriving_into_a_nearly_full_pool_parks_rather_than_ends_ everything: three slots generating near the ceiling and a fourth request whose prompt does not fit in what is left, which is the shape the existing tests miss because their victim holds almost no cells. The three are sized to oversubscribe the pool between them so the pressure does not depend on when the fourth arrives. It is kept for the shape it covers rather than as an attribution: it passes either way, and the attribution above was done at live scale.
…is kept alive Found by putting #190 and #192 together and then looking for the keepalive that #190 promises. It never arrives. Live, the 4B on one B200, two streaming completions that do not fit together so one is parked until the other finishes, every SSE line timestamped as it arrives: 6.19s B : preempted 16.82s B : resumed A 10.63 s silence on a stream whose whole point is that it says ": preempt- keepalive" every 2 s. Four-chat runs at -c 8192 and -c 4096 show the same: parks of up to 14.59 s by the server's own "resumed after" line, and not one keepalive on any stream in any run. server_response::send() notify_all()s a single condition variable for every result of every task, and server_response::recv_with_timeout() waited with wait_for(), which restarts on every wakeup. A reader waiting on a task that is producing nothing is therefore woken by every token every other task produces, and its wait_for() never elapses. On a server with any traffic at all the timeout is not a timeout: whoever waits for a quiet task waits indefinitely. A parked slot is the worst possible case for this, because a slot is only ever parked while the others are busy, so the keepalive was unreachable by construction. The same applies to the ordinary --sse-ping, which likewise only fired on an otherwise idle server, and to the should_stop polling in server_response_reader::next(), whose own comment says it happens every polling_interval_seconds and did not. Compute the deadline once and wait_until() it. Spurious wakeups then re-check the queue and go back to waiting for the same instant, which is what every caller already reads the argument as meaning. After, the same two streams: 6.26s B : preempted 9.26s B : preempt-keepalive 12.26s B : preempt-keepalive 14.26s B : preempt-keepalive 16.75s B : resumed Three keepalives across a 10.49 s park, at the 2 s period plus the reader's 1 s polling granularity. The probe is scripts/integ_keepalive_probe.py. No harness test: stories260K generates several hundred tokens a second, and at the context sizes the harness uses a park lasts two or three seconds, which is the keepalive period itself. Every sizing I tried either parked for milliseconds at a time as the pool oscillated around full, or did not park at all. A test that straddles the period it is testing would be worse than none, so the regression is pinned by the live probe above.
find_slot() and set_input_pages() each rebuilt the (sequence, logical page) to physical page map from a scan of every live cell into an std::map, so the paged allocator did O(cells log pages) work twice per ubatch, twice per decode step, and the CPU cost grew with the size of the pool rather than with the number of pages in it. Keep the ownership in a flat vector with one entry per physical page, claimed in apply_ubatch() as cells are placed and marked dirty by the paths that remove them, seq_rm(), seq_keep() and clear(). prepare() snapshots it alongside the cells so that undoing a speculative placement puts back what the allocator knew rather than forcing a rebuild. Both readers now build their lookup from one entry per page: 32 entries at -c 8192 and 256 at -c 65536, against 8192 and 65536 cells. find_slot also stops allocating a cells-sized bitmap per call. Nothing about the placement policy changes, and the derived-from-live-cells rebuild is still there and still authoritative: LLAMA_KV_CACHE_DEBUG=1 runs it on every read and asserts that the maintained ownership says exactly what the cells say. Four chats, 937 token prompts, 1536 tokens each, ignore_eos, speculation off, --parallel 4 --kv-unified --flash-attn on -ngl 99, three interleaved pairs on one B200, medians of four-chat aggregate decode tok/s: -c 8192 off 151.03 exact 136.70 0.905 before -c 8192 off 150.83 exact 137.94 0.915 after -c 65536 off 158.34 exact 136.29 0.861 before -c 65536 off 159.48 exact 143.62 0.901 after So at 32 pages it is worth about a point, and at 256 pages it is worth four, which is what a cost that followed the cell count and now follows the page count should look like. With LLAMA_KV_CACHE_DEBUG=1 and LLAMA_SERVER_PREEMPT_EVERY=32, which parks and restores every slot every 32 tokens and so exercises every path that marks the ownership dirty, no assert fires and P0 stays byte identical to its solo reference.
…he cache A review of #194 pointed at the new GGML_ASSERT in llama_kv_cache::seq_cp, and it is right. Reproduced on this branch with the 4B on one B200: LLAMA_EXACT_CONCURRENCY=1, POST /completion {"n": 2} -> llama-kv-cache.cpp:458: GGML_ASSERT(!exact_pages || seq_id_src == seq_id_dst) failed, through server_context_impl::decode -> common_memory::seq_cp -> process aborted, the next request gets connection refused With the mode off the same request is served normally, so this is reachable by any client of an exact-mode server and takes every other request on the machine with it. Two changes: The server refuses the request. n_cmpl > 1 works by copying the parent's cells to a second sequence id, and exact mode gives a page to one sequence, so there is nowhere for that copy to land. Rejecting it where the task is built turns it into a 400 with a reason. The check reads LLAMA_EXACT_CONCURRENCY from the environment, the same way the KV cache, the batch splitter and the CUDA backend each do, because the answer is needed before a context exists and the mode has no other representation. The cache stops aborting. seq_cp, seq_add and seq_div log an error and return instead of asserting, so a caller this branch does not know about degrades to a refused operation rather than killing the server. The guards also move below the shared-cells early return, which the asserts sat above: a draft cache forwards these calls and copies nothing of its own, and it should not be judged by a rule about cells it does not own. After: the n=2 request returns 400 on both /completion and /v1/completions, the server stays up, and a following ordinary request returns 200.
Under exact concurrency the KV cache hands out 256-cell pages, one to each (sequence, position / 256) pair, so a sequence can hold up to 255 cells that nobody else can be given. A preemption planner that counts tokens does not see those cells: it believes there is room, never parks anybody, and the pool fills until every request ends in the old context error. llama_memory_i gains alloc_granularity(), defaulting to 1 so no module that allocates a cell per token changes; the KV cache returns its page size under exact mode and the hybrid memory forwards to its attention half. llama_memory_alloc_granularity() exposes it. The server side of this, rounding its planner figures by that value, follows separately.
Exact mode and #184's preemption planner cannot both be right about how full the pool is, and on this branch they are not. Reproduced with the 4B on one B200, LLAMA_EXACT_CONCURRENCY=1, four chats with 1000-token prompts generating 2048 tokens each at --parallel 4 --kv-unified -c 8192 --spec-type draft-mtp --spec-draft-n-max 2, no forced-park knob, three rounds: 0 of 4, 0 of 4 and 1 of 4 completions, 12 "Context size has been exceeded", 0 parks and 0 restores. Nothing was ever parked. preempt_kv_used(), preempt_n_need() and preempt_kv_reserve() count tokens, and exact mode's allocator hands out 256-cell pages, one page to one (sequence, position / 256) pair. Four sequences can therefore be holding up to 1020 cells that no other sequence can be given, and the planner, seeing room in tokens that find_slot cannot find in pages, never reaches the threshold that would park anybody. The retry ladder then halves n_batch to 1 and ends every request, which is the pre-#184 behaviour that preemption exists to remove. Ask the memory how it allocates instead of assuming. The server reads llama_memory_alloc_granularity() once at load and rounds: preempt_kv_used() charges every slot's tail page in full, because a page belongs to one sequence however little of it is used preempt_n_need() rounds what a resume must be given, since a restore takes fresh pages preempt_kv_reserve() reserves the cells the next step ADDS rather than its tokens, because on a rounded used figure a step is free until it crosses a page boundary and costs a whole page when it does, and that crossing is the only moment the pool can run out preempt_n_margin() rounds the spare cells up to a page, since a margin of eight is no margin at all where a step can cost 256 With a granularity of 1 every one of these is the arithmetic it was, which is pinned by static assertions on the two rounding helpers rather than left to be read: at 1 they are the identity, so nothing changes with the mode off. After, same configuration and three rounds: 4 of 4 completions each round, 3, 4 and 4 parks and the same number of restores, no context errors, and P0 byte-identical to its solo run in all three. The same run with exact mode off is also 4 of 4 with 3, 2 and 2 parks, and its planner figures are still the token counts they always were. LLAMA_SERVER_PREEMPT_GRANULARITY overrides the figure the memory reports. It is a test knob, next to LLAMA_SERVER_PREEMPT_EVERY: the paged attention kernel needs a head size of 256, which the harness model does not have, so this is the only way to reach the paged arithmetic from tools/server/tests. The new test drives two slots over a 256-cell pool at a granularity of 64 and asserts every figure the planner logs is a whole number of blocks. Counting tokens the same run logs kv 119/256 and wanted 249; counting cells it logs kv 64/256 and wanted 256.
…de-preemption-integration
…e-preemption-integration # Conflicts: # tools/server/server-context.cpp
…n-integration # Conflicts: # tools/server/server-context.cpp
Under LLAMA_EXACT_CONCURRENCY a decode step with speculative drafts cost about twice what the same step cost with the mode off, and the mode itself was not where the time went. The batch splitter isolated any sequence set with more than one token left to place, on the reasoning that such a set is a prompt whose prefill would otherwise share a ubatch with other sequences. A speculative verify batch is such a set too: with two MTP drafts every slot brings three tokens, so each slot's verify step became a ubatch of its own and every decode step ran the whole graph once per slot. The splitter now isolates by width. llama_set_exact_decode_tokens() tells the library how many tokens one sequence contributes to a decode step, one plus the draft length, and only a set with more tokens than that left to place is a prompt. The server already derives the CUDA column bound from the same figure, so a grouped verify batch is at most that wide and the column policy keeps every column at its batch-of-one arithmetic. The default of 1 is the previous behaviour. On the CUDA side the column policy recomputed a batch above the bound one column at a time, reading the weights once per column. A column's result depends on the implementation and, for MMVQ, on the warp count of the launch, and neither depends on the other columns in the launch, so the split now runs in the widest slices whose configuration matches a batch of one: a twelve-column verify batch is three MMVQ launches on a table whose configuration holds up to four columns, rather than twelve. Mode 1 of GGML_CUDA_BATCH_INVARIANT still recomputes one column at a time. Qwen3.5-4B, four chats with two MTP drafts each, exact mode on: byte identical to the solo run in every round, with and without a forced park every 64 tokens, at about twice the previous aggregate rate. Qwen3.6-35B-A3B, the same cell: identical in every round at 92 to 96 tok/s against 55 before. MUL_MAT op tests 1217 of 1217 under the mode; server preemption tests 7 of 7.
|
Merged #194's c6c3cb6 as ef257d7. It fixes the speculative cost the Cost section measured: under exact mode the batch splitter treated each slot's three-token verify batch as a prompt and gave it a ubatch of its own, so every decode step ran the graph once per slot. Prompts are now isolated by width and the column split runs in batch-of-one-equivalent slices. Two MTP drafts, four chats, the same full-pool shape: 0.74 of the mode-off aggregate against 0.45 before, byte-identical to the solo run on the 4B and the 35B with and without parks. The 16 server tests pass on the merged binary. The Cost section is updated. |
…in one launch Under the batch-invariant policy a MUL_MAT_ID with several tokens was recomputed one token at a time, re-entering the op once per token, so a decode step of four slots with two MTP drafts each cost twelve serial expert launches per projection. The single-column MMVQ kernel already carries a sample axis. With ids, a sample is now a token: the wrapper launches the ncols_dst = 1 configuration once with the tokens on the z axis, y advancing by a token per sample and the expert index read per sample, so every (token, expert slot) block runs exactly the instructions the token alone would run, on the same data, with the same warp count, row split and K loop. Only the block indices differ. The stock single-token launch has one sample and is unchanged, as is every launch without the knob. A quantized expert matrix takes this path for any token count under the knob; other types still go one token at a time. Single-op probe, token 0's slice against its own single-token run, knob on, Q4_K, Q5_K, Q6_K and Q8_0 at K 2048 in both the gate-up and the down layout and Q6_K at K 512 (the shape whose multi-token kernel differed), 2 to 12 tokens: 0 differing elements in every one of 99 comparisons.
|
Merged #194's 379ca5d as abccc6e: on mixture-of-experts models the exact mode no longer re-enters every expert projection once per token, so the 35B decodes at the mode-off rate within noise with and without MTP drafts, byte-identical to the solo run with and without parks. The 16 server tests pass on the merged binary. |
…t mode With prompts isolated by width, sets at or below the decode width were grouped whatever their token counts, and the equal-length expansion then placed a three-token verify step beside a two-token one as two tokens now and one later. Attention and the gated delta net do not care, and the 4B reads identical either way, but a memory that reduces over a chunk of tokens, such as a chunked state space scan, would sum in a different order than the solo run's single three-token ubatch. A set now joins the ubatch only if it has as many tokens left as the first set taken, so every set in a ubatch finishes in that ubatch and each sequence's step has the shape it has alone. Sets with a different count wait for a later ubatch. Speculative verify steps of equal width, the common case, still share one ubatch. 4B, two MTP drafts, three rounds each: identical to the solo run with and without a forced park every 64 tokens; speculation off with forced parks identical; server preemption tests 7 of 7.
…mption-integration
Three gaps found in review, all of the same kind: exact mode accepted an input it could not implement and either ran something else or asserted. A model whose K or V heads are not 256 wide passed every load-time check while the paged attention kernel refuses such heads, so attention ran unpaged on the CPU with the mode reporting itself as on. The load now fails with the head widths in the message, as the other preconditions do. MLA layouts are refused the same way. A token carrying several sequence ids reached the page placement and hit an assertion there. init_batch now refuses the batch with a logged error and the failed-prepare status, for the unified cache and the hybrid one. On a hybrid memory the attention half already refused a cross-sequence copy, a position shift and a position division under the mode, but the recurrent half went ahead, leaving the two halves describing different states. The hybrid memory now refuses all three before either half is touched. The harness model (8-wide heads) is now refused at load under the mode instead of loading unpaged; the 4B is unaffected (two MTP rounds identical); server preemption tests 7 of 7.
…mption-integration
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
supports_op keeps the scheduler from sending a page table over RPC, but the server rebuilds whatever graph a client submits and computes it without asking, so a paged node would reach a backend that trusts its page ids and counts. graph_compute now rejects a FLASH_ATTN_EXT node with src[5] and drops that connection. test-rpc-paged-fa sends the graph from its own client against a CPU server: on the previous commit the paged graph computes, here it is refused and the server keeps serving.
…f asserting The paged pool files every cell under its position's page, and find_slot asserts the position is not negative. A sequence state with a negative position, from a corrupt or foreign file, reached that assert and aborted the process. state_read_meta now fails the restore through its error path, so llama_state_seq_set_data returns 0. test-exact-pages patches the first position of a saved sequence to -1: on the previous commit the restore aborts on the assert, here it returns 0 and the unpatched state still restores.
…rror return state_read_sinfo refuses a whole-context restore before reading a byte, so the assert in state_read_meta's whole-cache branch is not reachable in this mode. test-exact-pages now holds that in place: llama_state_set_data on a saved whole-context state returns 0 and the process lives.
…backend_device_i Appending event_query to ggml_backend_device_i changed its layout without a backend API version bump, so a backend module built against the old layout would load and the core would read the device's reg pointer as event_query. A fork-side bump would instead collide with upstream's next one. The member and every NULL initialiser of it are gone, so the interface is upstream's again; the CUDA backend returns its implementation from get_proc_address as "ggml_backend_dev_event_query", and ggml_backend_event_query() and ggml_backend_dev_supports_event_query() look it up there, keeping the blocking fallback for a backend that does not publish it. test-event-query checks that a CUDA device reports the query and that every device that does reads a completed event as complete.
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
A grouped child continues from the parent's cells through seq_cp, which LLAMA_EXACT_CONCURRENCY refuses (a page belongs to one sequence), while copy_prompt_to() still clones the parent's prompt metadata. The child then decoded its suffix at the shared position with no KV prefix behind it. Each task now keeps its whole prompt in exact mode.
…eloaded The whole-context restore is already refused under LLAMA_EXACT_CONCURRENCY, but llama_state_get_size/get_data and llama_state_save_file still succeeded, so llama-completion --prompt-cache wrote a session that made the next run fail to load it and exit. The save now fails the same way, before the file is opened, so no session is left behind and the next run starts fresh. Per-sequence saves, which the server uses, are unchanged.
…onse A multi-prompt /v1/completions request is one ordinary task per prompt, each of which can be parked; the non-streaming OAI merge kept only the first result's preempt object, so parks of the other prompts were dropped.
|
Codex Review: Didn't find any major issues. 🚀 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". |
# Conflicts: # src/llama-context.cpp # tests/test-state-restore-fragmented.cpp # tools/server/server-context.cpp # tools/server/tests/unit/test_preempt.py
The token was sampled before the park and post_decode discards the output, but a backend sampler runs on every output of its sequence and, at one output per sequence, draws its uniform from the stream's RNG. Every recompute park left the stream one draw ahead.
|
Codex Review: Didn't find any major issues. Bravo. 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". |
…r in exact concurrency mode The weight check only looked at blk.* tensors and the output head, so an --override-tensor that kept output_norm, cls or cls.output on the host passed while those ops ran with a batch-width-dependent placement. Exempt only the input-layer tables (token_embd and friends), which feed GET_ROWS.
Mark pytest.skip/pytest.fail calls the way the other server tests do, since ty misreads their positional reason, and type the streamed prompt as text or token ids.
The paged template parameter adds one bool to flash_attn_ext_vec's mangled name, so the already ignored D=256 q4_0 instance no longer matched its entry. Its register use is unchanged.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
With the same prompt twice, the parked one could come back on the slot the first had just finished on and reuse its cached cells, so prompt_n was 1 (seen on the windows runner).
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 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". |
With UNSLOTH_LLAMA_ADMISSION_PREEMPT=0 and no budget named, the stand-down wrote nothing, trusting the server to park nothing by default. A build from before unslothai/llama.cpp#197 has the flag and parks on an implicit 8192 MiB, so the server kept parking while Studio recorded parking as off. Write LLAMA_ARG_PREEMPT_RAM=0 whenever the probe confirmed the flag, as an inconclusive probe already does; it is the default from #197 on.
Stacked on #184. This branch merges #190 (park notices on the stream), #192 (park and restore copies off the decode loop) and #194 (opt-in exact concurrency) so they can be tested together, plus the fixes that only showed once they shared a binary. It is rebuilt from the three branches' heads as they move.
Correction, 2026-09-07. The sentence that used to stand here said every fix found on this branch had been carried back to the PR it belongs to. That is no longer true and it should not have been left standing.
git log --no-mergesagainst the three merged heads returns 16 commits unique to this branch, nine of them from 07 September: f8fdf06, 951a219, 57efd21, 7e424ad, 7549c68, 4cf9baf, 00855c2, bb510f5, 09cecf4. They share the park and resume bookkeeping between the copy paths, count the KV reserve in one pass, build the async state io on the host io, and share the preemption test setup. Each one cuts across #190, #192 and #194 together, so they cannot be split back into those branches cleanly.That makes this branch the merge target for the three, not a scratch integration of them. #190, #192 and #194 stay open as the reviewable layers, and
gh api compareconfirms this branch contains all three in full (#190 and #192 report ahead=0; #194 differs only by a merge commit with no unique content). It does not contain #186, which still holds four commits of its own including 296 lines oftest_preempt_hybrid.py, so the preemption stack currently has two live heads and #186 also needs another merge from #184, which it is four commits behind.Rebuilt over
75944db80from the current heads:1c5aa4904feat/server-side-preemption-notify(#190,5a791e03c)51eca0837feat/server-side-preemption-async(#192,888603d03)70d49bfacfeat/exact-concurrency(#194,da8556d31)ef257d7b8feat/exact-concurrency(#194,c6c3cb671): speculative verify batches stay grouped, sliced column splitabccc6e95feat/exact-concurrency(#194,379ca5d42): one launch per expert projection under the knob instead of one per tokena7db6262afeat/server-side-preemption(#184,50b617ae4): parked slots come back head of line by park time3f817d880feat/server-side-preemption(#184,8057a74af) andfeat/exact-concurrency(#194,f4e45646d): resume-order knob logged at load; equal-width grouping under exact modee8ab02c94feat/server-side-preemption(#184,2a7e277ab): a parked sequence that cannot fit the pool alone is failed instead of parked for ever; margin waived when nothing is residentdb9558696feat/exact-concurrency(#194,adeed654b): head widths other than 256, tokens with several sequence ids, and hybrid cross-sequence edits refused by name under exact mode70b874c33feat/server-side-preemption-async(#192,01dfecc5e, carrying #18484311fd3dand6dbc4e7b6): when the KV-full retry ladder runs out, resident slots are rewound to the cache boundary and the smallest parked instead of every slot getting the context error; a batch holding a draft is never narrowed through the groupa7e661c14feat/exact-concurrency(#194,c89d87db5): the same, with the page-rounded margin1130aed0b47ef8de54and #1946573242a1(#18486845c15e): a batch holding a draft is narrowed the old way when there is no budget to park intob89302b25feat/server-side-preemption-notify(#190,5864dae95): a park made as a last resort sends the stream comment the planner sends, so Studio shows the pausef8ec5665afeat/server-side-preemption-async(#192,cd1cd4e6d): the lookahead margin counts a slot being restored5e0f99aedfeat/exact-concurrency(#194,0c9fc0ed8): every context reports the widest decode step it can build, so the column bound covers direct library users3fc833954301f480c0, #1920303888e8, #19408e10dabb(#184662ec2029): the planner and the last resort step aside for a context without memory7c8a6d51576baf1a68, #192cac5ee6c0, #19467063e476(#184a9b712eee): unlimited budget enables the last resort; per-slot draft bound for restores and reservations; shared prompt charged once per family; reused slot charged its prefix; context shift before the planner measures800e166ad7fb42b582and #19446e7fa742: parked prompts of a multi-prompt stream kept apart; ngram-cache verify width; DFlash refused by name; an explicit bound below the decode width refused at context creation; width replayed to backendseb428268c53c59a109, #1928d74efbb2, #194b7ace528f(#18464a5064ef): a resident cycling through context shifts takes turns with a parked head9391aa71e356978a26, #19242e536970, #194dbd82ca5e(#1846744b3d9f): a non-causal context with a cache refused at creation under exact mode; one page boundary per waiting prompt slot in the reserve cap; a stream parked before its first token starts with the notice; the rotation park announced; a reused slot trimmed to its shared prefix before it is sized or parked; a round with a context shift waits for every copy in flight; the decode width of every context follows the token figure645d406dd3306d4b50, #192ad3856ae9, #194d4e3fc8a6(#184a1c34dad2), on top of6af0d4e99: a reused slot's need counts from its shared prefix and its trim is safe for memories without partial removal; a waiting child is charged its own cache; equal-count grouping stays on for recurrent and hybrid memories; a width the explicit column bound cannot cover is refused; a restore landing inside the context-shift wait sends the resume notice276dd25296fb0b91c5:LLAMA_SERVER_PREEMPT_POLICY, a test knob to compare victim choices on one workload (off unless set)ecdb0f5317efef20fa, #1922ba0dcf5f, #194bf00ac38a(#184a7a04c2a9): the rotation parks the resident that lets the head in (page-rounded here); soft-capped attention refused at load; width reports serialised and monotonic in the backend; the token figure never lowered089fedd923d179fd0b, #19202a3e11d4, #19498fe86dfc(#18464a3f6e7d): a parked slot, or one whose copy is in flight, survives an aborted round; a rotation counts the head's bytes as leaving; the exact setup runs before any context exists; one lock for the token figure, the sequence count and the widthd72e2a40da06419d00, #192e432b15c2, #19449c66c5bd(#18455f04bbd6): the leader measured by what a reused slot keeps; no rotation while a park is copying and an asynchronous rotation park re-examined when it lands; the rotation budget under asynchronous copies and buffers returned over budget; the cache-reuse shift waits for copies in flight; an isolated ubatch takes only sets that finish in it; page-aware margin at every step testb4a5f18d82b4a69122, #1942f2258dc0: a whole-context restore under exact mode is refused before it can clear the cache; the width is published once construction succeeds; the page table is refused on every backend that ignores it; DSpark refused with DFlash; a transfer that fails part way posts no copies; pageable host memory parks synchronously; no transfer for state that is not on a device; the runway rounding explained48f7d7c0b1d528856f, #192faa3dd3f7, #19423c9dc2ef(#184270fdd6f3): test that a parent and child alone in the pool get the context error and the server lives0611fd99ba4b62f2be, #194918a8bf4f: a park buffer that comes back pageable parks synchronously from then on; the graphs after a restore wait for its copies on the device; the exact-mode cache asks the device whether it runs the paged attention for the layer rather than trusting the backend's namef737e6d49294d2a912: idle parked RAM is given back when another slot needs to park, so a budget that holds one sequence is not spent for good by the first restore; the copies of a park or restore wait for the compute stream on the device instead of draining the hostbf0f731273800ddee9through #190a158200deand #192dffa102e3: a pure recurrent cache is served without preemption; a rotation holds both states at once, so the RAM cap is asked for the resident's state in full and a budget that holds one sequence but not two does not rotate, said once per parka140e80c881eec0bb3through #190ce02834c4and #192a5749d11b: the copies wait for a fence the context records after every decode, so restores issued in one pass run independently on the device; a started slot's reservation counts from the prefix it keeps (page-rounded here, the step starting from that prefix)e36a4b6ddaf560907bthrough #1905ecdba815and #192a56d49e1f: the context shift and the planner run inside the guarded part of the step, so a failure there ends the affected slots rather than the loopb0fae413a00b27d2df, #1904918294ff, #1928cb58dfdfplus 4b91744 here: what a started slot keeps is decided by the batch builder's rule (no caching, aLoRA cutoff); a parked stream keeps a shorter ping it asked for; staging counted by what the buffer charges; fences after the layout check; transfers only where a park can happen; a decode that fits goes ahead beside a park in flight instead of waiting for it; a slot restoring into the prompt phase counts in the page-boundary cap0d39b88baad89538d2, #190801e29ad1, #192114e230ab: the resume order read on every load; the shift wait runs before the draft is asked for, so the draft cache shifts after the copies have landed; the last transfer takes the fences with it7fdb58bb3301caa31d, #190929809ffa, #192b1a31b42d: the resume order belongs to the context and the recurrent flag is assigned on every load; the shift wait runs before the decode as well as before the draft; a context freed with live transfers drains and disowns them1bf8519163c99fafdf, #190a33c56397, #19258c6e3329: the pool is measured by the cells each slot physically holds (page-rounded here), and when nothing fits every started slot is trimmed to the prefix its request keeps before idle slots are cleared, so a resume is not attempted against cells the batch builder has not yet released474569ca390a5094d3and #194b4b0f9bd7: a started slot's prompt is validated before it can be parked, so a request the STARTED block would reject is never given a notice ahead of its non-stream error; shorter comments from #194, the conflicting hunks keeping this branch's textf8fdf063a951a21931tobb510f556preempt_park()serves the four park sites and one pair of helpers the three copy completions, the kv reserve is counted in one pass, the two test files share their server setup and stream readers (29 tests and every assertion unchanged), the async host io derives from the sync one, one-reader wrappers and the target-and-draft transfer repeats go. 1050 lines fewer. Verified at each commit by the suite, at the end by the seq-copy and fragmented-restore ctests on the 4B, the exact-mode soak identical 6 of 6 with forced parks, and test-backend-ops under the mode09cecf4f0The four fixes below now come in with those merges. Two conflicts had to be resolved by intent rather than by text: at the KV-full park site the notice and the new host-memory report both belong, in the order the forced-park site already uses; and #194's synchronous planner meets this branch's asynchronous one, where the resolution keeps the asynchronous margin and its
RESTORINGreservation and takes #194's compile-time-checked rounding helpers, so the two planners share one set of arithmetic and the synchronous branch of the margin rounds as well.Summary
Three merges and four fixes. Merging #190 into #192 needed intent rather than text: git placed two of the three notice sites after the asynchronous early-outs, where an asynchronous park or restore would have announced nothing. The rule applied is that a park is announced when the slot stops taking part in a decode, on entering the copy-out state, and a restore when it starts again, when the copy back lands; the keepalive therefore spans all three in-flight states. #194's page allocator and #192's park compose without change: a park removes whole pages, both in-flight states hold live cells, and a restore allocates through the page branch of the slot finder.
Fixes found here
llama_memory_i::alloc_granularity()now reports the page size and the server rounds its four planner figures by it. After: 4 of 4, two parks per round, the parked chat's bytes unchanged.nabove one reached a cache assert under exact mode and killed the server. It is refused with a 400 at task build, and the cache logs and returns instead of asserting.--sse-ping.Results
Qwen3.5-4B, two MTP drafts,
-c 8192, four slots, seed 0, temperature 0, forced parks every 64 tokens, all three features on, re-run on the rebuilt branch: 4 of 4 in three rounds, 28 parks and 28 restores per round, seven park and seven resume notices on every stream, and the observed chat byte-identical to its solo run in every round, at the same sha2563922db5817b706aa...the branch gave before the rebuild. Survivor stall at a park 52 to 67 ms and at a restore 39 to 85 ms with exact mode on, against 76 to 78 and 57 to 64 with it off, on a shared GPU.Qwen3.6-35B-A3B through Unsloth Studio on an unshared GPU: exact mode loads with Studio's own launch args; a chat's bytes are unchanged by three different neighbours across three rounds and by seven forced parks per stream, while the same cell with the mode off diverges at byte 488; four API chats and eight GUI chats in Chromium and WebKit all completed with zero errors and every one of 21 natural parks lasting up to 96 s resumed with the paused label shown.
Cost
Re-measured on this tree, interleaved: three on/off pairs, four chats, prompts of 937 tokens as the server counts them, 2048 tokens each with
ignore_eos,-c 8192, four slots, unforced, medians of three.70d49bfac70d49bfacef257d7b8ef257d7b8All six runs finished 4 of 4 with parks and restores and no context errors. The 37 to 42 percent this paragraph used to quote was measured on #194's reviewed head and is gone with speculation off: #194's own fixes stopped one prompt serialising every concurrent decode for the whole prefill and dropped the default column bound from a fixed 16 to the width a decode step can reach. What is left there is the CUDA column policy rather than the page bookkeeping, which #194 measures at 0.79 for the kernel half alone against 0.92 for the whole mode.
The speculative cost at
70d49bfacwas the batch splitter, not the column policy: under exact mode it isolated every sequence set with more than one token left as a prompt, and a slot's three-token verify batch is such a set, so each decode step ran the whole graph once per slot. #194'sc6c3cb671isolates by width (llama_set_exact_decode_tokens, one plus the draft length) and slices the column split into batch-of-one-equivalent launches, which is the 0.45 to 0.74 in the table, measured on the #194 tree and carried here byef257d7b8. What remains is the sliced column policy on a twelve-wide verify batch plus paged attention. One B200 shared with another tenant throughout, so the ratios are the result and the absolute figures are not.Tests
Server harness 31 of 31 (27 preemption, 4 notify, 22 parametrised cases), the fragmented-restore and sequence-copy ctests on CUDA with the 4B, and
test-backend-ops5234 of 5234 in exact mode.Follow-up: seven fixes and fewer tests
Nine fixes, each checked against the previous head.
llama_memory_update()applies the recorded shift on the target and the draft before the planner runs, so every park site sees applied state; the reviewer's harness goes from 26621 of 71864 checkpoint bytes differing to 0, and the token-identity test passes./slotsreportsis_preemptedonly for a slot whose cells are gone and a newis_transferringfor a copy in flight, so a reader counting residency keeps counting a transferring slot.--preempt-ramcannot hold a victim, the park drops the victim's cells and keeps its tokens, sampler and counters, and the resume re-prefills the tokens through the ordinary prompt path and carries on from the already-sampled token. Both the planner and the last resort use it, so the stock all-slot context error is unreachable while another slot can be parked. Two 2000-token streams under--preempt-ram 1go from both erroring to both finishing; a forced park at 1800 tokens with 1819 re-prefilled produces output bit-identical to the unparked run.-c 400 -b 64go fromfailed to process mtmd chunkto both completing after a park.Fewer tests. The two server test files go from 874 lines and 29 tests to 731 lines and 31 tests (22 parametrised cases plus the nine tests above), with the setup, prompts and stream readers shared and the near-duplicates folded into parametrisations. The survivors were checked against four scratch mutations (no victim ever picked, the pre-fix cell count, the started-slot validation gate removed, the park notice removed); each was caught by the intended test. Two behaviours that had no test before are written rather than kept: the physical cell count of a started slot, and the parked keepalive.
One thing found on the way, not of this PR: a 1900-token prompt processed in 32-token batches after a 2000-token decode hangs the CUDA build with graphs enabled, on master as on this branch, with
GGML_CUDA_DISABLE_GRAPHS=1or a larger batch it completes. The recompute test re-prefills in one batch for that reason.Verified on the merged tree: the two files 31 of 31 on CUDA with the recurrent, hybrid and M-RoPE models supplied and nothing skipped; the upstream completion, context-shift, vision, basic, stream and kv-keep files 73 passed and 1 skipped with the one pre-existing failure, a wording regex on the tiny model that fails on master too; the CPU-only build serves the recompute park and re-prefills 1910 tokens in 32-token batches; the exact-mode soak on Qwen3.5-4B with two MTP drafts and forced parks every 64 steps identical in 6 of 6 rounds against the solo run at 295 to 300 tok/s aggregate, 164 parks and 182 resumes with zero asynchronous markers and no context error. Live through Unsloth Studio: four GUI tool chats at 8k finished 4 of 4 with 9 parks and 9 resumes, and
unsloth runat 16k with two MTP drafts and exact concurrency finished 4 of 4 at 191 tok/s aggregate with 5 parks and 5 resumes, no context error in either.llama_decodeas 1, the code callers retry on, when it can never succeed. It is rejected during batch validation with -1 now, before the memory is asked.Round 23
/propscarriesexact_concurrency--preempt-ramto the poolRound 24: audit fixes and the exact-concurrency follow-ups
Six fixes from an isolated review of this head, each with a test, plus the three code fixes #194 gained since this branch took it (cherry-picked: the weight placement check at context creation, the allocation-granularity comment, and per-page live counts so a removal that empties nothing leaves the page index alone, with
tests/test-exact-pages.cpp).keep_firstdropped or kept the wrong tokensrewind_to_cacheconverts withsize_up_to_pos, steps back to the start of a media chunk it would cut, and asserts the result;tests/test-server-tokens.cppbuilds a 256-token, 16-position image chunk and checks the conversionLLAMA_SERVER_PREEMPT_FAIL_SAVE=Nfails the Nth save for the test)n_ubatchchunks unless the rest fits, a chunk a neighbour would cut short is deferred, and a batch too small to hold a decode step plus one ubatch warns once; measured identical ubatch grids alone and beside three decoders: recomputedfollows the: resumedof such a resume,llamacpp:preempt_recompute_totalin/metrics,n_recomputeper/slotsentry, andpreempt: {parks, recomputes}on every final completion object; documented in the server READMEmin(params.n_max, dp.n_max); with one token of allowance left the unfixed build logged the truncation, the fixed build none, and a 4-token draft got three times faster/propsstill reporting the modecommon_exact_batch_geometryrefuses the geometry at init, naming the batch size that would work (-b 514for a 512-token ubatch and two slots); the warn path is gone, a prompt that does not fit whole waits for the next iteration;tests/test-exact-geometryand a server test--preempt-asynchelp said the slots that keep running do not wait for a park: preemptedat park time on every streaming surface (320 ms before the resume in the test scenario); now stated in the README and pinned by a test parametrised over/completion, chat, responses and messages that the notice arrives before the first data linesse_ping_interval; ten consecutive runs passVerified on one GPU with Qwen3.5-4B:
test_preempt.pyandtest_preempt_notify.py39 passed, 5 skipped;test_metrics.py10 passed;test-server-tokens,test-exact-pages(also underLLAMA_KV_CACHE_DEBUG=1) andtest-state-seq-copypass;-ot attn_q=CPUunderLLAMA_EXACT_CONCURRENCY=1is refused namingblk.0.attn_qkv.weightinCUDA_Host; four exact-mode sequences of 256 greedy tokens with a forced park every 64 are identical to their solo references (12 parks, no recompute). The exact and MTP tests skip unlessLLAMA_SERVER_TEST_EXACT_MODELandLLAMA_SERVER_TEST_MTP_MODELname a model. Not covered end to end: the multimodal rewind, since the only local VLM has media positions equal to its token counts.