Skip to content

server: preemption notices, asynchronous parks and exact concurrency (pin branch on b11540) - #260

Open
danielhanchen wants to merge 5 commits into
base/upstream-1e6f04a75from
pin/server-side-preemption-b11540
Open

danielhanchen wants to merge 5 commits into
base/upstream-1e6f04a75from
pin/server-side-preemption-b11540

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Server-side preemption, preemption notices, asynchronous parks and exact concurrency, ported onto upstream b11540 (1e6f04a) as a pin branch. It replaces #210 as the commit pinned for this feature. #210's branch sits on b10871 plus the Inkling pin, so its history carries an old ggml-org#25731; merging a newer tag into it was refused by the pin-set sim on 10 files. This branch carries only the preemption change set on an upstream commit, so diff(merge-base, pin) is exactly what gets pinned and it composes with Inkling and DiffusionGemma additively.

What it does

With --kv-unified every slot is told it may use the whole context while the slots share one cache, so chats that each fit can be admitted together and then collide; upstream answers a full cache by failing every slot it is decoding. With --preempt-ram N (default 0, which behaves exactly as upstream) the server instead parks a slot's KV in up to N MiB of pinned host memory, or drops it for recompute when that is full, and restores it when room frees, FIFO by park time. Streams are told: : preempted <i>, : preempt-keepalive every two seconds while parked, : resumed <i>. Exact concurrency (LLAMA_EXACT_CONCURRENCY=1) stays an environment opt-in.

Commits

  • b91b2f0: the preemption delta alone on b11540. Upstream's CUDA matmul dispatch is left byte-identical (the batch-invariant split is a hook in front of it); F32 weights go one column at a time under batch-invariance mode 2; a split MUL_MAT_ID node synchronizes conservatively; upstream's new shared-expert fusion is gated off under batch invariance (it would hit the token-split MMVQ assert); three insertions moved off lines Inkling and DiffusionGemma add.
  • 48e9223: scheduling fixes.
    • Starvation: once the oldest parked slot has waited PREEMPT_ROTATE_US, new prompts that started after it was parked are held back, so it is restored instead of being overtaken forever. Held slots holding no cells are never victims, so nothing deadlocks.
    • Rotation: any generating resident can be rotated out, the longest included, after a minimum service of 32 tokens (or 1 token and 2 s).
    • Victim choice: park the one eligible slot with the fewest cells that covers the deficit, rather than several smaller ones. LLAMA_SERVER_POLICY=largest no longer exempts the leader.
    • /props reports "preempt": {"enabled", "ram_mib", "async", "notices": 2, "recurrent", "granularity"}, which is what Unsloth Studio reads to decide whether the server parks.
  • f6b916c: the pinned park buffer was freed and reallocated at exact size on every park of a grown sequence. It now grows to 1.5x (64 KiB granularity), and only when --preempt-ram still holds another state of the grown size. With --preempt-ram 0 and nothing parked, update_preemption() returns early.
  • a3f4d85, 7a011aa: tests for the above.

Evidence

  • New tests: all 8 fail on the b91b2f0 build on CPU (9 on CUDA, where the buffer growth test also runs) and pass on this head. Starvation: the head was still waiting when its stream stopped at 40 s. Rotation: the long resident was never rotated. Victim: two 407-cell residents parked where one would do. /props: the key was missing.
  • test_preempt.py + test_preempt_notify.py: CPU 50 passed, 13 skipped, five identical runs. CUDA 54 passed, 1 failed, 8 skipped; the failure (test_a_recompute_restore_does_not_count_its_replay_as_prompt, a predicted_ms > prompt_ms timing check) fails identically on b91b2f0. Model-gated tests (Qwen3.5-4B as exact, hybrid and MTP model): 5 passed, 4 skipped. No test passes on b91b2f0 and fails here.
  • b91b2f0 itself: FLASH_ATTN_EXT 3996/3996 (paged included), MUL_MAT 2468/2468, MUL_MAT_ID 981/981 under batch invariance 0 and 2; ctest 7/7. Exact concurrency on Qwen3.5-4B, four prompts in parallel vs alone at temperature 0: 4/4 byte-identical with LLAMA_EXACT_CONCURRENCY=1, 1/4 differs without it.
  • Pin-set sim with this commit in place of server: preemption notices, asynchronous parks and exact concurrency (pin branch on b10869) #210: b11540 and b11541 merge all 16 pins cleanly with pin_contract and merge_checks passing. On b11552 this pin is additive; that tag currently fails on a different pin (qwen4exp: run MTP heads that share the target's token_embd and output #240, src/models/qwen4exp.cpp), identically with or without this change.

Known, not fixed here

On CUDA a multi-token prompt chunk crossing position 2048 can hang inside llama_decode (main thread spinning). It reproduces on b91b2f0 and on this head alike, 3 of 3, with stories260K at an 8192 training context; this build has not been compared against plain b11540. The reservation test therefore runs its server on CPU, since everything it covers is host-side scheduling.

… on b11540

The change carried by #210, applied to upstream b11540 alone. #210 sat on b10871 with Inkling merged in, so its diff carried an old ggml-org#25731 and no longer composes with the nightly.
…dent, deficit-aware victim choice

A parked head that has waited PREEMPT_ROTATE_US is owed the cells: a prompt
that has never been resident waits until it is back, so a stream of short
requests can no longer overtake it for good. Rotation now considers every
generating resident, the longest included, and a held prompt that sits on
cells, choosing the fewest cells that make room; a resumed slot is not
rotated again before it has decoded 32 tokens, or one token and 2 s.

Ordinary victim choice parks the single eligible slot that covers the
shortfall where there is one, and LLAMA_SERVER_PREEMPT_POLICY=largest can
now pick the largest slot.

/props reports a preempt block (enabled, ram_mib, async, notices,
recurrent, granularity). A pinned park buffer grows by half again instead
of to the exact size, within --preempt-ram, and update_preemption() returns
at once with --preempt-ram 0 and nothing parked.
…ft in --preempt-ram

Rounded to 1 MiB and taken whenever it fitted, the reserved slack filled a
small budget: under --preempt-ram 2 MiB a 0.5 MiB state held 1 MiB, and the
rotation that needs the head's and a resident's states at once was refused.
Round to 64 KiB, and grow only where the budget still holds a second state
of the grown size.
@danielhanchen
danielhanchen requested a review from CISC as a code owner October 11, 2026 09:12
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-11T09:29:29.128950Z 7a011aa PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7a011aacfe

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2783 to +2785
// [TAG_EXACT_CONCURRENCY] src[5] is the page table, which only the CUDA backend reads; the remote end is not asked, so it is not claimed here
if (op->op == GGML_OP_FLASH_ATTN_EXT && op->src[5]) {
return false;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject paged attention at the RPC server boundary

When a CUDA-backed RPC endpoint is reachable by an untrusted client, this check only prevents the normal client-side scheduler from selecting RPC; rpc_server::graph_compute() still reconstructs and dispatches arbitrary submitted sources without calling supports_op(). A direct RPC client can therefore submit FLASH_ATTN_EXT with src[5], causing the new CUDA path either to abort on its shape assertions or to trust attacker-controlled page counts and IDs for out-of-bounds device reads. Reject this source in the RPC server's graph validation, and validate page contents before dispatch.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in #269 (83b6ca0), the repin of this branch onto b11577. The client-side supports_op check never reached a direct RPC client, because rpc_server::graph_compute rebuilt and computed whatever graph it was sent. The server now rejects a FLASH_ATTN_EXT node carrying the page table in src[5] while it builds the graph and drops that connection before anything reaches a backend. test-rpc-paged-fa runs a CPU server and sends the graph from its own client: the paged graph computed before this change, and now it is refused while a plain graph sent afterwards still computes.

Comment on lines +220 to +221
// (optional) non-blocking completion test for an event. Kept last: a missing entry is NULL and ggml_backend_event_query() then blocks instead.
bool (*event_query) (ggml_backend_dev_t dev, ggml_backend_event_t event);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bump the backend ABI version for event_query

When loading an out-of-tree backend built against the existing ABI version 3, appending this callback changes ggml_backend_device_i while GGML_BACKEND_API_VERSION remains 3, so the loader accepts the old, shorter structure. For an old device advertising events, the core then interprets the following reg field as event_query; preemption's capability check sees it as non-null and a later query calls that data pointer as code. Increment the backend API version so incompatible plugins are rejected and rebuilt.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in #269 (1161f59), the repin of this branch onto b11577. Rather than bump GGML_BACKEND_API_VERSION, which would collide with upstream's next bump in the nightly merge, event_query is no longer in ggml_backend_device_i at all, so the struct and the version are upstream's again. The CUDA backend publishes its implementation through get_proc_address as "ggml_backend_dev_event_query"; ggml_backend_event_query() and ggml_backend_dev_supports_event_query() look it up through the device's registry, and a backend that does not publish it keeps the blocking synchronize fallback. test-event-query checks that a CUDA device reports the query and that a completed event reads as complete.

Comment thread src/llama-kv-cache.cpp
std::set<uint32_t> assigned;
slot_info res {0, 0, {0}, {{}}};
for (uint32_t i = 0; i < ubatch.n_tokens; ++i) {
GGML_ASSERT(ubatch.n_seq_id[i] == 1 && ubatch.pos[i] >= 0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject negative restored positions instead of asserting

When LLAMA_EXACT_CONCURRENCY is enabled and an application restores a corrupt or client-supplied per-sequence state, each ubatch.pos here comes directly from the serialized llama_pos read by state_read_meta() without validation. A negative position therefore reaches this GGML_ASSERT and aborts the process instead of being reported through the existing state-restore error path. Validate the serialized position and return or throw before invoking the paged allocator.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in #269 (75dabc1), the repin of this branch onto b11577. A sequence state with a negative position reached the GGML_ASSERT in the paged slot search and aborted. state_read_meta now refuses such a cell in exact mode through the normal restore error path, so llama_state_seq_set_data returns 0. test-exact-pages patches a saved sequence's first position to -1: it aborted on the assert before this change, and now the restore returns 0 while the unpatched state still restores to its full length.

Comment thread src/llama-kv-cache.cpp
} else {
// whole KV cache restore

GGML_ASSERT(!exact_pages);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Return an error for whole-state restores in exact mode

When LLAMA_EXACT_CONCURRENCY is enabled, restoring any valid whole-context snapshot through llama_state_set_data() or the session-loading API takes this dest_seq_id == -1 branch and unconditionally aborts on the assertion. This makes the existing whole-state API unusable with the new mode and crashes applications instead of returning the documented zero/error result; either restore and rebuild the page ownership metadata or reject this operation through the normal state-read error path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one cannot happen. state_read_sinfo refuses a whole-context restore in exact mode before reading anything, by throwing, and llama_state_set_data and llama_state_load_file catch that and return 0 or false, so the assert in state_read_meta's whole-cache branch is never reached in this mode. #269 (64399f3) adds that case to test-exact-pages: a saved whole-context state is refused through the error return and the process keeps running.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant