DecodeGraphKey (shape, tier, pcie mode, cluster top-k, weights and owners epochs) and GraphReuse hand a kept assembly out only for an equal key after Reusable::rearm accepted the new request's seed; anything else retires it and records. The lifecycle fake bakes key and seed into its graph set and fails a stale replay: kept and re-recorded sets give the same text, each key input forces a re-record, a refused re-arm and a failed request do not replay. MoeWeightCache gets pin_for_window / unpin_window / weights_epoch (not wired). With the switch on, open states that the stack cannot keep the graphs yet; every request records as before.
Not done: the assembly still borrows the stack (needs handles instead of &'a DeviceBuffer in original_verify_window_{moe,gr,proj,qsa}), the QSA owner loan and the MTP binding follow it, and the verify bank's re-arm API is the speed session's. Exact changes in docs/experiments/decode-graph-reuse.md. No speedup claim.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
15 KiB
Decode graph reuse across requests (ledger row Q7)
Status: part 1 coded behind LELEKA_DECODE_GRAPH_REUSE (off by default, typed setting serve.decode_graph_reuse): the reuse
policy (DecodeGraphKey, GraphReuse, tested on the lifecycle fake), the shared-expert pin and the weights epoch in the MoE
cache. The stack does not hold an assembly: B1 below (the assembly borrows the stack) cannot be done without editing
original_verify_window_{moe,gr,proj,qsa}.rs, and part 2 (the verify bank's re-arm API) is the speed session's. 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::acquire((key, seed), record) returns the held assembly only for an equal key and
only if Reusable::rearm(seed) accepts; otherwise it retires it and calls record() (Armed::Recorded(Why::KeyChanged(name) | RearmRefused | NothingHeld | Disabled)). release keeps an assembly only after a clean request (a failed or cancelled one drops
its set); 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: not coded (needs B2): the journal compares 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 (not coded: dead until B1, touches 25 hot-path sites of the journal)
OriginalVerifyQsaJournal keeps indices: [RefCell<OriginalQsaResidentIndex>; 12] and mapped: [RefCell<...Journal>; 12].
Needed: both as RefCell<Option<..>> behind accessors (index(layer), index_mut, kv, kv_mut, which return
InvalidQwenShape while lent), lend(&self) -> Result<QsaOwners> (requires not armed, every index idle and published; records
the twelve window_addresses; leaves the journal lent) and take_back(&self, QsaOwners) -> Result<()> (requires the same
addresses and check_aligned at the new position, else marks the journal failed so the set is retired). The executor side
needs no change: take_qsa_owners / adopt_qsa_owners already move the physical owners by value and keep their buffers; the
stack calls journal.lend() where it now calls disassemble and journal.take_back(take_qsa_owners()) where it now builds a
journal. The driver's into_owners stays for the retire path.
B3. MTP drafter bound to the kept bank (not coded: follows B1)
teardown_decode calls release_mtp (mtp_release_verifier) before the bank closes. With a kept bank it skips that call
(the drafter's cached round programs stay valid for the same bank and are not re-captured, which also removes the first-draft
capture of every request), and the retire path (GraphReuse::invalidate, a changed key, a refused re-arm) calls it before the
bank closes. The drafter keeps nothing keyed on the request (its tail is cleared by OriginalMtpActor::set_prompt_len as today).
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.