Skip to content

Look up queued anonymous LLM serving prefixes together - #25727

Open
Gasoonjia wants to merge 8 commits into
gasoonjia/serving-ready-groupfrom
gasoonjia/prefix-clone-waves
Open

Gasoonjia wants to merge 8 commits into
gasoonjia/serving-ready-groupfrom
gasoonjia/prefix-clone-waves

Conversation

@Gasoonjia

@Gasoonjia Gasoonjia commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #25726.

Adds PrefixCache::find_identities(), which runs find_identity() for several requests in waves. Each wave queues one clone per request that is still searching before awaiting any, and a refused clone retries in the next wave. Errors stay per request, and Use/Skip/Stop selectors, entry IDs and caller-side touch() are unchanged. find_identity() now delegates to it. PrefixCache::longest_match() returns the match find_identity() would try first, in one scan without allocating or cloning.

With the prefix cache enabled, ServingRuntime now also groups queued anonymous text requests, building on #25726's cold-open groups:

  • Cost: a member's cost is the part of its prompt after its longest cached prefix, from longest_match(), so sizing clones nothing. It counts against the same half-of-step_prefill_budget() cap.
  • Launch: a group looks up its members in shared clone waves, as many as its refusals need, and submits its members after the last wave. A member with nothing cached issues its cold open while the group is sized, so the open shares the first wave's engine pass; members that end as misses after the waves open together.
  • Budget check after the waves: each member's cost is recomputed from the prefix it actually adopted. The group keeps the members that fit, in queue order. The rest release their clones and pending opens on control and return to the inbox as their original commands, bounded to the prefix they adopted (0 after a looked-up miss), so a longer snapshot that was refused is not tried again; an equal-length refused snapshot may be retried once. The trade-off: a cut member also ignores longer entries cached after the cut, and one cut after a looked-up miss reuses nothing; a member cut before any lookup stays unbounded. Cancelled members cost nothing and never anchor a group, and a member rejected in preparation is launched so its rejection is delivered, never requeued.
  • Unchanged: image, single and cache-less paths, and capture-lane accounting. Keyed requests are admitted as before, but while a group with capped lanes is still deferring captures (below), a keyed turn can find no free lane.

Results. Official Muse-Glimmer-30B-KQuant-17GB-Q4_K_M.gguf (HF meta-models/Muse-Glimmer-30B-GGUF), H100, CUDA graphs on, prefix cache on (8 entries, 4 capture slots), paired base (#25726) / PR runs:

Workload Base → PR
Shared ~1.2K-token prefix burst, B=16 / 32 / 48 throughput +18% / +44% / +64%; last first token 525 → 135 / 1054 → 188 / 2097 → 232 ms
Unique-prompt burst, B=48 +0.9% throughput, −1.0% mean TTFT (within noise)
Prefill 512 to 32k (cache on), 127k (cache off) within run-to-run noise
Decode B=1–4 / B=8–16 (steady) within ±0.5% / −0.5% (within session-to-session variation)
Decode B=32 / 52, steady +6.9% / +8.3%

Peak VRAM rises from 21.6 to 24.1 GiB in a short-prompt decode sweep with the cache on: a group of short prompts is prefilled in one step of up to half the per-step budget (about 2K tokens). That stays below the 25.0 GiB the base build already reaches under the same server configuration when it serves 1.2K-token prompts, so the configured worst-case footprint doesn't grow. Host RSS is unchanged.

Prompt-end captures in groups. Capture lanes are taken at submission, and a group submits its members together. When the lanes are capped below the group size (a small max_prefix_captures, or a checkpoint interval or policy; with the default lane count every member finds one), a member that finds no free lane retries on later tokens and captures its prompt end mid-decode once a lane frees. It hands the capture to control only after the clone completes (PrefixCache::PromptCapture::ready()), so control never blocks. Without this, only as many members as there are lanes captured, and stale entries widened the cell-cache read window enough to slow steady decode by about 2%. The trade-off: lanes freed mid-decode now go to waiting grouped members first. A newly submitted single request (which doesn't retry) is more likely to skip its capture, and a keyed turn whose replacement needs clone_prefix() may find no lane and re-prefill from position 0 instead of cloning its prefix.

Output determinism. At c=1, outputs are identical to the base, including every prefill length up to 127k. At c=32 on the shared workload, repeated PR runs match each other about 81% of the time, against about 95% for repeated base runs. Prefill lengths match on every request and the differences mostly start late in the text (median at character 204), so this comes from batch-composition-dependent numerics, not from reusing the wrong state. Cache entries are idle snapshots inserted on control between groups, so no member can clone an entry that is still being captured.

Trade-off. Because a cache-on group counts only uncached positions, the tokenization before its first submission is bounded by its free session slots rather than by the budget: a burst of long, mostly cached prompts is prepared in full first, in exchange for one shared admission.

Test plan: 23 new tests (10 batching, 13 serving) and one rewritten serving test (#25726's PrefixCachingDisablesGrouping becomes PrefixCachingStillGroupsShortPrompts). They cover wave-vs-sequential equivalence, clones pending together (checked by the order the engine serves them), longest_match(), Skip/Stop, entry IDs and touch, per-request clone failures including std::bad_alloc, capture-lane limits, shutdown while pending, the cache-on group budget before and after the waves, cut members (exact clone counts, released pending opens, no re-preparation of a rejected member, later reuse by a member cut before its lookup), cancelled head members, failed preparations, and credited members that miss. Each new behavior's test was checked to fail with its code removed, except the release of a cut member's pending open, which the same call releases anyway when it returns; that path is covered by a test and by the fixture's leak check. They are stable over 1000 repeats and 8×300 in parallel. Two more tests cover the deferred prompt-end capture (MembersWithoutALaneCaptureTheirPromptsLater, PromptCaptureIsReadyOnceItsCloneSettles). Serving suite: 317 pass (14 skipped, same as main). Batching suite: 240 pass.

@pytorch-bot

pytorch-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/25727

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit 56bb153 with merge base 2bb454f (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review this PR (head a611fe5ad8, stacked on #25726 950581bc1f): PrefixCache::find_identities() clone waves, and cache-on cold-open grouping in ServingRuntime, where a member costs its prompt minus its longest cached prefix. Scope is extension/llm/batching/prefix_cache.h and extension/llm/serving; please review only the diff against #25726.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 25, 2026
@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 30m 51s —— View job


PR Review: #25727

Request changes: cache-on groups are sized as if every member will reuse its longest cached prefix, and nothing re-checks the half-of-step_prefill_budget() cap after the clone wave, so when clones are refused one group can prefill many times the cap at once; the other six findings are minor.

Detailed review

Summary

The PR adds PrefixCache::find_identities(), which runs find_identity() for several queries in clone waves. It uses that to group queued anonymous text requests when the prefix cache is on, charging each member its prompt minus its longest cached prefix.

The main problem is that this charge is an estimate that nothing re-checks, so a group can go far past its cap whenever a credited clone is refused. The other findings are minor:

  • a group that mixes hits and misses waits an extra engine pass;
  • some of the new code is dead, or more general than its one caller needs;
  • the tests don't check that a wave's clones are actually in flight together.

I read the code for this review but did not build it or run the tests.

Code Quality

  • cached_prefix() gets its answer through a side effect of the selector (extension/llm/serving/serving_runtime.cpp:1175-1197).

    • It sets longest inside the selector and returns Stop so that no clone happens. That only works because find_identity() hands out candidates longest first (prefix_cache.h:409).
    • Each call builds, scans and sorts a candidate list over every cache entry. lookup_prefixes() then does the same work again for the same members.
    • Fix: add a small const PrefixCache query that returns the longest matched length. It would state what it does and scan once, without allocating.

    Fix this →

  • The Searches guard in find_identities() can never run, and if it did it would not do what its comment says (extension/llm/batching/prefix_cache.h:469-480).

    • settle_clone() calls get() on every clone queued in a wave before the next wave starts, and both helpers catch every exception. So no valid future ever reaches ~Searches().
    • If one did, wait() would leave the Session inside the shared state. The Runner holds a shared_ptr<promise> (runner.cpp:1372-1380) that may drop that state last, so the session could still be destroyed on the engine thread. That is exactly what the comment says the guard prevents.
    • Fix: delete the guard, or settle with get() inside a try the way SettleOpen does (serving_runtime.cpp:1451-1466).
    • Separately, queue_next_clone() and settle_clone() (prefix_cache.h:585, :620) are templates only because Search is declared inside the function. Making Candidate and Search private nested structs removes the templates.

    Fix this →

  • The new group plumbing is more general than its one caller needs (extension/llm/serving/serving_runtime.cpp).

    • lookup_prefixes() and acquire_sessions() take a begin parameter (:1204, :1255). Their only call (:1412) passes 0, so the checked[i - begin] offsets are never needed.
    • generate() takes PrefixLookupResult* looked_up (:1450), an in/out raw pointer that it moves from only when it opens a session.
      • A clone the member does not adopt is released only because the caller remembers to call found[i].reset() (:1420-1421).
      • cold_open, the parameter next to it, is taken by value and settled inside generate().
      • Fix: take std::optional<PrefixLookupResult> by value instead. That matches cold_open, releases unadopted clones on control when generate() returns, and removes the need for the reset and its comment.
    • The open try/catch in acquire_sessions() (:1268-1276) duplicates the one at :1395-1403.

    Fix this →

Testing

  • No test checks that a wave's clones are in flight together, and three serving tests don't depend on grouping at all.

    • EveryQueryQueuesItsCloneBeforeAnyIsAwaited (extension/llm/batching/test/prefix_cache_test.cpp:1177) counts selector calls while the engine is held inside the first clone. A loop that first runs every selector and then queues and awaits the clones one at a time would also reach 3.
    • QueuedHitsCloneTogetherBeforeAnyMemberPrefills (extension/llm/serving/test/prefix_reuse_test.cpp:3518) shows that every lookup finished before the first submission. A group that cloned one member at a time would pass it too.
    • MixedGroupKeepsEachMembersOutcome (:3606), RefusedCloneFallsBackOnlyForItsMember (:3633) and ShutdownDuringTheCloneWaveSettlesEveryMember (:3660) assert nothing that requires the members to share a wave. Handling the members one at a time, as Open queued anonymous LLM serving sessions together #25726 did with the cache on, gives the same reuse counts, clone attempts and terminal events.
    • Fix for the serving tests: hold executor.executing and wait for the expected clone count, as QueuedHitsCloneTogetherBeforeAnyMemberPrefills does.
    • Fix for the batching test: it has to observe queue order. For example, queue a marker open once selected reaches 3, then assert that the engine served the second query's clone before the marker.
  • The bad_alloc half of the per-query error contract has no test (prefix_cache.h:89-93, :611, :634).

    • IdentityResult says that a std::bad_alloc from one query's selector or clone request ends only that query, as a miss with no error.
    • OneQuerysFailureLeavesTheOthersAndTheirClones (prefix_cache_test.cpp:1331) only throws std::runtime_error.

    Fix this →

Performance

  • Nothing re-checks the cache-on group cost, so refused clones can push a group far past the half-budget cap (extension/llm/serving/serving_runtime.cpp:1382-1385, :1172-1197, :1410-1413).

    • What happens:
      • cached_prefix() charges each member its prompt minus its longest candidate, and group membership is then fixed.
      • acquire_sessions() opens the misses without comparing what each member actually reused against group_prompt_tokens_.
      • If a member's longest candidate is skipped, or its clone is refused, the member falls back to a shorter prefix or a full cold open. It does so inside a group that admitted it at almost no cost.
    • When it happens: runner.h:211-215 documents executors that "can clone only at saved boundaries" and refusals for "unavailable retained state". For example, take checkpointing with the default scheduler, which gives a 256-token cap. The cache holds a 1260-token prompt-end entry and a checkpoint at 1024, and the queued prompts share their first 1250 tokens:
      • each member is charged about 10 tokens, so about 25 members fit the cap;
      • every clone at 1250 is refused, and the next wave adopts the 1024 checkpoint;
      • every member then prefills about 236 tokens, so about 5.9K tokens are admitted together.
    • Why it matters:
      • This is the long-prompt packing that the generate_group() comment (:1356-1360) says measured slower.
      • It contradicts the PR description's claim that the cost "counts against the same half-of-step_prefill_budget() cap".
      • With the cache on, Open queued anonymous LLM serving sessions together #25726 admitted these requests one at a time.
    • Fix: after lookup_prefixes(), and before the misses' opens are issued, recompute each member's actual cost in queue order. A hit costs its prompt minus the adopted match; a miss costs its full prompt. Lower end to the first member that no longer fits, release the cut members' clones on control, and requeue them at position. No opens have been issued at that point, so the cut is cheap.
    • Test: RefusedCloneFallsBackOnlyForItsMember already shows the problem. Its group is sized at 3 positions but prefills 6, and it passes only because the default cap is 14. Running it with a small DecodeFirstScheduler budget would cover this case.

    Fix this →

  • A group that mixes hits and misses waits an extra engine pass, and every member waits for other members' retries (serving_runtime.cpp:1394, :1410-1413; prefix_cache.h:516-531).

    • Extra pass:
      • With the cache on, no cold open is queued until find_identities() has finished every wave.
      • generate() then blocks the first miss on cold_open.get(), and every member behind it waits too.
      • The Runner drains its whole inbox before each batch (runner.cpp:793-796, :858-876). Some members have no candidate at all (cached_prefix() returns 0). If those members queued their opens while the group is being sized, as the cache-less branch does, the opens would be served in the same pass as the first wave instead of one pass later.
    • Retries:
      • A refused clone retries in the next wave, and no member is submitted until every search has ended.
      • So a group runs as many waves as its longest chain of refusals, not the "one clone wave" the PR description states.
      • Members queued ahead of a refused member now wait for all of its retries.
    • Groups that are all hits or all misses are not affected. My confidence in how large this cost is in practice is low.

Recommendation

Request Changes. The cache-on group cost should be bounded by what each member actually reuses. Alternatively, accept the overshoot explicitly, document it, and add a test for it. The other findings are minor and could be follow-ups.

PrefixCache::find_identities() runs find_identity() for several requests at
once. Each wave selects the next candidate of every request still searching
and queues its clone before awaiting any, so Runner serves the whole wave in
one engine iteration; a request whose clone is refused continues in the next
wave. Each result matches find_identity() against the cache as it was at the
call, errors stay per request, and find_identity() now delegates to it.

ServingRuntime now also groups queued anonymous text generations when prefix
caching is enabled. A group looks up all of its members with one
find_identities() call and then issues the cold opens of its misses together,
before submitting the members in queue order. Previously each member awaited
its own clone, and then its cold open, before the next member was looked at,
so a shared-prefix burst was admitted one request per executed batch.

With caching, the group bound of half the step prefill budget counts only the
positions a member still has to prefill after its longest cached prefix,
found without cloning. Shared-prefix bursts therefore group widely, while
prompts that are long after reuse keep one-per-step admission. Keyed
requests, image prompts, single requests and cache-less groups are unchanged.
PrefixCache::longest_match() returns the match find_identity() would try
first, in one scan without allocating or cloning. find_identities() drops its
unreachable settle guard, since each wave settles every clone it queues, and
its candidate and search state become private nested structs so the helpers
are no longer templates.

Tests now show that the clones of a wave are pending together, using the
order in which the engine serves them, and cover a std::bad_alloc that ends
only the query that raised it.
A cache-on group was sized by charging each member its prompt minus its
longest cached prefix, and nothing re-checked that after the clone waves. A
refused or skipped clone could leave many members prefilling far more than
the half-step budget in one step. After the lookup, the group now recomputes
each member's cost from the prefix it adopted and keeps the members that fit
in queue order. The rest release their clones and pending opens on control
and return to the inbox as their original commands. A failed lookup ends the
group the way a failed preparation does.

The cost estimate uses PrefixCache::longest_match(). A member with nothing
cached issues its cold open while the group is sized, so the open shares the
engine pass of the first clone wave. generate() takes the group lookup by
value, so whatever a member does not adopt is released on control when it
returns. Serving tests now each hold the first prefill and check counts only
a group can reach, and a failed preparation is shown to end a cache-on group.
When a preparation fails after other members are waiting, the failed member
ends the group with its rejection already delivered. If the clone-wave budget
check then cut the group at an earlier member, the failed member was requeued
with the cut ones and prepared a second time: its input, consumed by the
first attempt, could prepare successfully and run a request whose Failed
terminal had already been emitted. Members rejected in preparation are now
always launched, and only prepared cut members and the untried tail return
to the inbox.

PrefixCachingStillGroupsShortPrompts also checks that no slice of the first
prompt ran before the second finished preparing.
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review the current head 526a4b5344, rebased onto #25726's latest head 644392c660 and stacked on it. It addresses the last review:

  • Cap holds after the clone wave: acquire_sessions() recomputes each member's cost from the prefix it actually adopted (a miss counts its full prompt) and keeps the members that fit, in queue order. Cut members release their clones and pending opens on control and go back to the inbox as their original commands. Members rejected in preparation are always launched, so their rejection is delivered and they are never prepared twice. New tests: RefusedCreditedClonesKeepTheGroupWithinItsCap and CutNeverRequeuesAMemberRejectedInPreparation.

  • PrefixCache::longest_match(): a const single-scan query used for the cost estimate, replacing the selector side effect.

  • find_identities: the unreachable guard is removed, and Candidate/Search are private nested structs, so the helpers are no longer templates.

  • Plumbing: the unused begin parameters are gone. generate() takes std::optional<PrefixLookupResult> by value, so unadopted clones are released on return. The open try/catch is shared via issue_open()/settle_open().

  • Tests:

    • the wave test proves the clones are pending together;
    • the mixed, refused and shutdown serving tests hold the first prefill and check counts only grouping can reach;
    • PrefixCachingStillGroupsShortPrompts checks engine slices exactly.

    Each fails without its code or on Open queued anonymous LLM serving sessions together #25726's runtime.

  • Extra engine pass: members with nothing cached issue their cold open while the group is sized. A failed preparation ends a cache-on group, through Open queued anonymous LLM serving sessions together #25726's shared rule.

Full model, H100, c=32, base #25726: shared prefix +45% throughput, −68% TTFT. Unique prompts are neutral within run-to-run noise (−1 to −2% throughput, +2% TTFT, inside the base-vs-base variance of about ±3%). Outputs at c=1 are identical.

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 32m 40s —— View job


PR Review: #25727

Request changes: the group cap now holds after the clone wave, but a member it cuts is requeued with the same credit, so when clones keep being refused each later group clones it again (about N² clone attempts for N members); the other six findings are minor.

Detailed review

Summary

This revision bounds cache-on groups by the prefix each member actually adopted, adds PrefixCache::longest_match(), and simplifies find_identities() and the group plumbing.

The cap now holds, but a cut member is requeued with nothing recorded about the clone it lost. When clones are refused for a structural reason, every later group credits that member and clones it again. The other findings are minor:

  • a branch in acquire_sessions() that cannot run;
  • a cancelled member counts as a kept member;
  • two new paths have no test;
  • with the cache on, a comment about the tokenization bound is no longer true;
  • two test nits, and the PR description is out of date.

I read the code for this review but did not build it or run the tests.

Code Quality

  • The ServingError branch in acquire_sessions() can never take its kept path (extension/llm/serving/serving_runtime.cpp:1306-1314).

    • A lookup yields a ServingError only when the selector stops on a NotReady acceptance error, because select_reuse_input() turns every other error into Unavailable (:776-784).
    • Only non-token inputs reach accepts_async() (:726-730). Such a member is always the only prepared member of its group (:1450-1467), so kept is still false when the branch runs.
    • The case its comment describes, a failed lookup with later members to cut, cannot occur. prefill_cost() already charges such a member nothing, so the branch can be deleted.

    Fix this →

  • Two test nits.

    • PrefixCachingStillGroupsShortPrompts open-codes the fixture's holds_for() (extension/llm/serving/test/text_generation_test.cpp:1653-1666) for its 200 ms window (:2043-2050).
    • The comment in QueuedMissesOpenTogetherAndShareOneCaptureLane (extension/llm/serving/test/prefix_reuse_test.cpp:3552) says a 32-token chunk groups 16 positions.
      • The cap is step_prefill_budget() / 2 (serving_runtime.cpp:276-277), which here is (64 − 4) / 2 = 30. The chunk size plays no part.
      • The fixture's default create(32, 4, 8) already gives 14 positions, enough for the 9 this test needs, so the custom scheduler can go.

    Fix this →

  • The PR description no longer matches the code.

    • The cost estimate now uses longest_match(), not a Stop selector.
    • A group runs as many clone waves as its refusals need, not one.
    • The diff adds 10 batching tests and 9 serving tests and rewrites one, not 8 and 6.

Testing

  • Two paths added in this revision have no test (serving_runtime.cpp:1296, :1323-1331).

    • A cut member with a pending cold open: none of the new tests cuts a member whose cold open was already issued during sizing, so settle_open(opens[j]) in cut never runs. Every member cut in RefusedCreditedClonesKeepTheGroupWithinItsCap and CutNeverRequeuesAMemberRejectedInPreparation is a credited hit. A test would need a hit whose credited clone is refused, leaving 6 positions, followed by a 3-token miss under the 4-position cap.
    • A credited member that ends as a miss: none of the new tests has one, and it is the only case the second loop of acquire_sessions() opens. By my reading, deleting that loop would not fail any test, because generate() would then open those sessions itself, one blocking open at a time.

    Fix this →

Performance

  • A cut member is requeued with the same credit, so each later group clones it again (serving_runtime.cpp:1293-1299, :1487-1502, :1174-1179).

    • What happens:
      • The cut releases the member's clone and requeues the member with nothing recorded about its lookup.
      • The next group's cached_prefix() credits it again with longest_match(), which knows nothing of the refusal.
      • Its longest clone is refused again, it falls back to the same shorter prefix, and it is cut again unless it is first.
    • Cost:
      • When every member's real cost is more than half the group cap, each group launches only its first member.
      • With one refused candidate per member, N such members take N groups and about N² clone attempts. About N²/2 of the successful clones are thrown away.
      • Handling them one at a time, as Open queued anonymous LLM serving sessions together #25726 does with the cache on, admits them about as fast, with 2N attempts and no clones thrown away.
    • When:
      • The refusal repeats whenever its cause is structural: an executor that clones only at saved boundaries, recurrent state that cannot be restored at the matched position, or unavailable retained history (extension/llm/batching/runner.h:211-215, extension/llm/batching/executor.h:101-106).
      • On hybrid or recurrent models, the shared-prefix workload this PR targets hits this whenever the shared prefix ends well past the last saved checkpoint.
    • The PR's own test shows it:
      • By my count, the three members of RefusedCreditedClonesKeepTheGroupWithinItsCap make 6 clone attempts on longer and 7 on shorter. One lookup per member would make 3 and 4.
      • EXPECT_GE(executor.clone_attempts(shorter), 4) (prefix_reuse_test.cpp:3804) accepts that.
    • Fix:
      • When a member is cut, record on its request the length it adopted, or 0 for a miss.
      • Pass that length as at_most to longest_match() in cached_prefix(). The next group then sizes the member by what it actually got, and a cut miss opens during sizing instead of being looked up again.
      • Pass the same bound to the member's query in lookup_prefixes(), so the refused clone is not tried again.
      • Then assert exact clone counts in the test.

    Fix this →

  • A cancelled member counts as the group's first kept member (serving_runtime.cpp:1315-1321).

    • What happens:
      • prefill_cost() charges a cancelled member 0, but the member still sets kept.
      • If it heads the group, the next live member is cut whenever its own cost exceeds the cap, although as the first live member it would have been kept. That member's clone is then released and redone in the next group.
      • Sizing charges the same cancelled member its full prompt, because cached_prefix() returns 0 for a cancelled request (:1175, :1446-1448). So the two loops disagree about what it costs.
    • Trigger: the request at the head of a group is cancelled while queued or during the wave, and the next member's credited clone is refused.
    • Fix: in both loops, a cancelled member should cost nothing and should not set kept.

    Fix this →

  • With the cache on, the tokenization before a group's first submission is no longer bounded by the budget (serving_runtime.cpp:1420-1423, :1446-1448).

    • The generate_group() comment still says that earlier members wait for later members' tokenization "bounded by the budget". That was true while every member counted its full prompt.
    • With the cache on, size is only the uncached part. A group of long, mostly cached prompts, such as re-sent chat histories with a short new turn, can tokenize many full prompts before any member is submitted. Only the uncached positions and the free session slots (:2084-2090) limit how many.
    • Fix: also bound the full prompt tokens a cache-on group prepares, or reword the comment and state the trade-off.
    • I have not measured the TTFT cost, so my confidence in how large it is is low.

    Fix this →

Recommendation

Request Changes. Requeued members should be sized by the prefix they actually got, so that persistent clone refusals cannot turn the cut into repeated clone waves. The other findings are minor and could be follow-ups.

A member cut by the clone-wave budget check was requeued with nothing
recorded about its lookup, so the next group credited it with the same
longest match and cloned the refused snapshot again. With refusals that
repeat, such as an executor that clones only at saved boundaries, N members
took about N squared clone attempts. A cut member now records the prefix it
adopted (0 after a miss), and its later sizing and lookups are bounded by it,
so each member tries a refused snapshot at most once.

A cancelled member no longer anchors a group: it costs nothing in either the
sizing loop or the budget check, so the first live member behind it is never
cut. The unreachable branch for a failed lookup in a kept group is removed,
and the generate_group() comment now states that a cache-on group bounds its
pre-submission tokenization by free session slots rather than the budget.

New tests cover the exact clone counts, a cancelled head member, a cut miss
whose pending open is released, and credited members that miss and open
together.
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review the current head d71d0543a7 (one new commit on top of 526a4b5344). It addresses the last review:

  • No repeated clones of cut members: a cut member records on its request the prefix it adopted, or 0 after a miss. Its later sizing, group lookups and single-request lookup are bounded by that, so a refused snapshot is tried at most once per member. RefusedCreditedClonesKeepTheGroupWithinItsCap now asserts exact clone counts. The trade-off is documented on reuse_bound: a cut member also ignores longer entries cached after the cut.
  • Removed: the unreachable ServingError branch in acquire_sessions().
  • Cancelled members cost nothing and never count as kept. New test: CancelledHeadDoesNotAnchorTheGroup.
  • Untested paths: new CreditedMembersThatMissOpenTogether and CutMissReleasesItsPendingOpen, the latter as coverage plus the fixture's leak check.
  • Comment: a cache-on group's tokenization before its first submission is bounded by its free session slots.
  • Test nits: holds_for() is used; QueuedMissesOpenTogether uses the default scheduler with a corrected comment.
  • PR description: updated.

A cut member's reuse bound records the prefix its lookup adopted, so that it
does not retry a longer snapshot that was refused. A miss whose cold open was
issued while the group was sized never looked anything up, yet a cut gave it
a bound of 0 and blocked all of its future prefix reuse, including entries
cached before its next pass. Only members that went through the lookup are
now bounded. The comment also says that only longer refused snapshots are
excluded: an equal-length one may be retried once.
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

Thanks for the approval. I pushed 022d3cb57f, which fixes the real issue you raised and nothing else:

  • reuse_bound for never-looked-up misses: cut() now sets reuse_bound only for members that went through the lookup (a hit, or a looked-up miss). A miss whose cold open was issued during sizing stays unbounded and can still reuse a later capture. New test: CutMemberNeverLookedUpKeepsFutureReuse, which fails without the fix.
  • Wording: the reuse_bound comment and the PR description now say that only a longer refused snapshot is excluded; an equal-length refused snapshot may be retried once.

I left three items for a small follow-up:

  • the two now-redundant cancelled.load() checks in cached_prefix() and prefill_cost();
  • tightening CutMissReleasesItsPendingOpen to assert that the miss's sizing-time session is already closed at the held step;
  • a test that pins the sizing-loop cancelled-member skip.

A cache-on group submits its members back to back, so the prompt-end capture
lanes that one-at-a-time admission recycles between members were still busy
for all but the first few, and the rest skipped their captures. The cache
then kept older entries whose cells no running request shares. With the cell
KV cache, every step reads cells up to the highest one in use, so decode
steps got slower: on Muse Glimmer with 4 capture lanes, steady decode at 8
and 16 concurrent requests was about 2% slower, with about 500 more cells
resident than on the base.

A member of a group of two or more that finds no lane at submission now
retries at each later output and queues the same prompt-end capture once a
lane frees, while it is still decoding. Like a first-output capture, it is
handed to control only once its clone has settled, using the new
PrefixCache::PromptCapture::ready(), so collecting it never blocks control.
Single requests and one-member groups keep skipping, as before.
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review the current head 8329bf153b (one commit on top of the approved 022d3cb57f). It fixes a ~2% steady-decode regression at B=8/16 with the prefix cache on, found in perf qualification on the official Muse-Glimmer Q4_K_M GGUF.

Cause: capture lanes are taken at submission and a group submits all its members together, so only as many members as there are lanes captured their prompt end. The cache kept stale entries whose cells no running request shares, which widened the cell-cache read window by 8–16%.

Fix: in a group of two or more, a member that finds no free lane retries on each later token and captures its prompt end ([0, prompt)) mid-decode once a lane frees. It hands the capture to control only after the clone completes, via the new PrefixCache::PromptCapture::ready(), so control never blocks. Single requests and one-member groups are unchanged.

Results: steady decode at B=8/16 goes from −2.4/−2.1% to about −0.5%, within session-to-session variation. The unique-prompt burst is neutral, and the shared-prefix wins are kept (+18/+44/+64% at B=16/32/48).

Tests: new MembersWithoutALaneCaptureTheirPromptsLater and PromptCaptureIsReadyOnceItsCloneSettles. The PR description is updated with the official-GGUF results and the VRAM note.

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 36m 0s —— View job


PR Review: #25727 (head 8329bf153b)

Verdict: Approve with six minor findings. The most important: deferred members retry for a capture lane at every output, so while a capped group is still deferring, a keyed turn that needs clone_prefix() finds no lane and re-prefills from position 0.

Detailed review

Summary

8329bf1 changes cache-on groups of two or more: a member that found no free capture lane at submission now retries at each later output, captures its prompt end mid-decode, and hands the capture to control once the clone settles (PromptCapture::ready()). Nothing blocks the merge. Six minor problems:

  • Deferred retries crowd keyed clone_prefix() out of the lanes.
  • Some deferred clones are wasted.
  • A bad_alloc during setup drops the request's callback.
  • The comment saying when deferral happens is wrong for the default config.
  • The comment on the engine-to-control handoff is inaccurate.
  • No test covers the ready() gate, the single-request exemption, or whether deferred entries are reused.

I read the code but did not build it or run the tests.

Code Quality

  • A bad_alloc while setting up the deferral leaves the request without its callback. serving_runtime.cpp:1419

    • inner = std::move(callback) empties callback. Only after that does the assignment back to callback heap-allocate the new closure.
    • If that allocation throws, the catch at line 1450 keeps the moved-from callback, which is empty in practice. Its comment says "Keep the original callback", but none of the request's updates reach request->emit().
    • The wrap() path at line 1805 passes a copy of callback, so it doesn't have this problem. inner = callback here does the same.

    Fix this →

  • The comment above defer_prompt_capture() treats a capped configuration as the general case. serving_runtime.cpp:1390-1392

    • It says the lanes "are still busy for all but the first few" members. That is true only when max_prefix_captures, or a checkpoint interval or policy, caps the lanes below the group size, as in the measured 4-slot config.
    • With the defaults, resolved_prefix_captures() is min(max_sessions, max_requests) (serving_runtime.h:103-106). That is one lane for every request that could be running, so every member finds a lane and nothing defers.
    • The commit message makes the same claim.

    Fix this →

Testing

  • The new tests only check that every prompt is eventually cloned. prefix_reuse_test.cpp:3621

    • ready() gate (serving_runtime.cpp:1443). No test holds executor.cloning during a deferred clone. Without the gate, control would receive the capture early and block in collect() until the clone ran. As far as I can tell, every test would still pass. Fix: hold cloning on a deferred member's clone and check that close_session_async() still completes, as PendingCloneDoesNotBlockControl does (lines 1451-1456).
    • shared gate (serving_runtime.cpp:1565). This gate is what keeps single requests unchanged. No test checks that a request admitted alone while the lane is busy never clones its prompt later.
    • Deferred entries. Nothing checks that they are inserted and reused, or that the lane comes back. Fix: resubmit each prompt and expect 2 reused tokens (as at line 1462), then check that a fresh prompt still clones.
    • Stale comment. QueuedMissesOpenTogetherAndShareOneCaptureLane (lines 3614-3615) still attributes its single clone to the busy lane. Now the other members skip only because queue() submits with a one-token limit, so their only update is terminal (line 1423).

    Fix this →

Thread Safety

  • The cross-thread handoff of capture_lane and prefix_capture is undocumented, and the nearest comment is inaccurate. serving_runtime.cpp:1399, :1437

    • TextState::capture_lane is a plain bool (line 63). Before this commit only control wrote it (lines 1386, 1799). Now the engine thread writes it (line 1437) and also calls capture_at() and ready() on prefix_capture.
    • This is race-free only because control reads both fields after enqueue_capture() (under mutex_) or after the request settles, and the engine stops touching them once pending clears. A later change that reads them earlier from control, such as cancelling a pending capture, would race.
    • "The state lives on the engine thread, which alone calls the callback" covers only the local Deferred, and it is not quite true. A request rejected before admission runs its callback inline on control (runner.h:87-89). That case is harmless only because a terminal update never takes a lane.
    • Fix: replace that sentence with the handoff rule.

    Fix this →

Performance

  • Deferred members take the lanes that keyed clone_prefix() needs, although the PR lists keyed paths as unchanged. serving_runtime.cpp:1422-1424

    • Each deferred member retries try_acquire_capture_lane() at every output on the engine thread, so it takes a lane as soon as control frees one.
    • clone_prefix() tries once, on control (line 826). If it finds no lane, lines 1084-1086 keep the reset, so the keyed turn re-prefills from position 0 instead of cloning its prefix.
    • In the measured 4-slot config, a group of 16 keeps every lane busy for several more decode steps after its first output. A keyed turn that arrives in that window pays a full re-prefill.
    • The PR's trade-off mentions only new single requests, which merely skip a capture.
    • Fix: when there are two or more lanes, let a deferred retry take a lane only while another stays free. With one lane the two can't both be served, so at least add the keyed cost to the trade-off note.

    Fix this →

  • Some deferred clones are wasted. serving_runtime.cpp:1795, :1813

    • Identical prompts. touch_identity() runs only at submission, before any member's capture is collected. So in a group that repeats one prompt, such as n samples of it, every member without a lane later clones that same prompt, and each clone holds a lane for about a step. insert_identity() keeps the existing snapshot for a duplicate key (prefix_cache.h:326), so these clones are discarded. Before this commit those members simply skipped. Fix: in generate_group(), don't defer a member whose prompt equals an earlier kept member's.
    • Recurrent executors (low confidence). A deferred clone at [0, prompt) is taken after the session has moved past the prompt. executor.h:101-103 requires an executor to refuse it unless it can recover the complete state at upto. On a hybrid or SSM executor, every deferred attempt would then cost a refused clone and hold a lane for about a step. I did not check whether any serving executor in scope is affected. If one is, stop deferring once a deferred clone comes back refused.

    Fix this →

Recommendation

Approve. Nothing blocks the merge. Handle the keyed-lane contention first, in code or at least in the PR description's trade-off. The rest are a one-line exception-safety fix, two comment fixes, a duplicate-prompt check, and more tests.

The deferred prompt-end capture moved the request's callback into its
closure before allocating the closure, so a std::bad_alloc there left the
request without a callback. It now copies the callback, so a failed setup
keeps it intact.

The comments now say that deferral handles a lane cap below a group's size
(with the default lane count every member finds a lane), and state the
handoff of capture_lane and prefix_capture between the callback and control.
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

Thanks for the approval. I pushed 56bb1532da:

  • Exception safety: the deferral closure now copies the callback instead of moving it, so a bad_alloc while setting up the deferral leaves the request with its original callback.
  • Comments: the comment above defer_prompt_capture() now says it covers members that found no lane, which only happens when lanes are capped below the group size. The cross-thread handoff of capture_lane and prefix_capture is documented: the callback owns them until enqueue_capture(), and control reads them only after taking the capture under mutex_ or after the request settles.
  • Keyed-lane contention: stated in the PR description. While a capped group is still deferring, a keyed turn whose replacement needs clone_prefix() may find no lane and re-prefill from position 0. Keyed paths are no longer listed as unchanged.

I left three items for follow-ups:

  • tests that pin which entries the cache ends up holding;
  • the wasted deferred clones;
  • de-duplicating identical prompts before deferred capture.

This branch was previously deployed

1 inactive deployment
cadence — 56bb1532 Deployed Nov 25, 2026 by Gasoonjia via hifi-op-test / hifi4 #41038
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant