Merge of the speed session's driver part (DeviceRef handles, OriginalVerifier park/rearm, OriginalVerifyCanonicalGdn reseed; ptx manifest and seal plan entries of both sides kept, ledger rows of both sides kept) with the owner loan: the journal's owners are Option behind accessors, lend() uses the same idle precondition as the speed session's require_idle. DecodeResources implements HeldAssembly for real (park, rearm from the session priors, lend and take_back through the journal loan; every refusal retires the set). OriginalServeStack holds a GraphReuse; decode assemble asks begin first (re-arm, refill queue; or the owners back to record), teardown keeps the assembly for a clean request (drafter end_request_keep_bank, shared-expert pin, park, lend, adopt) or runs the old teardown; retirement releases the drafter before the bank closes, in begin, close and reset_expert_tier. The MoE cache pins the shared experts while a set is held and counts freed window entries (weights epoch). Switch off: begin is not called and teardown runs the old body unchanged. Tests: GraphReuse policy with a logging probe (switch off touches nothing, key change, moved owners, refused re-arm, lost owners, order release before drop), keepable outcomes, the lifecycle fake scenarios, the GPU-free loan state machine. Not run on a GPU. No speedup claim. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
23 KiB
Decode graph reuse across requests (ledger row Q7)
Status: wired behind LELEKA_DECODE_GRAPH_REUSE (off by default, typed setting serve.decode_graph_reuse), unit tested
host-side and on the lifecycle fake, NOT run on a device. The speed session's driver part (DeviceRef handles, OriginalVerifier:: park / rearm, OriginalVerifyCanonicalGdn::reseed, docs/experiments/verify-decode-graph-reuse-handles.md) is merged in;
this side is the policy (DecodeGraphKey, GraphReuse::begin / end, HeldAssembly), the QSA owner loan in the journal
(B2), the drafter decision (B3), the shared-expert pin and weights epoch, and the stack wiring (section 4). With the switch off
every path is the one before this change. No speedup claim; the sections to compare are in section 5.
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. The pieces: handles (speed session), owner loan, drafter, stack wiring
B1. The held assembly cannot borrow the stack (done by the speed session: DeviceRef handles)
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)
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 (wired)
OriginalServeStack::held: GraphReuse<DecodeResources<'ctx>>, enabled by the setting.DecodeView::assembletakes the QSA owners from the executor as before, thenbegin_kept: with the switch off it returns them untouched (Start::Record, the old path); on, it builds theDecodeGraphKey(graph_key:verifier_max_t,max_cells,decode_pcie_mode, tier present,cluster_topk_requested(),MoeWeightCache::weights_epoch()) and the seed (RearmSeed: binding and the session'sOriginalVerifiedBase) and asksGraphReuse::begin.ReusedskipsAssembleInputs::assembleand queues the lent-slot refill that assembly's prepare step would have queued; a refill that cannot be queued lends the owners out again and retires the set (the failure goes throughresolve_assembled, which adopts the owners).Record { owners, why }assembles as today over those owners and prints why a kept set was not reused (decode graphs recorded again: ...).Lostmarks the stack broken.DecodeResourcesimplementsHeldAssembly(original_serve_verifier/held.rs):park=OriginalVerifier::park,rearm=OriginalVerifier::rearmwith the 36 GDN priors (gdn_layer_priors) and the PLE history of the session's base,lend/take_back= the journal's loan mapped to the executor's 48 slots. Any refusal or error answersfalse/None/Err, and the policy retires the set.servecomputes the key before the request runs;teardown_decode(decode_teardown.rs) keeps the assembly only for a request that was served without an error, whose host outcome is neitherfailednordirty(keepable), and whose drafter and pins went through:mtp_end_request_keep_bank(the drafter forgets an unfinished draft and the staged window, keeps its programs),MoeWeightCache::pin_for_window(shared), thenGraphReuse::end(park, lend,QsaOwnerHome::adopt). Not kept: the old teardown (release_mtp,disassemble, adopt), or, when the owners were already home,release_mtpandverifier.close(). Kept: norelease_mtp, nodisassemble, spansdecode.keep(park + lend + adopt) in their place.- Retirement always runs
retire_keptfirst (release_mtp=mtp_release_verifier, thenunpin_window) and drops the assembly after it, so the bank is never closed under the drafter. It happens inbegin(changed key, owners at other addresses, refused re-arm), inOriginalServeStack::close, and inreset_expert_tier. - Weights: the assembly holds handles, so an evicted tensor stays alive; the pin only avoids loading it a second time. A freed
entry the window reads, and the release of the pins, move
weights_epoch, which retires the set at the next request. - With the switch off
Endingcarries noKeep,GraphReuse::beginis not called, andteardown_decoderuns the old body unchanged.
Drafter state keyed on the previous request (checked)
OriginalMtpDrafter holds: in_flight (a draft launched and never finished), the tail owner's staged verifier window
(full.source), the cached round programs (graphs, graph_metadata), direct_window_mode, ring_owner, policy_key.
end_request_keep_bank clears the first two (after draining the draft stream) and keeps the rest: the programs name the bank's
final-R span (unchanged for a kept bank; stage_round refuses a window at another address) and the draft ring
(ring_owner, policy_key are checked by the drafter on use). The actor's other state (DraftSettings, prompt length, max
drafts, the coupled host) is set per request by the stack as before. To confirm on the GPU: the draft trace and the top-16
logprobs of request 2 equal the fresh-assembly run, and draft.* shows no capture at the first draft.
Scenarios (the lifecycle fake runs them; the real wiring answers the same way where it can run host-side: 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 (done by the speed session; the text below is the spec it was written from)
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: greedy output and top-16 logprob rows over N requests with different prompts and lengths, switch on vs off,
with an eviction of a shared expert in between, a changed
max_t(graph OOM fallback) and a request that fails in the middle (each must re-record and match); the draft trace of request 2 equal to the fresh-assembly run. - The stderr lines:
decode graph reuse ... onat open;decode graphs recorded again: <why>for every request that did not re-arm (expect none after the first in a steady run;OwnersChangedmeans the prefill moved an owner buffer,RearmRefuseda driver refusal). - Spans, paired A/B on the same workload (cache state recorded):
decode.assemble(recording) againstdecode.reuse(take back + re-arm),decode.disassembleagainstdecode.keep(park + lend + adopt),record.capture,record.instantiate,record.modules(should be 0 after the first request), the first-draft capture indraft.*,prefill.*(the pins and the kept pool must not slow the prefill), end-to-end request time. - VRAM at the decode low-water mark (
vram_note "decode end before disassemble") and during the prefill: a kept set holds the graph pool, the bank arena, the mapped staging and the 118 MB canonical image; the loan ladder and the prefill arena budget see that much less. - The GPU tests of the speed session's doc (section 5 of
verify-decode-graph-reuse-handles.md) and the journal check of B2 (lend, a prompt over the owners, take_back accepted; aresetof the mapped journal between must be refused).
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.