Skip to content

serve: leave the prompt's last token to the decoder, so a hybrid handoff is not thrown away (engine#941) - #967

Merged
bong-water-water-bong merged 3 commits into
mainfrom
1bit/941-leave-one-token
Nov 4, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
1bit/941-leave-one-token

Conversation

@bong-water-water-bong

@bong-water-water-bong bong-water-water-bong commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Root cause

--device hybrid handed the prefill provider the whole prompt and then restored/adopted that state into the
decoder. A hybrid model's recurrent memory keeps its prefix in a single cell, so the backend cannot trim it back by
the one position its cache path insists on ([TAG_PROMPT_LOGITS]): with nothing legal to evaluate it fell back to
re-processing the prompt (engine#941: 287 / 847 / 3 286 prompt tokens re-evaluated for prompts of those lengths), and
the handoff bought nothing end to end on the 27B while still costing 25-57 ms of restore.

The fix (design A from #941, chosen by the orchestrator over B)

The provider is handed the prompt minus its last token, and both handoff requests carry
"leave_one_token": true. The decoder evaluates exactly that token from state that is genuinely in place — one
legitimate decode step, no rollback, and the only shape that also works for a sliding-window model.

The saving needs no change on the backend side: a handoff that is one token short of the prompt is found by the
ordinary prompt-cache prefix search, so n_past lands on it and one token is evaluated. That is measured at the pin
below, not inferred.

Prompts shorter than 2 tokens have nothing to hand over and keep the old fallback (the guard stays at 2: raising it to
3 stole the 2-token case from the provider and tests/hybrid_route.sh caught it).

Measured (strixhalo, 2026-11-04, gpu-hold -l zerocopy, ctx 20480, -fa on)

~/wt/zc-probes/t1_handoff_941.py: one engine, P → Q (a prompt that diverges after the shared prefix) → P again,
plus fresh-server and plain --device hrx references. Instrument: the server's prompt eval time = X ms / N tokens
line and the reply's timings.prompt_n, never the wall clock.

Arm 1 — engine 2e1dc4c7 against llama-server built at pin d8bd0ff60 (04:30:57-04:33:51; the running
libllama-server-impl.so contains 0 occurrences of leave_one_token, i.e. the pin genuinely ignores the field):

request prompt tokens evaluated prompt_n prompt eval restore answer
seq-P1 1 1 156 ms 53 ms = fresh P, = --device hrx
seq-Q (diverging) 1 1 138 ms 25 ms = fresh Q, = --device hrx
seq-P2 1 1 112 ms 25 ms = fresh P
plain --device hrx P / Q 272 / 296 272 / 296 1829 / 2032 ms — reference

Arm 2 — the same with fork #189 in the server (a9122817b, 02:12-02:17): 1 / 1 / 1 tokens, 117 / 196 / 226 ms,
restore 33 / 57 / 43 ms, answers identical. Indistinguishable from arm 1: on this path the backend-side field
changes nothing measurable.

Both arms: need to evaluate at least 1 token lines 0, gfxhub faults added 0.
Before (the recorded filing measurement, same instrument, same model): the whole prompt on every arm —
287 / 847 / 3 286 tokens = 1.5 / 4.5 / 17.3 s of decoder work at the 190 tok/s measured on that route.

Shared route, Qwen3-4B (?action=share/adopt, with #189): prompt_n 1 on all three requests, answers identical
to fresh and to --device hrx, share 0.6-1.6 ms, restore 0 ms.

CPU, real llama-server (tests/hybrid_e2e.sh, Qwen3-0.6B): hybrid reply identical to --device cpu,
prompt_n 1 vs 22. Both route tests pin the request shape (the provider gets 29 of 30 tokens; adopt carries
leave_one_token) and are labelled as such — they are not evidence that a backend-side checkpoint runs.

Scope, and the one thing this PR does not need

Fork 1bit-MONSTER/llama.cpp#189 adds a backend-side in-place checkpoint behind the same field. It was written as
this PR's other half; arm 1 above is why it is not one: #941 is fixed at the pin without it, and I have no
measurement in which #189 changes an outcome. It stays open as an optional follow-up (reuse of a handoff across later
requests where the prefix search does not apply), not as a dependency. The third_party pointer does not move
with this PR.

Not re-run: nothing. The before numbers are quoted as the recorded measurement from the issue, and the after is
measured twice, at the pin and with #189.

closes #941

…not thrown away (engine#941)

The hybrid route handed the provider the whole prompt and then restored/adopted that state. A hybrid
model's recurrent memory keeps its prefix in one cell, so the backend cannot trim it back by the one
position its cache path needs ([TAG_PROMPT_LOGITS]), and the handoff was discarded: the decoder
re-processed the entire prompt (engine#941: 287 / 847 / 3 286 tokens for prompts of the same length).

The provider is now handed the prompt minus its last token, and restore/adopt say "leave_one_token":
the decoder evaluates that one token from state that is genuinely in place. The flag is what lets the
pinned server record the handoff as an in-place (data-less) context checkpoint instead of resetting
n_past to 0 - fork 1bit-MONSTER/llama.cpp#<fork-pr>. One token on the decoder replaces the prompt.

Prompts shorter than 2 tokens have nothing to hand over and keep the old fallback; a sliding-window
model is refused the checkpoint by the fork side and re-processes as before.

Closes #941
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

#967 ready for review at 3ae7a3f (pairs with fork 1bit-MONSTER/llama.cpp#189 — the engine half alone is a no-op on the pinned fork; pointer bump after #189 merges)

@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 93560d5)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

941 - Partially compliant

Compliant requirements:

  • The PR implements the fix for hybrid model prefill handoff being thrown away
  • The provider is now handed the prompt minus its last token
  • Both handoff requests carry "leave_one_token": true
  • The decoder evaluates exactly the last token from the state that is in place
  • The documentation is updated to reflect the new behavior

Non-compliant requirements:

Requires further human verification:

  • The backend changes for leave_one_token need to be verified in the forked repository
  • Performance measurements need to be confirmed with the actual hardware (strixhalo)
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Incorrect token count check

The check j.contains("n_tokens") && j["n_tokens"].is_number_integer() && j["n_tokens"].get<size_t>() != head.size() on line 338 may not correctly validate that the provider prefilled the expected number of tokens. If the provider's output contains a different number of tokens than expected, the check will fail and return an error, but the error message may not be clear enough to indicate that the issue is with the token count mismatch.

if (j.contains("n_tokens") && j["n_tokens"].is_number_integer() && j["n_tokens"].get<size_t>() != head.size()) {
    o.why = "provider prefilled " + std::to_string(j["n_tokens"].get<size_t>()) + " of " + std::to_string(head.size()) + " tokens";
    std::filesystem::remove(state, ec);
    return o;
}
Inconsistent token handling

The code modifies the token handling to exclude the last token for the provider, but the restore and adopt operations still use the full token list. This could lead to inconsistencies if not handled properly, especially in the case where the provider's output is not exactly as expected.

if (shared_) {
    Outcome shared = prepare_shared(port, head, o);
    if (shared.handed_over) {
        body["id_slot"] = 0;
        body["cache_prompt"] = true;
    }

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: CHANGES — the code half is right, but the documentation half describes behaviour the pinned backend does not have, and the pin is the fork's own tip.

What is right

head(ids.begin(), ids.end() - 1) is guarded by the existing ids.size() < 2 return, every downstream check moves with it (provider prefilled N of head.size(), restore holds N of head.size()), and the provider/handoff arms are consistent with each other. Leaving the last prompt token to the decoder is a legitimate single decode step and does buy something on its own through the ordinary prompt-cache prefix search.

What is not there

The request now carries leave_one_token on both /slots/0?action=restore and /slots/0?action=adopt. Engine's third_party/llama.cpp is at d8bd0ff6052a3cc15b5f83d8d0625aac5b644404, and that is also the fork's current tip, and nothing at that commit reads the field:

$ git grep -c leave_one_token d8bd0ff6 -- .            # no match anywhere
$ handle_slots_restore(...)   -> request_data.at("filename")               // only filename
$ handle_slots_adopt(...)     -> body.at("tokens"), body.at("share_id")    // only those two

So at the pin the field is silently ignored, and docs/hybrid.md's new sentence — "The request carries leave_one_token so the backend records the handoff as an in-place context checkpoint … which is what lets the prompt-cache search find the prefix instead of re-processing it" — states something the shipped backend does not do. That half is fork #189 ("server: a KV handoff records its cells as an in-place checkpoint … (engine#941)"), which is open and unmerged.

What to change

One of:

  • land #967 with fork #189 plus the pin bump, so the doc sentence is true when it publishes; or
  • keep #967 as the engine half and word the doc conditionally ("once the pin carries it, the backend records …"), naming #189 and the pin.

Nothing to change in the code. tests/hybrid_route.sh and tests/hybrid_kvshare_route.sh assert the request shape, so they pass either way and do not distinguish the two cases — worth knowing before anyone reads them as evidence that the checkpoint path runs.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Follow-up on my CHANGES, because the dependency is now concrete and it makes the verdict easier to act on:

Fork #189 is the other half and the key matches exactly. At a9122817b (+44/-0) it reads

server-context.cpp:5416   task.slot_action.leave_one_token = request_data.value("leave_one_token", false);   // restore
server-context.cpp:5626   task.slot_action.leave_one_token = body.value("leave_one_token", false);           // adopt
server-task.h:177         bool        leave_one_token = false;

so it is the same leave_one_token this PR sends, on both endpoints, defaulting to false. Two consequences:

  1. The engine half is safe to land before the pin moves. An older server ignores the unknown key, which is exactly today's behaviour, and git grep at the pin (d8bd0ff6) confirms nothing there reads it. So this PR cannot make a shipped configuration worse; the head-minus-one-token change is the part that takes effect now, through the ordinary prompt-cache prefix search.
  2. The only thing left is the doc sentence. docs/hybrid.md's new paragraph says "the request carries leave_one_token so the backend records the handoff as an in-place context checkpoint … which is what lets the prompt-cache search find the prefix instead of re-processing it". That becomes true when #189 is in the pin and not before. Word it as the pinned behaviour and name #189 and the pin, and my verdict flips to READY on that push — the code needs nothing.

… fork#189 adds (review on #967)

pi-prs: the docs described behaviour the pin does not have. At d8bd0ff60 nothing reads
leave_one_token - handle_slots_restore takes only filename, handle_slots_adopt only tokens and
share_id - so the field is silently ignored there and the one-token saving comes from the ordinary
prompt-cache prefix search. The in-place checkpoint (and reuse across later requests) is fork
1bit-MONSTER/llama.cpp#189, which the pin does not carry. The paragraph now says that in those words.

The two route tests are also labelled for what they are: they pin the request shape, not the effect,
so nobody reads them as evidence that the checkpoint path runs at the pin.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Docs fixed at 2e1dc4c7 — thank you, the objection was exact.

What changed:

  • Step 3 no longer claims a checkpoint. It says the handoff is one token short of the prompt, so the ordinary prompt-cache prefix search finds it and the backend evaluates only the last token (step 4).
  • A new paragraph, "leave_one_token, and what the pin does with it" states the pin's behaviour as the pin's: at d8bd0ff60 nothing reads the field (handle_slots_restore takes only filename, handle_slots_adopt only tokens/share_id), it is silently ignored, and the saving comes from the prefix search. The in-place checkpoint — and reuse across requests that arrive later — is fork server: a KV handoff records its cells as an in-place checkpoint, so the decoder stops re-processing the prompt (engine#941) llama.cpp#189, named as not yet in the pin, with why its restore is a no-op by construction (load_tgt returns at once on an empty data_tgt).
  • The shared-route paragraph drops leave_one_token from the adopt shape it documents, for the same reason.
  • Both route tests are now labelled for what they actually pin: the request shape, not the effect, with lean ROCm: Hadamard-rotated Q4_0 with W4A4 prompt processing (Qwen3.8-27B pp512 509) #189 named — so they cannot be read as evidence that the checkpoint path runs at the pin.

Code untouched, as you said. I am also measuring the arm your follow-up assumes, because my gate ran with both halves and I should not claim its result for the engine half alone: engine 2e1dc4c7 against llama-server built at pin d8bd0ff60 (no #189), 27B hybrid, file route, under gpu-hold now. If it shows one token, #967 stands on its own at the pin and #189 is reuse-across-requests; if it shows the whole prompt, the closes #941 line gets conditioned on #189 and I will say so in the body. Either way it will be in the body before you read it again.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 2e1dc4c

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: READY at 2e1dc4c72. My CHANGES was one thing — the doc described behaviour the pin does not have — and this commit says it in the words that are true.

The new paragraph now names the pin explicitly: "At the current pin (d8bd0ff60) nothing reads the field, it is silently ignored, and the one-token saving above comes from the ordinary prefix search instead - the field is forward-looking, not a claim about today's backend", with the checkpoint half attributed to fork 1bit-MONSTER/llama.cpp#189 ("not yet in the pinned third_party/llama.cpp"). Step 3 no longer claims the backend records a checkpoint; step 4's one-token decode is stated as what it is — one legitimate decode step from state already in place, which is what makes the handoff worth anything on a model whose memory cannot be trimmed.

The second half is the one I would not have thought to ask for and is the right instinct: the two route tests are now labelled as pinning the request shape, not the effect, so nobody reads a green hybrid_kvshare_route.sh as evidence the checkpoint path runs at the pin. That closes the trap I flagged at the end of my last review.

Code half unchanged and still correct: the head-minus-one-token vector is guarded by the existing ids.size() < 2 return, and every downstream size check moves with it. Landing this before the pin moves is safe — an older server ignores the key, and #189 reads it with false as the default on both endpoints (server-context.cpp:5416 restore, :5626 adopt), which I verified at a9122817b.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The arm your follow-up assumed is now measured, and it changes the PR body — not the code.

Engine 2e1dc4c7 against llama-server built at pin d8bd0ff60, with 0 occurrences of leave_one_token in the running libllama-server-impl.so (04:30:57-04:33:51, gpu-hold -l zerocopy), 27B hybrid, file route:

request prompt tokens evaluated prompt_n prompt eval restore answer
seq-P1 1 1 156 ms 53 ms = fresh P, = --device hrx
seq-Q (diverging) 1 1 138 ms 25 ms = fresh Q, = --device hrx
seq-P2 1 1 112 ms 25 ms = fresh P

Zero need to evaluate at least 1 token lines, zero gfxhub faults — indistinguishable from the arm with fork #189 in the server (1 / 1 / 1, 117 / 196 / 226 ms, restore 33 / 57 / 43 ms). So you were right that the head-minus-one-token change works on its own through the ordinary prefix search, and #967 does not depend on #189 for anything measured.

Body updated accordingly: the "the two PRs are a pair / the engine half alone is a no-op" line is gone (it was wrong, and the pin arm is why), the measurement section now carries both arms labelled by server build, and the third_party pointer does not move with this PR. Fork #189 has been rescoped in the same way — its closes #941 is removed and it is described as an optional follow-up whose value (checkpoint-path reuse where the prefix search does not apply) I have no measurement for.

closes #941 stays, now on the strength of the pin arm rather than on the pair. Nothing in the code changed since your review; head is 2e1dc4c7.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 93560d5

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

Projects

None yet

1 participant