OriginalVerifyQsaJournal keeps its owners as Option behind accessors; lend() hands the twelve index images and mapped journals to the prompt executor without dropping the journal (and so the graphs), take_back() accepts them only when every address the captured commands bind is unchanged (else the journal is failed for good and the owners go back to the caller). The pure loan state machine (owner_loan.rs) has unit tests that run without a GPU. GraphReuse gets begin/end over a HeldAssembly trait (park, lend, take_back, rearm): the kept assembly is reused only for an equal key, owners at the same addresses and an accepted re-arm; anything else retires it after the MTP drafter's bindings are released, and the owners are never lost. DecodeResources implements the trait (owner loan real; park and rearm refuse until the verify bank has them, so nothing is kept and every request records as before). The lifecycle fake models the bank (generation, counters, wait flag, canonical image) and the owners, and the scenarios the real implementation must pass are in docs/experiments/decode-graph-reuse.md. Switch off: unchanged path. No speedup claim. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
20 KiB
Decode graph reuse across requests (ledger row Q7)
Status: part 1 and the stack protocol are coded behind LELEKA_DECODE_GRAPH_REUSE (off by default, typed setting
serve.decode_graph_reuse): the reuse policy (DecodeGraphKey, GraphReuse::begin / end, HeldAssembly), the QSA
owner loan in the driver journal (B2), the drafter-binding decision (B3), the shared-expert pin and weights epoch, all
tested on the lifecycle fake. The real stack does not keep an assembly yet: B1 (the assembly borrows the stack) is the
speed session's handle change in original_verify_window_{moe,gr,proj,qsa}.rs, and the verify bank's park / rearm /
reseed (part 2) is theirs too; DecodeResources::park and rearm refuse until then. With the switch on, open says so
on stderr and every request records its graphs, as without the switch. No speedup claim.
1. Why the graphs are recorded per request
decode_phase (OriginalServeStack) calls assemble_decode -> AssembleInputs::assemble (original_serve_verifier.rs) for
every request, and teardown_decode -> disassemble at its end. assemble is: prepare (geometry, canonical GDN image
uploaded from the session's priors, QSA gamma), OriginalVerifyQsaJournal::new over the twelve QSA owners, then
capture_verifier: a new OriginalVerifier (new Physical arena, mapped allocations, two streams), one aggregate
(OriginalVerifyWindowResources) per T = 1..=max_t plus one for the commit graph, and record_all (nine graphs at T <= 8
with the mode17 policy, 54-62 ms capture + 27-30 ms instantiate). disassemble closes the verifier (drains, drops every
graph and aggregate), which releases the aggregates' references to the QSA journal so into_owners can take the owners back,
and release_mtp drops the MTP drafter's programs bound to this verifier's bank.
The recording is per request because of OWNERSHIP, not because the kernel arguments change:
- The QSA owners (twelve index images + mapped K/V journals) belong to the prompt executor. The next request's prefill
writes them (chunks, prefix-cache import, rollback). They can only get there by moving out of the journal
(
Rc::try_unwrapininto_owners), which requires every graph that holds the journal to be gone. - The resources borrow the stack:
DecodeResources<'s, 'ctx>holds&'s DenseWeightCache,&'s MoeWeightCache,&'s OriginalNativeOutput,&'s DeviceBuffer(PLE history and scratch),&SharedKeys(a value of the request's own stage). A value that borrows fields ofOriginalServeStackcannot be stored in it (self-reference); this is whyDecodeViewborrows the fields one by one. - The shared experts and routers are LRU entries of the MoE cache (
ensure_original_verify_shared); the prompt path loads layer by layer and may evict and reload them, so their device addresses are not guaranteed to survive a prefill. - The MTP drafter's round programs read the verifier's bank (final R span) and are released with it (
mtp_release_verifier); they are re-captured against the next bank (spansdraft.*, a second cost of the same cause).
docs/decode-parity.md already records this as "Verifier persistence: not done ... needs the executor to use the owners through
the journal".
2. What the captured graphs point at
Per-request buffers (created by assemble, addresses change every request today; data must be re-seeded if the buffer is kept):
| Resource | Created in | Per request | Can be stable |
|---|---|---|---|
| Canonical GDN image (36 layers x 12848128 + 10240*3 f32, ~118 MB) | prepare_assembly (original_verify_canonical_gdn(states, histories)) |
allocated and uploaded from the session priors | yes: keep the buffer, re-upload (118 MB H2D, stays in the per-request cost) |
Verifier arena, prof, 15 mapped allocations, window modules |
OriginalVerifier::new |
new | yes: sized by verify_geometry(max_t, max_cells, blobs); only the window state is data (last_t, last_position, generation, staged tokens) |
| Head rows per T, embedding rows per T, GDN journal, window aggregates | aggregate() |
new | yes, part of the kept assembly |
QSA journal Rc<OriginalVerifyQsaJournal> |
OriginalVerifyQsaJournal::new |
new Rc around the executor's buffers | the buffers are the executor's (fixed addresses); the Rc must outlive requests |
| Graphs, streams, event | record_all |
new | the point of the feature |
Stable resources the graphs also point at (owned across requests today, so reuse needs only a proof that they were not
reallocated): dense weights and gamma, router and shared experts (MoE cache entries, see 1.3), OriginalNativeOutput, PLE history
and PLE scratch (stack buffers), RoPE tables, the registered expert banks of the pcie path, the VRAM expert cache slots.
Context length, window width, expert tier:
- Context length and positions are DATA (staged into mapped host memory / device flags before each
run); the arena and the QSA journals are sized formax_cells, fixed by the configuration. A longer context does not change the graphs. - The window width T is the graph identity (
OriginalGraphKey::VerifyWindow(t), t in 1..=8) andmax_tis the arena geometry.verifier_max_tcan only fall during a process (narrow_window_policyafter a graph OOM); a held assembly recorded for anothermax_tmust be retired. - The expert tier:
pcie_mode(0 DMA, 2 copy kernel) and the per-layer role bytes are baked into the graphs (set_pcie_mode,pcie_role_bytes); the VRAM cache slot contents are data (published plan), the cache object and the registered banks are addresses.decode_pcie_modeis a function of the configuration and of the cache being present. - Process-level switches resolved at recording time:
qsa_cluster_requested(cluster top-k), the sm120 switches (from_env),WindowPolicy::mode17(). They are fixed for a process; they are in the key so a change is caught.
3. Key and invalidation (coded: original_serve_stack/decode_graph_reuse.rs)
DecodeGraphKey { max_t, max_cells, pcie_mode, tier, cluster_topk, weights_epoch, owners_epoch }. weights_epoch and
owners_epoch are counters bumped by the owners of the physical buffers whenever one that a window reads or writes in place
is freed, moved or reallocated. GraphReuse::begin((key, seed), owners, retire) returns the held assembly only for an equal key, with the owners taken back
at the addresses the graphs bound and HeldAssembly::rearm(seed) accepting; otherwise it retires it (Why::KeyChanged(name) | OwnersChanged | RearmRefused | NothingHeld | Disabled) and gives the owners back to record a new one. end parks the assembly
of a clean request, lends the owners home and keeps it; a failed or cancelled request keeps nothing; invalidate retires it
(broken stack, reconfigure, narrowed window). A reuse that cannot show an equal key is a
re-record. The lifecycle fake (lifecycle_fake/graphs.rs, tests backend/lifecycle_tests/graphs.rs) bakes the key and the seed
into its graph set and fails the request on a replay for another key or without a re-arm: kept and re-recorded sets give the
same text, a kept set costs no recording, each of the seven key inputs forces a re-record, a refused re-arm and a failed
request do not replay.
Owners of the epochs:
weights_epoch:MoeWeightCache::weights_epoch()counts every raw entry the cache evicted (room,room_protected) and every pin release;pin_for_window(keys)/unpin_window()makeis_pinnedtrue for the 192 shared tensors so the prompt path cannot evict them while a set is held (the existing eviction rule, as for the profile's permanent pool). Not wired yet: pinning shrinks what a prefill can evict, and a prefill that finds nothing evictable fails withInputAllocation, so it is switched on only together with a held set. The routers and the other dense operands live in the dense cache, which does not evict after open.owners_epoch: replaced by the journal's own check (B2):take_backcompares the window addresses (window_addresses(layer)for the twelve layers: resident pools, table, host copy, resolver, pooled and dead key spans) taken when it lent the owners with those of the owners that come back; any difference is a refusal and a re-record.
4. What is not done and why
B1. The held assembly cannot borrow the stack (blocked: forbidden files)
DecodeResources<'s> is OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>>; the aggregates hold &'a DeviceBuffer<'ctx> into the dense cache (projections, GR, QSA operands, gamma), the PLE history and scratch, the RoPE tables
and the MoE cache (shared experts, original_verify_moe). The prompt path of the next request needs &mut MoeWeightCache and
&mut DeviceBuffer (seed_ple_history), which a live &'a forbids, and a value that borrows fields of the stack cannot live in
the stack. No safe restructuring of the stack alone fixes this: an owner above the stack would have to hold the MoE cache
immutably (the prompt path mutates it) or split the shared experts out of it (the prompt path loads them through it).
Exact change that removes the borrow (files of the speed session's area, or operand types they use):
original_verify_window_moe.rs(5 sites:OriginalVerifyMoeLayerWeights),original_verify_window_gr.rs(16:PleBuffers,HcLayerBuffers, ...),original_verify_window_proj*andoriginal_verify_window_qsa.rs(5),qwen_dispatch/fixed_operands.rs(34): replace the&'a DeviceBuffer<'ctx>operands with a shared handleDeviceRef<'ctx>(anRcto the allocation plus offset and length,Clone, derefs to&DeviceBufferfor the existingqwen_address()calls). The aggregates then have no'a,OriginalVerifyWindowResources<'ctx>andDecodeResources<'ctx>can sit in the stack, and the borrow of the caches ends atassemble.- The caches hand out handles:
DenseWeightCache::original_verify_*andMoeWeightCache::raw_sharedclone theRcof the entry (the entries becomeRc<DeviceBuffer>); an unpinned entry that a held set still references is dropped from the cache's book on eviction but not freed (the set keeps the allocation alive;weights_epochbumps, so the set is retired at the next request). seed_ple_historywrites through the shared handle (a&selfupload ofDeviceBuffer, device idle).
B2. QSA owner loan (coded, driver)
OriginalVerifyQsaJournal (cuda-driver/src/qsa_verification_commit*, not a speed-session file) keeps its owners as
RefCell<Option<..>> behind the accessors index, index_mut, kv, kv_mut, which refuse (InvalidQwenShape) while the
owners are out, so a graph run, a window arm or a commit over a lent journal fails instead of touching nothing.
lend(&self) -> Result<OriginalQsaOwners>: needs the journal valid, not armed, every index idle and published and standing where its journal does. It records theOwnerPrintof each of the twelve layers: thewindow_addresses(resident pools, table, host copy, resolver, pooled and dead key spans) and the image's tail and block-position addresses, i.e. every address the captured append and attention commands bind; then moves the 24 owners out (all 24 are borrowed and found full before the first moves).take_back(&self, owners) -> Result<(), (Error, owners)>: takes the print of the returning owners, requires all twelve idle at one position (check_aligned) and the print equal to the lent one. Equal: the owners are put back, the journal stands at their position, disarmed. Anything else (an address moved, a resolver reset, a print that cannot be taken, called while not lent) fails the loan and the journal for good (validate_contextthen answersContextPoisoned) and gives the owners back to the caller with the error, so none is lost; the stack retires the assembly.- The state machine is
cuda-driver/src/owner_loan.rs(pure; unit tests run without a GPU: round trip, a changed address or a missing print fails for good, steps out of order change nothing). into_owners(the retire path) keeps working and refuses a lent journal.- The stack side:
DecodeResourcesimplementsHeldAssembly(original_serve_verifier/held.rs):lend/take_backmap the twelve layers to and from the executor's 48 slots (place_owners) and refuse owners that are not at exactly the assembly's slots;parkandrearmreturnfalseuntil the bank has them (below). - GPU check (orchestrator, with the speed session's
park/rearm): lend, run a prompt over the executor's owners,take_back: accepted when the prompt only appended;take_backof owners after aresetof the mapped journal (new resolver) must be refused.
B3. MTP drafter bound to the kept bank (coded in the policy, not in the real stack)
GraphReuse::begin / invalidate take a retire callback that runs before the retired assembly is dropped; end never
calls it when the assembly is kept. The stack passes || executor.mtp_release_verifier(binding) (the current release_mtp).
So a kept bank keeps the drafter's cached round programs (no first-draft capture in the next request) and a retired one
releases them before its bank closes. Lifecycle fake: drafter_releases is 0 across kept requests and exactly 1 per
retirement (key change, owners moved, refused re-arm, invalidate) and per request with the switch off or park refused.
Open point for the GPU run: the drafter's tail keeps the last staged window of the previous request; the first request after
a re-arm must clear it (today set_prompt_len does; check OriginalMtpActor for anything keyed on the previous request).
The stack side, mechanical once the bank has park / rearm and the assembly stops borrowing the stack (B1)
OriginalServeStackgetsheld: GraphReuse<DecodeResources<'ctx>>(GraphReuse::new(settings.serve.decode_graph_reuse)), and anowners_epoch/weights_epochsource for the key (MoeWeightCache::weights_epoch(), pinning viapin_for_window(&shared)when a set is kept andunpin_window()on retire).decode_phase: buildDecodeGraphKeyindecode_stage(fromverifier_max_t,max_cells,pcie_mode, tier present,qsa_cluster_requested, the epochs). Replaceexecutor.take_qsa_owners()+assemble_decodebyheld.begin((&key, &base), owners, retire):Reused(resources)skipsAssembleInputs::assemble;Record { owners, .. }assembles as today over those owners;Lostmarks the stack broken.teardown_decode:match held.end(&key, resources, |owners| home.adopt(owners)):Keptreturns (norelease_mtp, nodisassemble);Retire { assembly, owners_home: false }is the current path (release_mtp,disassemble, adopt);Retire { owners_home: true }callsrelease_mtpand drops the assembly (the owners are already home).held.invalidate(retire)onreconfigure,reset_expert_tier, a broken stack andnarrow_window_policy.- With the switch off
GraphReuse::endalways returnsRetire { owners_home: false }andbeginreturnsRecord { Disabled }with the owners untouched: the path is the current one.
Scenarios the real implementation must pass (the lifecycle fake runs them: backend/lifecycle_tests/graphs.rs)
| Scenario | Expected |
|---|---|
| switch off, 3 requests | 3 recordings, 3 drafter releases, set never held |
| switch on, 4 requests, different prompts | text equal to the switch-off run; 1 recording, 3 re-arms, 0 drafter releases; the 3 later requests pay no recording |
full cycle: request 1 records, park, request 2 re-arms |
bank generation 1 then 2; a window token of request 1 refused after the re-arm, a window of request 2 accepted; windows, commits and the wait flag count request 2's rounds only (4, not 8); the canonical image holds request 2's seed, not request 1's |
| each key input changed (max_t, max_cells, pcie_mode, tier, cluster top-k, weights epoch, owners epoch) | re-record with KeyChanged(name), 1 drafter release, the new set kept again |
owners moved by the prefill (take_back refused) |
re-record with OwnersChanged, owners not lost, the new set kept |
rearm refused |
the owners are lent out again, the set retired (1 drafter release), re-record RearmRefused, next request re-arms |
park refused |
not kept, owners home, every request records |
| request failed or cancelled | not kept, owners home, next request records NothingHeld; invalidate of a kept set releases the drafter once |
Part 2: the verify bank's re-arm API (speed session's files; the policy codes against Reusable::rearm)
Needed in crates/cuda-driver (original_verify_schedule/*, original_verify.rs, original_verify_gpu_plan*):
/// Seed of the next request: the session's recurrent priors, in the canonical image's layout.
pub struct OriginalVerifyRearm<'s> {
pub gdn_states: [&'s [f32]; 36], // 128*48*128 f32 each
pub gdn_histories: [&'s [f32]; 36], // 10240*3 f32 each
pub ple_history: &'s [f32], // 9*10240 f32
}
impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> OriginalVerifier<'ctx, R> {
/// End of a request: drain both streams, wait a pending commit; keep graphs, bank, streams and event.
pub fn park(&mut self) -> Result<()>;
/// Start of the next request over the same recording. `Err` leaves the verifier unusable (the caller retires it).
pub fn rearm(&mut self, seed: OriginalVerifyRearm<'_>) -> Result<()>;
}
impl OriginalVerifyCanonicalGdn<'_> {
/// Overwrite the image in place (same device address): states and histories, 117.7 MB host to device.
pub fn reseed(&self, states: [&[f32]; 36], histories: [&[f32]; 36]) -> Result<()>;
}
Preconditions of rearm: park ran (both streams idle, commit_pending, window_ready and active false, failed false,
not released); every captured graph is quiescent; the QSA journal is not armed and not lent. State it resets (everything a
fresh OriginalVerifier::new + record_all leaves, so the first run of the new request sees what the first run after a
recording sees):
OriginalVerifier:windows = 0,commits = 0,completed_generation = None,completed_ids = [0; 8], profile counters;split,groups,resource_keysas recorded.OriginalVerifyBank:last_t = 0,last_position = 0,last_tokens = [0; 8],last_keep = 0,generationadvanced (oldOriginalVerifyRow/OriginalVerifyWindowvalues are refused),released = false,pcie_sourcescleared (held until the previous copy-stream fence);pcie_mode/pcie_rolesunchanged (they are in the key).- Every device and mapped flag the graphs wait on or raise (
verify_wait_flag_ge_kernel/_or_kerneloperands, the group flag rings and doorbell ofraise_group_flag/wait_doorbell, theverify_clear_statuswords, the ident-hit and tail-snapshot flags): back to the value they have at the end ofrecord_all(zero). The graphs compare against a "want" that counts up inside a window; it must restart. - The gpu-plan state in
Physical.mapped[..](the published plan, the fetch tables) andprof: cleared. - The canonical GDN image (
reseed) and the PLE history image (seed.ple_history, through the journal'splehandle).
Postcondition for the stack: the first stage_window of the new request is accepted at any position the QSA owners stand at.
The policy retires and re-records on any Err or false, so a partial re-arm is safe.
5. Validation (GPU, orchestrator)
Identity of greedy output reuse-on vs off over N requests with different prompts and lengths and a forced eviction in between
(must re-record, and match); paired A/B of decode.assemble, decode.disassemble, record.capture, record.instantiate,
record.modules, the first-draft capture in draft.*, and end-to-end request time; VRAM at the decode low-water mark (a kept
set holds the graph pool during prefill: the prefill arena and loan ladder budget shrink by the pool size).
6. Expected size of the win and what stays
Removes record_all (83-85 ms) and the aggregate construction; the canonical image upload and per-request state seeding stay
(about 15-25 ms of the 98-109 ms), decode.disassemble (B4, 11.7 ms) becomes a park. The kept pool costs VRAM during prefill.