docs/experiments: driver side of the decode graph reuse (DeviceRef handles, park, rearm, reseed), ledger Q7

What changed, the reset checklist with the code location of each item, what is not covered, how to test it
on a GPU and the risks. No measurement: nothing was run on a device.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-10 00:24:02 +01:00
co-authored by Claude Sonnet 5.5
parent a3b55ac312
commit 0e84729686
@@ -0,0 +1,146 @@
# Decode graph reuse, driver side: shared handles, park, re-arm (ledger row Q7)
Status: implemented and unit tested without a GPU; NOT run on a device. Nothing changes on the existing paths (no new
switch, no kernel, no argument of a captured launch). The policy side (`LELEKA_DECODE_GRAPH_REUSE`, the key, the pin and
epoch, the owner loan, the drafter binding) is the hex-finish team's; this is the part they listed as blocked
("B1" and "Part 2" of `decode-graph-reuse.md`, branch `claude/prefill-latency` a4a8d597f). No performance claim:
the section to watch is `decode.assemble` (`record_all` 83 ms of 98-109 ms per request, `decode-graph-reuse.md`).
## 1. What changed
### 1.1 `DeviceRef<'ctx>` (crates/cuda-driver/src/device_ref.rs)
An `Rc` handle to a device allocation, `Clone`, `Deref<Target = DeviceBuffer>`:
* from a whole buffer (`from_buffer`, owns it) or from a `DeviceSlice` (`from_slice`: the alias of exactly
`[offset, offset + len)` of a 64 MiB slab, plus the `Rc` of the slab that keeps it alive). Offset and length are the
alias' own (`len()`, the address); there is no separate `(offset, len)` pair to disagree with the buffer.
* `release(self)`: the sole holder frees (the last handle of a slab frees the slab); with other holders it frees nothing
and returns `Ok`, the last holder frees on drop. So a cache that evicts or closes while an assembly holds an entry
leaves the allocation alive and the cache's own accounting.
* `DeviceBuffer::copy_from_shared(&self, ..)`: the `copy_from` transfer through a shared borrow (`copy_from` now calls it),
used to seed the PLE history behind the handle.
### 1.2 The `'a` is gone from the verify-window types
`OriginalVerifyWindowResources<'ctx>`, `OriginalVerifyResources`, `OriginalVerifyGdnJournal`, `OriginalVerifyGdnWeights`,
`OriginalVerifyQsaJournal` (its twelve gamma buffers), `OriginalVerifyRope` (now `Clone`, not `Copy`; its optional tables
are handles, always `None` in the serve stack), the GR/MoE/projection/QSA bindings and their element types now hold
`DeviceRef`s. Files: `original_verify_window_{moe,gr,proj,qsa}.rs` (+ their subdirectories), `original_verify.rs`,
`original_verify/**`, `original_verify_window_ops*`, `qsa_verification_commit*`, `original_serve_access.rs`, the preflight
probe in `crates/cuda-driver/tests`. `DecodeResources<'ctx>` (engine) follows.
`qwen_dispatch/fixed_operands.rs` is NOT changed: its 34 `&'a DeviceBuffer` are the operand groups of single kernel
calls (`MtpGrWeights`, `QsaPackedKv`, ...), built and dropped inside one call; nothing stores them, so they do not
tie an assembly to the caches.
### 1.3 Engine plumbing (minimum to hand out clones; the files are listed in the report)
* `DenseWeightCache::buffers: Vec<DeviceRef>`; `handle(i)` / `handles([i; N])` clone; the slot accessors are split into
`*_slot(s)` (role to index, owner check) plus the unchanged `&DeviceBuffer` accessors, so the prefill callers
(`gdn_matrix`, `gdn_aux`, `qsa_matrix`, `qsa_norms`, `ple_aux`, `router`) keep their types.
* `original_verify_gr/_qsa/_projections/_gdn_weights/_qsa_gamma` and `router_handle` return handles.
* `MoeWeightCache`: `EncodedWeight::Raw(DeviceRef)`; `raw_shared` returns a clone; eviction (`EncodedWeight::close`)
releases the cache's handle only.
* Stack: `ple_history` / `ple_scratch` are `DeviceRef`s; `AssembleInputs` / `VerifyWeights` take `&DeviceRef`;
`seed_ple_history(&DeviceRef)`.
### 1.4 Hot loop
Handles are cloned only while an assembly is built (engine caches, `assemble_parts.rs`) and in `park` / `rearm`.
The recorders, `OriginalVerifier::run` / `commit`, the journals and the graph validation read them through `Deref`
(`&**handle`, `Option::as_deref`); no allocation, no count traffic. Guard test:
`device_ref::tests::the_window_and_journal_modules_never_clone_a_handle` (source scan of the window-ops and journal modules).
## 2. The API
```rust
pub struct OriginalVerifyRearm<'s> { pub gdn_states: [&'s [f32]; 36], pub gdn_histories: [&'s [f32]; 36], pub ple_history: &'s [f32] }
impl OriginalVerifier<'ctx, R> { pub fn park(&mut self) -> Result<()>; pub fn rearm(&mut self, seed: OriginalVerifyRearm<'_>) -> Result<()>; }
impl OriginalVerifyCanonicalGdn<'_> { pub fn reseed(&self, states: [&[f32]; 36], histories: [&[f32]; 36]) -> Result<()>; }
```
`park`: refused (nothing changed) for a failed / released verifier or a window `active` or completed but neither
committed nor discarded (`window_ready`). Otherwise `wait_commit`, synchronize `compute` and `copy`, retire every graph's
launch (`resources_after_wait`), drop the held PCIe sources. An error fails the verifier. Graphs, bank, streams, event stay.
`rearm`: order of refusals, none of which changes anything: seed shapes (`check_shapes`: 36 x `128*48*128`, 36 x
`10240*3`, `9*10240` f32), then `require_rearmable` (not failed / released here or by the watchdog registry, `active`,
`window_ready`, `commit_pending` false; bank and commit graph present; every graph idle; the QSA journal valid, not armed,
all twelve indices and journals idle and published at one position). After that any error sets `failed` (the stack retires
the set and records a new one, "a partial re-arm is safe"). The work, in this order: bank re-arm (below), canonical GDN
reseed and PLE history upload through the commit graph's journal (every aggregate shares both), counters.
`reseed`: the intake of `original_verify_canonical_gdn` again, in place: same lengths check, finite check per layer,
36 x `copy_from_range_shared`; the device address of the image does not change. 117.7 MB host to device plus the f32
to bytes conversion per layer, the same cost as today's upload.
## 3. Reset checklist (what a fresh `new()` + `record_all` leaves, and where it is restored)
| State | Restored to | Where |
| --- | --- | --- |
| `windows`, `commits`, `completed_generation`, `completed_ids`, profile counters | 0 / None / `[0; 8]` / default | `OriginalVerifier::reset_run_counters` (`original_verify_schedule/verifier_park_rearm.rs`) |
| `commit_pending`, `window_ready`, `active`, `failed`, `released` | false (preconditions) | `require_rearmable` |
| `split`, `groups`, `resource_keys`, window/commit graphs, streams, event, `test_stall` | unchanged (as recorded) | not touched |
| watchdog registry numbers (rows, first position, layer step, active) | 0 / false | `Registration::reset_window` (`original_verify_diag.rs`) |
| bank staged window (`t`, `position`, `tokens`, `keep`) | `StagedWindow::EMPTY` | `Book::rearmed` (`original_verify/original_verify_rearm.rs`) |
| bank generation and `Physical.generation` | + 1 (stale `OriginalVerifyRow` / `OriginalVerifyWindow` refused, `validate_context`) | `OriginalVerifyBank::rearm` |
| bank `released` | false | `Book::rearmed` |
| `pcie_sources` (registered banks held to the copy fence) | cleared | `release_pcie_sources`, also in `park` |
| `pcie_mode`, `pcie_roles` | unchanged (they are in the key) | not touched |
| mapped staging 0..=14: tokens, steps, positions, commit record, PLE rows, sampled ids, CPU rows, doorbell `seq` (9), flags served / plan (A) / copies (B) (10, 11, 12), CPU output (13), published GPU plan and fetch tables (14) | all zero (`initialize_zero`) | `Physical::reset_to_recorded`, `ResetPlan` |
| arena: GDN / QSA journals, `tail_snap`, `hist_snap`, `plan` copy, expert `staging`, `head_logits`, the `hit_count` status word of `verify_clear_status` | zero (`cuMemsetD8`, then a context synchronize) | `Physical::zero_device` |
| profile stamp buffer (`STRATA_VERIFY_PROFILE`) | zero | `Physical::zero_device` |
| canonical GDN image (36 states, 36 histories) | the seed, same address | `OriginalVerifyCanonicalGdn::reseed` / `Canonical::reseed` |
| PLE history image | the seed | `reseed_images` (journal `ple_buffer()`, `copy_from_shared`) |
The flags a window waits on or raises are already zeroed by `stage` at the start of every window (`write_staged_rows`), so
a request that ends normally leaves them reusable; the re-arm restores the post-record value anyway (a released
verifier is refused, so the `u32::MAX` of `release_gpu_waits` never reaches a re-armed bank). The finite verdict word of the
head rows is re-armed by every `finish_same_stream`; the scan status is cleared by the graph.
## 4. Not covered
* The policy: key, `GraphReuse`, `LELEKA_DECODE_GRAPH_REUSE`, `weights_epoch` (not on this base: it is `moe_weight_cache/window_pins.rs`
in `claude/prefill-latency`; it belongs in `room` and `room_protected`, the two eviction sites, and my change leaves them as they were),
pinning, the QSA owner loan (`lend` / `take_back`, not on this base either: `require_idle` only checks the journal is quiet,
it does NOT compare owner addresses; if the owners moved, the graphs point at freed memory, so that comparison is the
loan's job), the drafter's programs bound to the bank (B3: after a re-arm the first draft must not reuse a tail of the previous request).
* A tensor the cache evicts and loads again lives at a new address; the held assembly keeps the old allocation with the same
bytes (weights are immutable), at the price of VRAM until the set is retired. Nothing here retires it.
* VRAM of a kept set (nine graphs, bank arena, mapped staging, 118 MB canonical image) during the prefill; the pool is the
stack's budget question (`decode-graph-reuse.md` section 5).
* Head-row and embedding-row aggregates: their words are rewritten by every window; not reset.
* `OriginalVerifyQsaJournal::snapshots` (the NaN-guard flag, set per request by `serve`) and its snapshot buffers.
* Any change of `max_t`, `max_cells`, expert formats, `WindowPolicy`, sm120 switches: a different recording.
* `target/` is not part of the change; no kernel, PTX or asset changed.
## 5. Tests
Without a GPU (`cargo test -p leleka-cuda-driver --features cuda-driver --lib`, 431 tests, 14 new):
`original_verify::rearm::tests` (seed shapes, little-endian PLE bytes, `Book::rearmed` clears the window, un-releases and
advances the generation by one without wrapping, the reset plan covers 15 mapped allocations, the arena and the profile),
`schedule::verifier_park_rearm::tests` (counters, the refusal for each of failed / released / active / window_ready /
commit_pending that changes nothing, no recording, wrong seed first, `park` refusals and the no-op `park`),
`diag::tests::a_rearmed_registration_...`, `device_ref::tests::the_window_and_journal_modules_never_clone_a_handle`.
On a GPU (orchestrator):
1. `LELEKA_VERIFY_WINDOW_GPU=yes cargo test -p leleka-cuda-driver --features cuda-driver --lib -- --ignored device_ref`
(handle release semantics, slab lifetime after the allocator released it).
2. The identity job over N requests with different prompts and lengths with the stack calling `park` / `rearm` (hex-finish):
top-16 logprob rows and the draft trace equal to the fresh-assembly run; the first window of request 2 accepted at the
QSA owners' position; `verifier.windows()` and the commit count of request 2 only; a `Row` / `Window` of request 1
refused after the re-arm; the canonical image holds request 2's seed (`with_committed_gdn` after the first commit).
3. Re-arm cost: `drv.*` host spans and the new `rearm` time (H2D 117.7 MB + the arena memset, expected well below the
83-85 ms of `record_all`; not measured here).
## 6. Risks
* Tensor addresses must not move while a set is held. Handles guarantee the memory is alive, not that the cache still
points at it; the stack must keep the key (weights epoch, owners).
* `rearm` zeroes the whole arena and every mapped allocation: correct for "fresh" semantics, a memset of the arena size
per request. If a measurement shows it matters, the reset can be narrowed to the spans that carry state, but that is a
separate, measured change.
* The merge with the owner loan touches `qsa_verification_commit/*` too (`require_idle` reads `indices[0]` and
`check_idle_at`, which become `Option` borrows there).