decode graph reuse (Q7), part 1: LELEKA_DECODE_GRAPH_REUSE (off), key and policy tested on the lifecycle fake, shared-expert pin and weights epoch; assembly borrow and re-arm API documented as blocked
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>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
11bdb54666
commit
3e68def28e
@@ -12,6 +12,7 @@ use crate::qwen_forward::original_serve_stack::lifecycle_fake::{FakeDevice, Fake
|
||||
use leleka_obs::time::ManualClock;
|
||||
|
||||
mod ends;
|
||||
mod graphs;
|
||||
mod prefix;
|
||||
|
||||
/// An id the model never produces: no request stops on it.
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! The decode graphs under the lifecycle (ledger row Q7, `LELEKA_DECODE_GRAPH_REUSE`): a kept graph set gives the same
|
||||
//! text as re-recording, costs no recording, and is replaced - never replayed - when anything it was recorded over
|
||||
//! changed.
|
||||
use super::*;
|
||||
use crate::qwen_forward::original_serve_stack::decode_graph_reuse::{Armed, DecodeGraphKey, Why};
|
||||
|
||||
/// What recording the graph set costs on the manual clock.
|
||||
const RECORD_MS: u64 = 90;
|
||||
|
||||
impl Rig {
|
||||
fn with_graphs(self, enabled: bool) -> Self {
|
||||
Self { stack: self.stack.with_graph_reuse(enabled, RECORD_MS), ..self }
|
||||
}
|
||||
|
||||
/// Runs `count` requests with different prompts: the text of each, and the decode milliseconds of each.
|
||||
fn requests(&mut self, count: usize) -> (Vec<String>, Vec<f64>) {
|
||||
let (mut texts, mut decode_ms) = (Vec::new(), Vec::new());
|
||||
for i in 0..count {
|
||||
let p = prompt_of(300 + 10 * i, i);
|
||||
let run = self.run(&p, 12, NO_EOS);
|
||||
assert_eq!(run.text, expect(&p, 12), "request {i}");
|
||||
texts.push(run.text);
|
||||
decode_ms.push(self.stack.last_timing().1);
|
||||
}
|
||||
(texts, decode_ms)
|
||||
}
|
||||
}
|
||||
|
||||
fn rig(enabled: bool) -> Rig {
|
||||
Rig::new(Script::default(), false).with_graphs(enabled)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_the_switch_off_every_request_records_its_graphs() {
|
||||
let mut rig = rig(false);
|
||||
let (_, decode_ms) = rig.requests(3);
|
||||
assert_eq!((rig.stack.graphs().recordings, rig.stack.graphs().reuses), (3, 0));
|
||||
assert_eq!(decode_ms, [90.0; 3]);
|
||||
assert_eq!(rig.stack.graphs().last, Some(Armed::Recorded(Why::Disabled)));
|
||||
assert!(!rig.stack.graphs().is_held());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_graph_set_gives_the_text_of_re_recording_and_costs_no_recording() {
|
||||
let (mut kept, mut fresh) = (rig(true), rig(false));
|
||||
let (kept_text, kept_ms) = kept.requests(4);
|
||||
let (fresh_text, _) = fresh.requests(4);
|
||||
assert_eq!(kept_text, fresh_text, "the same text per request");
|
||||
assert_eq!((kept.stack.graphs().recordings, kept.stack.graphs().reuses), (1, 3));
|
||||
assert_eq!(kept_ms, [90.0, 0.0, 0.0, 0.0], "only the first request records");
|
||||
assert_eq!(kept.dev.digest(), fresh.dev.digest(), "the device ends in the same state");
|
||||
assert_eq!(kept.log("graphs"), ["graphs recorded: NothingHeld", "graphs reused", "graphs reused", "graphs reused"]);
|
||||
}
|
||||
|
||||
/// The inputs of the key, by the name `first_difference` gives them.
|
||||
const INPUTS: [&str; 7] =
|
||||
["max_t", "max_cells", "pcie_mode", "expert tier", "cluster top-k", "weights epoch", "owners epoch"];
|
||||
|
||||
/// Changes the named input of the key.
|
||||
fn change(name: &str, k: &mut DecodeGraphKey) {
|
||||
match name {
|
||||
"max_t" => k.max_t -= 1,
|
||||
"max_cells" => k.max_cells *= 2,
|
||||
"pcie_mode" => k.pcie_mode = 2,
|
||||
"expert tier" => k.tier = true,
|
||||
"cluster top-k" => k.cluster_topk = false,
|
||||
"weights epoch" => k.weights_epoch += 1,
|
||||
_ => k.owners_epoch += 1,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_input_of_the_key_forces_a_re_record_and_the_new_set_is_kept_again() {
|
||||
for name in INPUTS {
|
||||
let mut rig = rig(true);
|
||||
rig.requests(1);
|
||||
change(name, rig.stack.graph_key());
|
||||
let p = prompt_of(333, 7);
|
||||
assert_eq!(rig.run(&p, 12, NO_EOS).text, expect(&p, 12), "{name}");
|
||||
assert_eq!(rig.stack.graphs().recordings, 2, "{name}");
|
||||
assert_eq!(rig.stack.graphs().last, Some(Armed::Recorded(Why::KeyChanged(name))), "{name}");
|
||||
rig.run(&prompt_of(344, 8), 12, NO_EOS);
|
||||
assert_eq!((rig.stack.graphs().recordings, rig.stack.graphs().reuses), (2, 1), "{name}: kept for the new key");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_that_refuses_to_be_re_armed_is_recorded_again_not_replayed() {
|
||||
let mut rig = rig(true);
|
||||
rig.stack.graphs().refuse_rearm = true;
|
||||
rig.requests(1);
|
||||
rig.stack.graphs().refuse_rearm = false;
|
||||
let (texts, _) = rig.requests(2);
|
||||
assert_eq!(texts.len(), 2);
|
||||
assert_eq!(rig.stack.graphs().recordings, 2, "the second request records; the third replays that recording");
|
||||
assert_eq!(rig.stack.graphs().reuses, 1);
|
||||
assert_eq!(rig.log("graphs")[1], "graphs recorded: RearmRefused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_that_fails_or_is_cancelled_does_not_keep_its_graphs() {
|
||||
let mut rig = Rig::new(Script { fail_round: Some(0), ..Script::default() }, false).with_graphs(true);
|
||||
let p = prompt(300);
|
||||
assert!(matches!(rig.run(&p, 12, NO_EOS).ended, Ended::Failed(..)));
|
||||
assert!(!rig.stack.graphs().is_held());
|
||||
let run = rig.run(&p, 12, NO_EOS);
|
||||
assert_eq!(run.text, expect(&p, 12));
|
||||
assert_eq!(rig.stack.graphs().last, Some(Armed::Recorded(Why::NothingHeld)));
|
||||
assert_eq!((rig.stack.graphs().recordings, rig.stack.graphs().reuses), (2, 0));
|
||||
assert!(rig.stack.graphs().is_held(), "the clean request keeps its set");
|
||||
rig.stack.graphs().invalidate();
|
||||
assert!(!rig.stack.graphs().is_held());
|
||||
}
|
||||
@@ -170,6 +170,9 @@ pub(crate) struct MoeWeightCache<'ctx> {
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
adaptive_shared: Option<cache_profile::SharedPermanentPool>,
|
||||
age: u64,
|
||||
/// The entries a held decode graph set reads in place (`window_pins`), and how many raw entries were evicted.
|
||||
window_pins: std::collections::HashSet<MoeWeightDescriptor>,
|
||||
raw_evictions: u64,
|
||||
failed: Cell<bool>,
|
||||
bank: Option<Rc<DeviceBuffer<'ctx>>>,
|
||||
dense: Vec<Dense<'ctx>>,
|
||||
@@ -351,6 +354,9 @@ pub(in crate::qwen_forward) use original_mtp_weights::{MtpHeadSources, RetainedO
|
||||
|
||||
mod validate_ranked_profile;
|
||||
#[allow(unused_imports)]
|
||||
// pinning and the epoch are read by the decode graph reuse, which the stack does not wire yet
|
||||
#[allow(dead_code)]
|
||||
mod window_pins;
|
||||
use validate_ranked_profile::dual_layout;
|
||||
#[allow(unused_imports)]
|
||||
use validate_ranked_profile::integer_iq3_triplet;
|
||||
|
||||
+2
@@ -30,6 +30,8 @@ macro_rules! blank_cache {
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
adaptive_shared: None,
|
||||
age: 0,
|
||||
window_pins: Default::default(),
|
||||
raw_evictions: 0,
|
||||
failed: Cell::new(false),
|
||||
bank: None,
|
||||
dense: Vec::new(),
|
||||
|
||||
+3
@@ -139,6 +139,9 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
self.routed_workspace.as_ref().map(Rc::clone).ok_or(Error::IdentityMismatch)
|
||||
}
|
||||
pub(in super::super) fn is_pinned(&self, key: MoeWeightDescriptor) -> bool {
|
||||
if self.window_pins.contains(&key) {
|
||||
return true;
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if self.adaptive_shared.as_ref().is_some_and(|pool| pool.contains(key)) {
|
||||
return true;
|
||||
|
||||
+1
@@ -279,6 +279,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
let key = self.eviction_key(protected)?;
|
||||
self.remove_lru_entry(key)?;
|
||||
let entry = self.main.remove(&key).ok_or(Error::IdentityMismatch)?;
|
||||
self.note_eviction(&entry.weight);
|
||||
if entry.weight.close().is_err() {
|
||||
self.failed.set(true);
|
||||
return Err(Error::CudaExecution);
|
||||
|
||||
+1
@@ -72,6 +72,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
let key = self.eviction_key(&[])?;
|
||||
self.remove_lru_entry(key)?;
|
||||
let entry = self.main.remove(&key).ok_or(Error::IdentityMismatch)?;
|
||||
self.note_eviction(&entry.weight);
|
||||
if entry.weight.close().is_err() {
|
||||
self.failed.set(true);
|
||||
return Err(Error::CudaExecution);
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
//! The shared experts a kept decode graph set reads in place (`LELEKA_DECODE_GRAPH_REUSE`, ledger row Q7).
|
||||
//!
|
||||
//! The window graphs hold the device addresses of the shared-expert tensors of all 48 layers. While a graph set is held
|
||||
//! across requests the prompt path must not free them: `pin_for_window` makes the cache skip them when it needs room
|
||||
//! (the same rule as the profile's permanent pool), and `raw_evictions` counts every raw entry the cache did free, so a
|
||||
//! graph set recorded before such an eviction is never replayed (the count is part of the graph key's weights epoch).
|
||||
use super::*;
|
||||
|
||||
impl<'ctx> MoeWeightCache<'ctx> {
|
||||
/// Keep the shared experts `keys` (from `ensure_original_verify_shared`) resident until `unpin_window`.
|
||||
pub(in crate::qwen_forward) fn pin_for_window(&mut self, keys: &[[MoeWeightDescriptor; 4]]) -> Result<()> {
|
||||
if keys.iter().flatten().any(|key| !self.main.contains_key(key)) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.window_pins.extend(keys.iter().flatten().copied());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Release the pins: the entries can be evicted again, so a graph set that read them is no longer replayable.
|
||||
pub(in crate::qwen_forward) fn unpin_window(&mut self) {
|
||||
if !self.window_pins.is_empty() {
|
||||
self.window_pins.clear();
|
||||
self.raw_evictions = self.raw_evictions.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Raw entries freed so far, plus the pins released: unchanged between two requests means every address a window
|
||||
/// graph read is still the same live buffer.
|
||||
pub(in crate::qwen_forward) fn weights_epoch(&self) -> u64 {
|
||||
self.raw_evictions
|
||||
}
|
||||
|
||||
/// Account an entry the cache is about to free (the window reads raw entries only).
|
||||
pub(super) fn note_eviction(&mut self, weight: &EncodedWeight<'ctx>) {
|
||||
if matches!(weight, EncodedWeight::Raw(_)) {
|
||||
self.raw_evictions = self.raw_evictions.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -233,6 +233,9 @@ mod tests;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod lifecycle_fake;
|
||||
|
||||
// The reuse policy ahead of its stack wiring (see its module doc): driven by the lifecycle fake until then.
|
||||
#[allow(dead_code)]
|
||||
pub(crate) mod decode_graph_reuse;
|
||||
mod stack_groups;
|
||||
use stack_groups::{RequestState, ServePolicy, TierState};
|
||||
mod stack_config_and_ttft_marks;
|
||||
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
//! When the assembled decode graphs may be kept for the next request (`LELEKA_DECODE_GRAPH_REUSE`, off by default;
|
||||
//! docs/experiments/decode-graph-reuse.md).
|
||||
//!
|
||||
//! A captured graph holds the device and mapped-host ADDRESSES of every buffer its kernels touch, never the data, so a
|
||||
//! graph set recorded for one request replays correctly in the next only when every address and every shape it was
|
||||
//! recorded over is the same. `DecodeGraphKey` names those inputs; `GraphReuse` keeps one assembly together with the
|
||||
//! key it was recorded for and hands it out again only for an equal key, after the assembly agreed to be re-armed with
|
||||
//! the new request's seed. Anything else - a changed key, a refused re-arm, a request that did not end cleanly -
|
||||
//! retires the held assembly and records a new one. There is no path that replays a graph set for a key it was not
|
||||
//! recorded for.
|
||||
//!
|
||||
//! `Reusable::rearm` is the contract of the verify bank's re-arm API (`reset_for_new_request`, the part of the feature
|
||||
//! that lives in the speed session's files); the lifecycle fake implements it, the real assembly does not yet, so the
|
||||
//! stack states at `open` that the switch is refused and records every request as before.
|
||||
|
||||
use std::mem;
|
||||
|
||||
/// Everything the recorded decode graphs are specific to. Two requests may share a recording only when their keys are
|
||||
/// equal. The two epochs are counters of the owners of the physical buffers: each owner bumps its counter whenever it
|
||||
/// frees, moves or reallocates a buffer a window graph reads or writes in place (`MoeWeightCache::pin_epoch`,
|
||||
/// the QSA journal's `OwnersFingerprint`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct DecodeGraphKey {
|
||||
/// The widest recorded window (a graph per T = 1..=`max_t`, plus the commit graph).
|
||||
pub(crate) max_t: usize,
|
||||
/// The cell budget the verifier arena and the QSA journals are sized for.
|
||||
pub(crate) max_cells: usize,
|
||||
/// How the window stages the PCIe share of the experts: 0 DMA, 2 copy kernel (baked into the graph).
|
||||
pub(crate) pcie_mode: u8,
|
||||
/// Whether a VRAM expert tier stands behind the windows.
|
||||
pub(crate) tier: bool,
|
||||
/// The decode top-k as a thread-block cluster, as resolved for the card (the graph holds the kernel choice).
|
||||
pub(crate) cluster_topk: bool,
|
||||
/// The shared experts and routers the windows read in place (MoE and dense caches).
|
||||
pub(crate) weights_epoch: u64,
|
||||
/// The twelve resident QSA index images and mapped K/V journals, the PLE history and the canonical GDN image.
|
||||
pub(crate) owners_epoch: u64,
|
||||
}
|
||||
|
||||
impl DecodeGraphKey {
|
||||
/// The name of the first input that differs from `other`, or `None` for equal keys.
|
||||
pub(crate) fn first_difference(&self, other: &Self) -> Option<&'static str> {
|
||||
let checks = [
|
||||
("max_t", self.max_t != other.max_t),
|
||||
("max_cells", self.max_cells != other.max_cells),
|
||||
("pcie_mode", self.pcie_mode != other.pcie_mode),
|
||||
("expert tier", self.tier != other.tier),
|
||||
("cluster top-k", self.cluster_topk != other.cluster_topk),
|
||||
("weights epoch", self.weights_epoch != other.weights_epoch),
|
||||
("owners epoch", self.owners_epoch != other.owners_epoch),
|
||||
];
|
||||
checks.into_iter().find_map(|(name, differs)| differs.then_some(name))
|
||||
}
|
||||
}
|
||||
|
||||
/// A recorded decode assembly the policy can keep between requests. `S` is what the next request seeds it with (the
|
||||
/// session's recurrent priors and PLE prior).
|
||||
pub(crate) trait Reusable<S> {
|
||||
/// Make the assembly ready for the next request: drain both streams, reseed the canonical GDN image and the PLE
|
||||
/// history in place, reset the bank's window state and every flag the graphs wait on. `false` refuses: the assembly
|
||||
/// is then retired, never replayed.
|
||||
fn rearm(&mut self, seed: &S) -> bool;
|
||||
}
|
||||
|
||||
/// Why a request got a freshly recorded assembly.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Why {
|
||||
/// The switch is off.
|
||||
Disabled,
|
||||
/// Nothing was held (first request, or the previous one ended without releasing its assembly).
|
||||
NothingHeld,
|
||||
/// The held assembly was recorded for another key; the name of the first input that differs.
|
||||
KeyChanged(&'static str),
|
||||
/// The held assembly refused to be re-armed.
|
||||
RearmRefused,
|
||||
}
|
||||
|
||||
/// How a request got its assembly.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Armed {
|
||||
/// The assembly kept from the previous request, re-armed.
|
||||
Reused,
|
||||
/// A new recording.
|
||||
Recorded(Why),
|
||||
}
|
||||
|
||||
/// One assembly kept between requests, with the key it was recorded for.
|
||||
pub(crate) struct GraphReuse<A> {
|
||||
enabled: bool,
|
||||
held: Option<(DecodeGraphKey, A)>,
|
||||
}
|
||||
|
||||
impl<A> GraphReuse<A> {
|
||||
pub(crate) fn new(enabled: bool) -> Self {
|
||||
Self { enabled, held: None }
|
||||
}
|
||||
|
||||
/// The assembly for a request over `key`: the held one when the key is equal and it re-arms with `seed`, else
|
||||
/// `record()`'s. The held assembly is taken out in every case (a request owns its assembly while it runs).
|
||||
pub(crate) fn acquire<S, E>(
|
||||
&mut self,
|
||||
(key, seed): (&DecodeGraphKey, &S),
|
||||
record: impl FnOnce() -> Result<A, E>,
|
||||
) -> Result<(A, Armed), E>
|
||||
where
|
||||
A: Reusable<S>,
|
||||
{
|
||||
let why = match self.held.take() {
|
||||
_ if !self.enabled => Why::Disabled,
|
||||
None => Why::NothingHeld,
|
||||
Some((held_for, mut assembly)) => match held_for.first_difference(key) {
|
||||
Some(name) => Why::KeyChanged(name),
|
||||
None if assembly.rearm(seed) => return Ok((assembly, Armed::Reused)),
|
||||
None => Why::RearmRefused,
|
||||
},
|
||||
};
|
||||
record().map(|assembly| (assembly, Armed::Recorded(why)))
|
||||
}
|
||||
|
||||
/// The request ended cleanly: keep its assembly for the next one (a disabled policy drops it).
|
||||
pub(crate) fn release(&mut self, key: &DecodeGraphKey, assembly: A) {
|
||||
if self.enabled {
|
||||
self.held = Some((*key, assembly));
|
||||
}
|
||||
}
|
||||
|
||||
/// Retire the held assembly (a lost owner, a reconfigure, a request that failed).
|
||||
pub(crate) fn invalidate(&mut self) {
|
||||
drop(mem::take(&mut self.held));
|
||||
}
|
||||
|
||||
/// Whether an assembly is held.
|
||||
pub(crate) fn is_held(&self) -> bool {
|
||||
self.held.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// The one line `open` writes when the switch is on while the stack cannot keep an assembly yet.
|
||||
pub(crate) fn refusal_line(requested: bool) -> Option<&'static str> {
|
||||
requested.then_some(
|
||||
"decode graph reuse (LELEKA_DECODE_GRAPH_REUSE) requested: refused, the verify bank has no re-arm API and the \
|
||||
assembly still borrows the stack (docs/experiments/decode-graph-reuse.md); every request records its graphs",
|
||||
)
|
||||
}
|
||||
@@ -21,10 +21,12 @@ use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
mod graphs;
|
||||
mod port;
|
||||
mod prefix;
|
||||
mod stack;
|
||||
|
||||
pub(crate) use graphs::GraphBook;
|
||||
pub(crate) use prefix::{FakeBlock, FakeState};
|
||||
pub(crate) use stack::FakeStack;
|
||||
|
||||
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
//! The decode graphs of the scripted device: what the reuse policy keeps between requests (test support only).
|
||||
//!
|
||||
//! `FakeGraphs` stands for the nine recorded window graphs and the commit graph. Recording costs `record_ms` on the
|
||||
//! manual clock (the part of the request that `LELEKA_DECODE_GRAPH_REUSE` removes); a recording bakes the key it was
|
||||
//! made for and the seed of its request, exactly as a captured graph bakes addresses, and a replay checks both, so a
|
||||
//! graph set replayed for another key or without a re-arm fails the request instead of passing silently.
|
||||
use super::super::decode_graph_reuse::{Armed, DecodeGraphKey, GraphReuse, Reusable};
|
||||
use crate::qwen_forward::contract::Error;
|
||||
|
||||
/// What a request seeds the graphs with: the recurrent state the device stands at when its prompt is read.
|
||||
pub(crate) type Seed = u64;
|
||||
|
||||
/// A recorded graph set of the fake.
|
||||
pub(crate) struct FakeGraphs {
|
||||
baked: DecodeGraphKey,
|
||||
seeded: Seed,
|
||||
refuse_rearm: bool,
|
||||
}
|
||||
|
||||
impl FakeGraphs {
|
||||
pub(crate) fn record(key: DecodeGraphKey, seed: Seed, refuse_rearm: bool) -> Self {
|
||||
Self { baked: key, seeded: seed, refuse_rearm }
|
||||
}
|
||||
|
||||
/// The replay check of a captured graph: it runs only over the key it was recorded for, seeded for this request.
|
||||
pub(crate) fn replay(&self, key: &DecodeGraphKey, seed: Seed) -> Result<(), Error> {
|
||||
if self.baked != *key || self.seeded != seed {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Reusable<Seed> for FakeGraphs {
|
||||
fn rearm(&mut self, seed: &Seed) -> bool {
|
||||
if self.refuse_rearm {
|
||||
return false;
|
||||
}
|
||||
self.seeded = *seed;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The policy plus the counters a test reads.
|
||||
pub(crate) struct GraphBook {
|
||||
reuse: GraphReuse<FakeGraphs>,
|
||||
/// Graph sets recorded so far.
|
||||
pub(crate) recordings: usize,
|
||||
/// Requests that replayed a kept set.
|
||||
pub(crate) reuses: usize,
|
||||
/// The re-arm of the next kept set refuses.
|
||||
pub(crate) refuse_rearm: bool,
|
||||
/// How the last request got its graphs.
|
||||
pub(crate) last: Option<Armed>,
|
||||
}
|
||||
|
||||
impl GraphBook {
|
||||
pub(crate) fn new(enabled: bool) -> Self {
|
||||
Self { reuse: GraphReuse::new(enabled), recordings: 0, reuses: 0, refuse_rearm: false, last: None }
|
||||
}
|
||||
|
||||
/// The graphs for a request over `key` and `seed`: a kept set or a recording.
|
||||
pub(crate) fn acquire(&mut self, key: &DecodeGraphKey, seed: Seed) -> Result<(FakeGraphs, Armed), Error> {
|
||||
let (refuse, recordings) = (self.refuse_rearm, &mut self.recordings);
|
||||
let record = || {
|
||||
*recordings += 1;
|
||||
Ok::<_, Error>(FakeGraphs::record(*key, seed, refuse))
|
||||
};
|
||||
let (graphs, armed) = self.reuse.acquire((key, &seed), record)?;
|
||||
self.reuses += usize::from(armed == Armed::Reused);
|
||||
self.last = Some(armed);
|
||||
Ok((graphs, armed))
|
||||
}
|
||||
|
||||
/// The request ended cleanly: its graphs are kept (when the switch is on).
|
||||
pub(crate) fn release(&mut self, key: &DecodeGraphKey, graphs: FakeGraphs) {
|
||||
self.reuse.release(key, graphs);
|
||||
}
|
||||
|
||||
pub(crate) fn invalidate(&mut self) {
|
||||
self.reuse.invalidate();
|
||||
}
|
||||
|
||||
pub(crate) fn is_held(&self) -> bool {
|
||||
self.reuse.is_held()
|
||||
}
|
||||
}
|
||||
+57
-2
@@ -1,9 +1,10 @@
|
||||
//! `FakeStack`: the request-level seams of the stack over the scripted device.
|
||||
use super::super::decode_graph_reuse::{Armed, DecodeGraphKey};
|
||||
use super::super::{
|
||||
PlanLimits, PrefixConfig, PrefixServe, PromptOptions, PromptPath, PromptPlan, RequestOwners, ResumePoint,
|
||||
ServeDevice, ServeError, ServeRequest, original_serve_residency, plan_error, run_request,
|
||||
};
|
||||
use super::{FakeBlock, FakeDevice, FakeState, GRID, VOCAB};
|
||||
use super::{CELLS, FakeBlock, FakeDevice, FakeState, GRID, GraphBook, VOCAB};
|
||||
use crate::backend::original_prompt::PromptAction;
|
||||
use crate::qwen_forward::contract::Error;
|
||||
use crate::qwen_forward::original_serve_engine::{
|
||||
@@ -24,6 +25,9 @@ pub(crate) struct FakeStack {
|
||||
max_context: i64,
|
||||
reused: usize,
|
||||
timing: (f64, f64),
|
||||
graphs: GraphBook,
|
||||
graph_key: DecodeGraphKey,
|
||||
record_ms: u64,
|
||||
}
|
||||
|
||||
impl FakeStack {
|
||||
@@ -45,9 +49,37 @@ impl FakeStack {
|
||||
max_context: 4096,
|
||||
reused: 0,
|
||||
timing: (0.0, 0.0),
|
||||
graphs: GraphBook::new(false),
|
||||
graph_key: DecodeGraphKey {
|
||||
max_t: 4,
|
||||
max_cells: CELLS,
|
||||
pcie_mode: 0,
|
||||
tier: false,
|
||||
cluster_topk: true,
|
||||
weights_epoch: 0,
|
||||
owners_epoch: 0,
|
||||
},
|
||||
record_ms: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// `LELEKA_DECODE_GRAPH_REUSE` on or off, and what recording the graph set costs on the manual clock.
|
||||
pub(crate) fn with_graph_reuse(mut self, enabled: bool, record_ms: u64) -> Self {
|
||||
self.graphs = GraphBook::new(enabled);
|
||||
self.record_ms = record_ms;
|
||||
self
|
||||
}
|
||||
|
||||
/// The policy's counters, and the switch for the next re-arm to refuse.
|
||||
pub(crate) fn graphs(&mut self) -> &mut GraphBook {
|
||||
&mut self.graphs
|
||||
}
|
||||
|
||||
/// The inputs the next request's graphs are keyed on (a test changes one between requests).
|
||||
pub(crate) fn graph_key(&mut self) -> &mut DecodeGraphKey {
|
||||
&mut self.graph_key
|
||||
}
|
||||
|
||||
/// Checkpoint hits the prefix cache has counted.
|
||||
pub(crate) fn prefix_hits(&self) -> u64 {
|
||||
self.prefix.as_ref().map_or(0, |p| p.stats().hits)
|
||||
@@ -176,6 +208,29 @@ impl FakeStack {
|
||||
serve_request(&mut self.controller, &mut engine, speculative, callbacks)
|
||||
}
|
||||
|
||||
/// The graph set of the request (kept or recorded), the rounds over it, and the set kept again after a clean end.
|
||||
fn decode_over_graphs(
|
||||
&mut self,
|
||||
request: &ServeRequest,
|
||||
emit: &mut dyn FnMut(&[i32]) -> Result<(), Error>,
|
||||
cancel: &mut dyn FnMut() -> bool,
|
||||
) -> Result<ServeOutcome, SpecError> {
|
||||
let (key, seed) = (self.graph_key, self.dev.digest());
|
||||
let (graphs, armed) = self.graphs.acquire(&key, seed)?;
|
||||
if let Armed::Recorded(why) = armed {
|
||||
self.clock.advance_ms(self.record_ms);
|
||||
self.dev.log(format!("graphs recorded: {why:?}"));
|
||||
} else {
|
||||
self.dev.log("graphs reused");
|
||||
}
|
||||
graphs.replay(&key, seed)?;
|
||||
let served = self.serve_rounds(request, emit, cancel);
|
||||
if served.is_ok() {
|
||||
self.graphs.release(&key, graphs);
|
||||
}
|
||||
served
|
||||
}
|
||||
|
||||
fn prefix_resume(&mut self, request: &ServeRequest) -> Option<usize> {
|
||||
let prefix = self.prefix.as_mut()?;
|
||||
match prefix.begin(&mut self.dev, &request.prompt) {
|
||||
@@ -230,7 +285,7 @@ impl RequestOwners for FakeStack {
|
||||
cancel: &mut dyn FnMut() -> bool,
|
||||
) -> Result<ServeOutcome, SpecError> {
|
||||
let started = self.clock.now();
|
||||
let result = self.serve_rounds(request, emit, cancel);
|
||||
let result = self.decode_over_graphs(request, emit, cancel);
|
||||
self.timing.1 = self.clock.since(started).as_secs_f64() * 1e3;
|
||||
result
|
||||
}
|
||||
|
||||
+3
@@ -31,6 +31,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
this.register_memory_classes();
|
||||
crate::memory_governor::post_open();
|
||||
log_open_inventory();
|
||||
if let Some(line) = decode_graph_reuse::refusal_line(crate::settings::process().serve.decode_graph_reuse) {
|
||||
operator_text(line);
|
||||
}
|
||||
Ok(this)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,10 @@ pub(crate) struct ServeSettings {
|
||||
/// `LELEKA_DRAFT_CHAIN_PIPELINE` is `1` or `on`: the MTP chain steps of a greedy draft run back to back, one
|
||||
/// stream drain for the run (identity and paired A/B of docs/experiments/decode-tail-5090.md).
|
||||
pub(crate) draft_chain_pipeline: bool,
|
||||
/// `LELEKA_DECODE_GRAPH_REUSE` is `1` or `on`: keep the assembled decode graphs for the next request when nothing
|
||||
/// they bake in changed (OFF by default; docs/experiments/decode-graph-reuse.md). The stack refuses the reuse
|
||||
/// (and records every request, as without the switch) until the verify bank has its re-arm API.
|
||||
pub(crate) decode_graph_reuse: bool,
|
||||
}
|
||||
|
||||
impl ServeSettings {
|
||||
@@ -47,6 +51,7 @@ impl ServeSettings {
|
||||
cpu_pool_plan: equals(env, "LELEKA_CPU_POOL_PLAN", "on"),
|
||||
prefill_loan_tiers: one_of(env, "LELEKA_PREFILL_LOAN_TIERS", &["1", "on"]),
|
||||
draft_chain_pipeline: one_of(env, "LELEKA_DRAFT_CHAIN_PIPELINE", &["1", "on"]),
|
||||
decode_graph_reuse: one_of(env, "LELEKA_DECODE_GRAPH_REUSE", &["1", "on"]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,3 +96,11 @@ fn the_draft_chain_pipeline_is_one_or_on_and_off_by_default() {
|
||||
assert_eq!(serve(&[("LELEKA_DRAFT_CHAIN_PIPELINE", value)]).draft_chain_pipeline, want, "pipeline {value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_decode_graph_reuse_is_one_or_on_and_off_by_default() {
|
||||
assert!(!serve(&[]).decode_graph_reuse);
|
||||
for (value, want) in [("1", true), ("on", true), ("0", false), ("off", false), ("yes", false), ("", false)] {
|
||||
assert_eq!(serve(&[("LELEKA_DECODE_GRAPH_REUSE", value)]).decode_graph_reuse, want, "reuse {value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,101 +1,187 @@
|
||||
# Decode graph reuse across requests (ledger row Q7)
|
||||
|
||||
Status: design only, no code committed. The reuse needs an ownership refactor (stack-independent assembly, QSA owner loan, a re-arm API in the verify bank / gpu plan, which is `original_verify_gpu_plan*`, owned by the speed-vs-strata session); see section 4 for why and the order of changes. 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:
|
||||
|
||||
1. 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_unwrap` in `into_owners`), which requires every graph that holds the journal to be gone.
|
||||
2. 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 of `OriginalServeStack` cannot be stored in it (self-reference); this is why
|
||||
`DecodeView` borrows the fields one by one.
|
||||
3. 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.
|
||||
4. 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 (spans `draft.*`, 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 128*48*128 + 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 for `max_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) and `max_t` is the arena
|
||||
geometry. `verifier_max_t` can only fall during a process (`narrow_window_policy` after a graph OOM); a held assembly
|
||||
recorded for another `max_t` must 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_mode` is 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 (the policy the reuse would implement)
|
||||
|
||||
`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 (MoE cache eviction or reload of a shared expert or router, dense cache reload, QSA owner
|
||||
rebuilt, PLE or canonical buffer replaced, expert bank re-registered). `GraphReuse::acquire(key, record)` returns the held
|
||||
assembly only for an equal key and only if `rearm()` accepts; otherwise it retires it and calls `record()`. `release` keeps an
|
||||
assembly only after a clean request; `invalidate` retires it (broken stack, reconfigure, failed request, narrowed window).
|
||||
A reuse that cannot show an equal key is a re-record.
|
||||
|
||||
## 4. Why it is not implemented in this change
|
||||
|
||||
The reuse needs, in order (none of it needs `original_verify_window_*`, `original_verify_gpu_plan*` or graph-stream code,
|
||||
except where marked; without a GPU none of it can be validated here):
|
||||
|
||||
1. Lifetimes: the held assembly must not borrow the stack. Either the caches the windows read (dense, MoE, output, formats,
|
||||
PLE buffers) move behind `Rc` / a long-lived owner that the stack and the assembly both reference, or the assembly is kept
|
||||
outside the stack in a holder that outlives it. Every `&'s` in `DecodeResources`, `VerifyWeights`, `AssembleInputs` and the
|
||||
aggregates changes. (`unsafe` lifetime erasure is not an option in this crate.)
|
||||
2. QSA owner loan: the journal must be able to lend the owners to the executor without the graphs being dropped
|
||||
(`indices`/`mapped` as `RefCell<Option<..>>` in `qsa_verification_commit.rs`; a graph run while lent is refused), and the
|
||||
executor must hand them back at the same addresses (`take_qsa_owners` / `adopt_qsa_owners` keep the physical buffers; they
|
||||
rebuild the lineage objects, which is fine). Epoch `owners_epoch` bumps if any owner is replaced.
|
||||
3. Re-arm API in the driver: reseed the canonical GDN image in place, reset the bank's window state (`last_*`, generation, the
|
||||
gpu-plan state), drain both streams, instead of `OriginalVerifier::close`. The gpu-plan state lives in
|
||||
`original_verify_gpu_plan*` (owned by another session): that part needs their change, exact need: a `reset_for_new_request`
|
||||
on the bank/plan that leaves the registered buffers and clears per-request flags.
|
||||
4. MTP drafter: do not release the verifier bindings when the bank is kept (`mtp_release_verifier`), release them on retire.
|
||||
5. Epoch counters in the MoE and dense caches and the executor (the key above), and pinning of the shared experts / routers
|
||||
for as long as an assembly is held, so that a prefill cannot evict a buffer a held graph reads.
|
||||
|
||||
Validation (GPU, orchestrator): identity of greedy output reuse-on vs off over N requests with different prompts, 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`, `draft.*` first-draft capture, 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).
|
||||
|
||||
## 5. 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 re-arm. The kept pool costs VRAM during prefill.
|
||||
# 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:
|
||||
|
||||
1. 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_unwrap` in `into_owners`), which requires every graph that holds the journal to be gone.
|
||||
2. 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 of `OriginalServeStack` cannot be stored in it (self-reference); this is why
|
||||
`DecodeView` borrows the fields one by one.
|
||||
3. 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.
|
||||
4. 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 (spans `draft.*`, 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 128*48*128 + 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 for `max_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) and `max_t` is the arena
|
||||
geometry. `verifier_max_t` can only fall during a process (`narrow_window_policy` after a graph OOM); a held assembly
|
||||
recorded for another `max_t` must 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_mode` is 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()` make `is_pinned` true 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 with `InputAllocation`, 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*` and `original_verify_window_qsa.rs` (5), `qwen_dispatch/fixed_operands.rs`
|
||||
(34): replace the `&'a DeviceBuffer<'ctx>` operands with a shared handle `DeviceRef<'ctx>` (an `Rc` to the allocation plus
|
||||
offset and length, `Clone`, derefs to `&DeviceBuffer` for the existing `qwen_address()` calls). The aggregates then have no
|
||||
`'a`, `OriginalVerifyWindowResources<'ctx>` and `DecodeResources<'ctx>` can sit in the stack, and the borrow of the caches
|
||||
ends at `assemble`.
|
||||
* The caches hand out handles: `DenseWeightCache::original_verify_*` and `MoeWeightCache::raw_shared` clone the `Rc` of the
|
||||
entry (the entries become `Rc<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_epoch` bumps, so the set is retired
|
||||
at the next request).
|
||||
* `seed_ple_history` writes through the shared handle (a `&self` upload of `DeviceBuffer`, 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*`):
|
||||
|
||||
```rust
|
||||
/// 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_keys` as recorded.
|
||||
* `OriginalVerifyBank`: `last_t = 0`, `last_position = 0`, `last_tokens = [0; 8]`, `last_keep = 0`, `generation` advanced (old
|
||||
`OriginalVerifyRow` / `OriginalVerifyWindow` values are refused), `released = false`, `pcie_sources` cleared (held until the
|
||||
previous copy-stream fence); `pcie_mode` / `pcie_roles` unchanged (they are in the key).
|
||||
* Every device and mapped flag the graphs wait on or raise (`verify_wait_flag_ge_kernel` / `_or_kernel` operands, the group flag
|
||||
rings and doorbell of `raise_group_flag` / `wait_doorbell`, the `verify_clear_status` words, the ident-hit and tail-snapshot
|
||||
flags): back to the value they have at the end of `record_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) and `prof`: cleared.
|
||||
* The canonical GDN image (`reseed`) and the PLE history image (`seed.ple_history`, through the journal's `ple` handle).
|
||||
|
||||
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.
|
||||
|
||||
Reference in New Issue
Block a user