From feba35f91ad6bd234cb852c18b3c91acdb191074 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 7 Nov 2026 10:28:38 +0100 Subject: [PATCH] STRA-338 size4 s12: wrap comments to 120 columns; split the long tests (serve_in, read_chunks, churn, ledger comparison, tail skip) --- .../original_serve_engine/tests.rs | 60 ++++++------ .../tests/constructor_validates_dimensions.rs | 4 +- .../tests/restore_attempts_do_not_depend.rs | 22 +++-- .../src/qwen_forward/original_serve_host.rs | 3 +- .../impl_requestsampling.rs | 6 +- .../src/qwen_forward/original_serve_ledger.rs | 50 ++++++---- .../src/qwen_forward/original_serve_native.rs | 3 +- .../impl_nativewindow.rs | 24 +++-- .../src/qwen_forward/original_serve_pool.rs | 6 +- .../original_serve_pool/impl_directtier.rs | 15 ++- .../impl_drop_for_directtier.rs | 3 +- .../prefetch_off_file_exists_fn.rs | 6 +- .../src/qwen_forward/original_serve_prefix.rs | 18 ++-- .../impl_prefixconfig.rs | 12 ++- .../impl_prefixserve/impl_prefixserve_2.rs | 3 +- .../impl_prefixserve/impl_prefixserve_2_2.rs | 9 +- .../original_serve_prefix/tests.rs | 79 +++++++-------- .../tests/one_token_prompt_reads.rs | 98 ++++++++++++------- .../tests/second_session.rs | 21 ++-- .../qwen_forward/original_serve_residency.rs | 57 +++++++---- .../impl_std_fmt_debug.rs | 3 +- .../original_serve_residency/open_tier_fn.rs | 12 ++- .../split_group_pcie_fn.rs | 30 ++++-- .../tail_skip_rank_fn.rs | 18 ++-- .../original_serve_residency/tests.rs | 23 +++-- .../src/qwen_forward/original_serve_seed.rs | 18 ++-- .../src/qwen_forward/original_serve_stack.rs | 21 ++-- .../impl_default_for_ttftmarks.rs | 3 +- 28 files changed, 395 insertions(+), 232 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs index e5d8f8b6..9ceebf2a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs @@ -300,15 +300,27 @@ fn serve_in( mut cancel: impl FnMut() -> bool, fail_emit_after: Option, max_context: i64, -) -> ( +) -> ServedIn { + let (f, w) = Fake::new(p); + let s = serve_settings(max_context); + let mut e = OriginalServeEngine::new(f, VOCAB, s.max_t, s.max_t - 1).unwrap(); + let mut c = s.controller().unwrap(); + let mut out = Vec::new(); + let emit = recording_emit(&mut out, Rc::clone(&w), fail_emit_after); + let r = serve_request(&mut c, &mut e, p, max_new, 0.0, eos, emit, &mut cancel, || 0.0); + (r, out, c, e, w) +} + +type ServedIn = ( std::result::Result, Vec, OriginalSpecController, OriginalServeEngine, Rc>, -) { - let (f, w) = Fake::new(p); - let s = OriginalServeSettings { +); + +fn serve_settings(max_context: i64) -> OriginalServeSettings { + OriginalServeSettings { max_t: 4, mtp_max_t: 0, max_context, @@ -318,30 +330,22 @@ fn serve_in( adaptive: None, nan_guard: NanGuard::off(), request_min_p: None, - }; - let mut e = OriginalServeEngine::new(f, VOCAB, s.max_t, s.max_t - 1).unwrap(); - let mut c = s.controller().unwrap(); - let mut out = Vec::new(); - let wc = Rc::clone(&w); - let r = serve_request( - &mut c, - &mut e, - p, - max_new, - 0.0, - eos, - |t| { - if fail_emit_after.is_some_and(|n| out.len() >= n) { - return Err(Error::InputRead); - } - out.extend_from_slice(t); - wc.borrow_mut().committed.extend_from_slice(t); - Ok(()) - }, - &mut cancel, - || 0.0, - ); - (r, out, c, e, w) + } +} + +fn recording_emit<'a>( + out: &'a mut Vec, + world: Rc>, + fail_emit_after: Option, +) -> impl FnMut(&[i32]) -> Result<()> + 'a { + move |t| { + if fail_emit_after.is_some_and(|n| out.len() >= n) { + return Err(Error::InputRead); + } + out.extend_from_slice(t); + world.borrow_mut().committed.extend_from_slice(t); + Ok(()) + } } #[path = "tests/constructor_validates_dimensions.rs"] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/constructor_validates_dimensions.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/constructor_validates_dimensions.rs index e592f11d..83c21eb9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/constructor_validates_dimensions.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/constructor_validates_dimensions.rs @@ -1,4 +1,6 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): constructor_validates_dimensions, verify_returns_all_t_outputs_and_requires_a_drained_window, out_of_range_tokens_never_reach_the_port, a_short_or_invalid_window_is_drained_not_leaked .... +//! Tests of tests by topic (moved out of the test file by STRA-338): constructor_validates_dimensions, +//! verify_returns_all_t_outputs_and_requires_a_drained_window, out_of_range_tokens_never_reach_the_port, +//! a_short_or_invalid_window_is_drained_not_leaked .... #[allow(unused_imports)] use super::*; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/restore_attempts_do_not_depend.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/restore_attempts_do_not_depend.rs index 9282ac32..7c5df2f9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/restore_attempts_do_not_depend.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/restore_attempts_do_not_depend.rs @@ -1,4 +1,7 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): restore_attempts_do_not_depend_on_engine_health_and_reset_draft_state, a_refused_window_is_taken_back_only_after_it_drained_and_a_failed_take_back_poisons, first_draft_path_is_cached_and_drains, controller_over_the_engine_emits_the_greedy_continuation .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! restore_attempts_do_not_depend_on_engine_health_and_reset_draft_state, +//! a_refused_window_is_taken_back_only_after_it_drained_and_a_failed_take_back_poisons, +//! first_draft_path_is_cached_and_drains, controller_over_the_engine_emits_the_greedy_continuation .... #[allow(unused_imports)] use super::*; @@ -174,11 +177,7 @@ fn a_window_cap_narrows_every_bound_and_leaves_the_rest() { (wide.max_context, wide.vocabulary, wide.suffix_min_match, wide.coupled) ); assert_eq!(s.nan_guard, wide.nan_guard); - // the controller and the engine accept it - let c = s.controller().unwrap(); - assert!(c.finished() && !c.is_failed()); - let (f, _) = Fake::new(&prompt_long()); - assert!(OriginalServeEngine::new(f, VOCAB, s.max_t, s.max_drafts()).is_ok(), "cap {cap}"); + assert_controller_and_engine_accept(&s, cap); } // a cap above the settings changes nothing; a fixed window narrower than the cap keeps its own width assert_eq!(wide.with_window_cap(8), wide); @@ -189,6 +188,14 @@ fn a_window_cap_narrows_every_bound_and_leaves_the_rest() { assert!(narrow.adaptive.is_none()); } +fn assert_controller_and_engine_accept(s: &OriginalServeSettings, cap: usize) { + // the controller and the engine accept it + let c = s.controller().unwrap(); + assert!(c.finished() && !c.is_failed()); + let (f, _) = Fake::new(&prompt_long()); + assert!(OriginalServeEngine::new(f, VOCAB, s.max_t, s.max_drafts()).is_ok(), "cap {cap}"); +} + #[test] fn mode17_settings_follow_generate_defaults() { let s = OriginalServeSettings::mode17(4096, VOCAB, false); @@ -203,7 +210,8 @@ fn mode17_settings_follow_generate_defaults() { assert!(OriginalServeSettings { vocabulary: 0, ..s }.controller().is_err()); } -/// Upstream 41cf05a0 `e85567b6`: through the real engine (plan, cap and cross-check of the chain), a request that runs to the +/// Upstream 41cf05a0 `e85567b6`: through the real engine (plan, cap and cross-check of the chain), a request that runs +/// to the /// context's end never touches a cell past it, whatever the distance of the last windows to it. #[test] fn serve_request_to_the_context_end_stays_inside_the_cells_and_ends_as_context() { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs index 6a077044..7df760d3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs @@ -86,7 +86,8 @@ pub(in crate::qwen_forward) struct OriginalServeHost<'a, 'ctx> { window_origin: Option, /// A draft launched behind the enqueued commit, completed after the publication (`launch_draft`). launched: Option, - /// The round whose adaptive swaps are still to be planned and queued (`LELEKA_SERVE_ADAPT_DEFER`, default on): the host does that + /// The round whose adaptive swaps are still to be planned and queued (`LELEKA_SERVE_ADAPT_DEFER`, default on): the + /// host does that /// work while the GPU runs the draft instead of before the commit and the draft are enqueued. deferred_adaptation: Option, } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_requestsampling.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_requestsampling.rs index 91175f23..190e8b05 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_requestsampling.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_requestsampling.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl RequestSampling, fn serial_publish, fn operator_line, impl OriginalServeHost, fn adapt_defer, impl OriginalServeHost. +//! Moved out of the parent module by STRA-338: impl RequestSampling, fn serial_publish, fn operator_line, impl +//! OriginalServeHost, fn adapt_defer, impl OriginalServeHost. #[allow(unused_imports)] use super::*; @@ -165,7 +166,8 @@ impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { } } -/// `LELEKA_SERVE_ADAPT_DEFER=off`: plan and queue the adaptive swaps before the commit (the earlier order; the A/B control). +/// `LELEKA_SERVE_ADAPT_DEFER=off`: plan and queue the adaptive swaps before the commit (the earlier order; the A/B +/// control). pub(super) fn adapt_defer() -> bool { crate::settings::process().decode.adapt_defer } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_ledger.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_ledger.rs index e6f5c04f..7d74f8c1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_ledger.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_ledger.rs @@ -43,7 +43,8 @@ pub(in crate::qwen_forward) struct ServeLedger { /// published; the owners must be rolled back to the session's lineage before they are reused. dirty: bool, failed: bool, - /// What `agrees_with` already compared: the controller's `consumed` and `committed` only grow, so each round compares the tokens + /// What `agrees_with` already compared: the controller's `consumed` and `committed` only grow, so each round + /// compares the tokens /// appended since the last one (a full pass every `token_memo::FULL_EVERY` rounds) instead of both whole histories. agreed: Cell, } @@ -66,7 +67,8 @@ impl ServeLedger { agreed: Cell::new(PrefixMemo::new()), }) } - /// `committed == consumed`, examining only the tokens appended since the last successful comparison of the same buffer. + /// `committed == consumed`, examining only the tokens appended since the last successful comparison of the same + /// buffer. pub(in crate::qwen_forward) fn agrees_with(&self, consumed: &[i32]) -> bool { let mut memo = self.agreed.get(); let equal = memo.equal(consumed, &self.committed); @@ -242,17 +244,7 @@ mod tests { let mut consumed: Vec = Vec::with_capacity(64); consumed.extend_from_slice(&[1, 2, 3]); assert!(l.agrees_with(&consumed)); - // rounds: both histories grow by the committed tokens, the memo only needs the new ones - for round in 0..100 { - let t = [10 + round, 11 + round]; - l.committed.extend_from_slice(&t); - consumed.extend_from_slice(&t); - assert!(l.agrees_with(&consumed), "round {round}"); - assert!( - l.validate_current(&consumed, 7, consumed.len() as i64, consumed.len() as u64).is_ok(), - "round {round}" - ); - } + grow_both_histories_for_a_hundred_rounds(&mut l, &mut consumed); // the controller's newest token differs from the ledger's, or its length does let n = consumed.len(); consumed[n - 1] ^= 1; @@ -260,13 +252,10 @@ mod tests { consumed[n - 1] ^= 1; assert!(l.agrees_with(&consumed), "restored"); assert!(!l.agrees_with(&consumed[..n - 1])); - // an old token rewritten in place (no owner does this) is found by the periodic full pass - consumed[n - 2] ^= 1; - let found = (1..=crate::qwen_forward::token_memo::FULL_EVERY + 1).find(|_| !l.agrees_with(&consumed)); - assert!(found.is_some(), "the full pass must find the rewritten token"); - consumed[n - 2] ^= 1; + assert_the_periodic_full_pass_finds_a_rewritten_token(&mut l, &mut consumed); assert!(l.agrees_with(&consumed)); - // another buffer with the same contents agrees, another buffer with different contents does not (whatever was remembered) + // another buffer with the same contents agrees, another buffer with different contents does not (whatever was + // remembered) let copy = consumed.clone(); assert!(l.agrees_with(©)); let mut other = copy.clone(); @@ -275,6 +264,29 @@ mod tests { assert!(l.agrees_with(©)); } + fn grow_both_histories_for_a_hundred_rounds(l: &mut ServeLedger, consumed: &mut Vec) { + // rounds: both histories grow by the committed tokens, the memo only needs the new ones + for round in 0..100 { + let t = [10 + round, 11 + round]; + l.committed.extend_from_slice(&t); + consumed.extend_from_slice(&t); + assert!(l.agrees_with(consumed), "round {round}"); + assert!( + l.validate_current(consumed, 7, consumed.len() as i64, consumed.len() as u64).is_ok(), + "round {round}" + ); + } + } + + fn assert_the_periodic_full_pass_finds_a_rewritten_token(l: &mut ServeLedger, consumed: &mut [i32]) { + // an old token rewritten in place (no owner does this) is found by the periodic full pass + let n = consumed.len(); + consumed[n - 2] ^= 1; + let found = (1..=crate::qwen_forward::token_memo::FULL_EVERY + 1).find(|_| !l.agrees_with(consumed)); + assert!(found.is_some(), "the full pass must find the rewritten token"); + consumed[n - 2] ^= 1; + } + #[test] fn a_published_window_appends_exactly_the_accepted_inputs_and_cleans_the_ledger() { let mut l = ledger(&[1, 2]); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native.rs index bb1f6625..accb5e6e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native.rs @@ -52,7 +52,8 @@ pub(in crate::qwen_forward) trait NativeServeHost<'ctx> { committed: &[i32], ) -> Result<()>; fn begin_adaptation(&mut self, next_round: u64) -> Result; - /// Adaptive work a host deferred at `begin_adaptation`: run it now (the draft is launched, the GPU is busy). A host that does its work + /// Adaptive work a host deferred at `begin_adaptation`: run it now (the draft is launched, the GPU is busy). A + /// host that does its work /// at `begin_adaptation` has nothing to run. `join_adaptation` must run whatever is still deferred. fn run_deferred_adaptation(&mut self) -> Result<()> { Ok(()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_nativewindow.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_nativewindow.rs index 7e6e7717..dc936239 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_nativewindow.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_nativewindow.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl NativeWindow, impl NativeServePort, fn trace_logprobs, fn trace_draft, fn trace_draft_line, fn trace_residual .... +//! Moved out of the parent module by STRA-338: impl NativeWindow, impl NativeServePort, fn trace_logprobs, fn +//! trace_draft, fn trace_draft_line, fn trace_residual .... #[allow(unused_imports)] use super::*; @@ -225,8 +226,10 @@ where pub(super) fn trace_logprobs() -> Option { crate::settings::process().decode.trace_logprobs } -/// `LELEKA_TRACE_DRAFT=1`: one line per completed draft (position, accepted row, the draft ids and the IEEE bits of their probabilities). The draft's numerics -/// are bit-compared across builds and settings by diffing these lines (draft-round identity gate); nothing reads them in production. +/// `LELEKA_TRACE_DRAFT=1`: one line per completed draft (position, accepted row, the draft ids and the IEEE bits of +/// their probabilities). The draft's numerics +/// are bit-compared across builds and settings by diffing these lines (draft-round identity gate); nothing reads them +/// in production. pub(super) fn trace_draft() -> bool { crate::settings::process().decode.trace_draft } @@ -247,17 +250,22 @@ pub(super) fn trace_residual() -> Option<&'static std::ffi::OsString> { } /// `LELEKA_SERVE_OVERLAP=off`: settle the commit (wait + publish) before the draft launches (the earlier, serialized -/// order; A/B control). Default: the draft is enqueued while the commit runs (`draft_waits_for_commit` says whether it also waits for +/// order; A/B control). Default: the draft is enqueued while the commit runs (`draft_waits_for_commit` says whether it +/// also waits for /// the commit event on the device), and the host publishes the session while the draft's first graph runs. pub(super) fn overlap() -> bool { crate::settings::process().decode.overlap } /// Whether the draft stream waits for the verifier's commit event on the device before its first command. -/// Upstream's serve loop does not: `Verifier::commit` (core/verify.cpp, `set_commit_async`) enqueues the commit graph on the verifier's -/// stream and returns, and `MtpDrafter::draft` launches the round graph on the drafter's own stream with no dependency on it ("the drafter -/// (its own stream) reads only this window's final rows and its own K/V"), so the two graphs run side by side. The earlier port enqueued -/// the draft behind the commit event, which put the commit graph (~0.36 ms: 36 GDN layers, 12 QSA appends, the PLE history) in front of +/// Upstream's serve loop does not: `Verifier::commit` (core/verify.cpp, `set_commit_async`) enqueues the commit graph +/// on the verifier's +/// stream and returns, and `MtpDrafter::draft` launches the round graph on the drafter's own stream with no dependency +/// on it ("the drafter +/// (its own stream) reads only this window's final rows and its own K/V"), so the two graphs run side by side. The +/// earlier port enqueued +/// the draft behind the commit event, which put the commit graph (~0.36 ms: 36 GDN layers, 12 QSA appends, the PLE +/// history) in front of /// every draft on the critical path. `LELEKA_SERVE_DRAFT_AFTER_COMMIT=on` restores that order (A/B control). pub(super) fn draft_waits_for_commit() -> bool { crate::settings::process().decode.draft_after_commit diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool.rs index a432eca7..0648ef50 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool.rs @@ -151,10 +151,12 @@ struct DirectTier { /// Which experts of the next layer the VRAM tier holds (set by the tier before each group). next_resident: Vec, /// Admitted experts' validated spans and formats by (layer, expert): the bank spans are immutable, so a group whose - /// experts are all here skips the per-expert source scope (claude/decode-parity; `LELEKA_OPEN_CACHE=on` enables; not measured on a device yet). + /// experts are all here skips the per-expert source scope (claude/decode-parity; `LELEKA_OPEN_CACHE=on` enables; + /// not measured on a device yet). opened_cache: Vec>, open_cache_on: bool, - /// Whether a group runs the page-touch pass over its mapped experts (`LELEKA_CPU_PREFETCH=on|off` force it; on Windows it is + /// Whether a group runs the page-touch pass over its mapped experts (`LELEKA_CPU_PREFETCH=on|off` force it; on + /// Windows it is /// chosen by measurement, see `prefetch_policy`). prefetch: super::prefetch_policy::PrefetchPolicy, } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_directtier.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_directtier.rs index 67a623e9..436a2fd7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_directtier.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_directtier.rs @@ -1,13 +1,18 @@ -//! Moved out of the parent module by STRA-338: impl DirectTier, impl CpuExpertPool, impl OriginalServePool_for_CpuExpertPool. +//! Moved out of the parent module by STRA-338: impl DirectTier, impl CpuExpertPool, impl +//! OriginalServePool_for_CpuExpertPool. #[allow(unused_imports)] use super::*; impl DirectTier { - /// Admit every routed expert of every layer now (stack open), through the same `open_group` admission the decode runs at an - /// expert's first CPU or PCIe use (source scope, descriptor checks, the full FP16-scale scan of `mapped_span`): the checks are - /// unchanged, they only stop costing the decode its first use of each expert (~50 us each on the 5090 host, 1.3 ms per round - /// in the first request of a fresh process). Returns how many were admitted. `LELEKA_CPU_ADMIT_EAGER=off`: first use, as before. + /// Admit every routed expert of every layer now (stack open), through the same `open_group` admission the decode + /// runs at an + /// expert's first CPU or PCIe use (source scope, descriptor checks, the full FP16-scale scan of `mapped_span`): + /// the checks are + /// unchanged, they only stop costing the decode its first use of each expert (~50 us each on the 5090 host, 1.3 ms + /// per round + /// in the first request of a fresh process). Returns how many were admitted. `LELEKA_CPU_ADMIT_EAGER=off`: first + /// use, as before. pub(super) fn admit_all(&mut self, binding: &ModelBinding) -> Result { let all: Vec = (0..EXPERTS as u32).collect(); let mut admitted = 0usize; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_drop_for_directtier.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_drop_for_directtier.rs index 0ce4eb0e..1e225e49 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_drop_for_directtier.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_drop_for_directtier.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Drop_for_DirectTier, fn admit_eager, fn sink_result, fn native_cpu_error, fn selection. +//! Moved out of the parent module by STRA-338: impl Drop_for_DirectTier, fn admit_eager, fn sink_result, fn +//! native_cpu_error, fn selection. #[allow(unused_imports)] use super::*; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/prefetch_off_file_exists_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/prefetch_off_file_exists_fn.rs index 28fc69cf..08d057f8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/prefetch_off_file_exists_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/prefetch_off_file_exists_fn.rs @@ -1,9 +1,11 @@ -//! Moved out of the parent module by STRA-338: fn prefetch_off_file_exists, fn plan_experts, fn plan_experts_where, fn output_offset, fn scatter, impl PoolPath .... +//! Moved out of the parent module by STRA-338: fn prefetch_off_file_exists, fn plan_experts, fn plan_experts_where, fn +//! output_offset, fn scatter, impl PoolPath .... #[allow(unused_imports)] use super::*; -/// A bring-up file (`LELEKA_CPU_PREFETCH_OFF_FILE`, A/B inside one engine): while it exists the page-touch pass is skipped, whatever the policy says. +/// A bring-up file (`LELEKA_CPU_PREFETCH_OFF_FILE`, A/B inside one engine): while it exists the page-touch pass is +/// skipped, whatever the policy says. pub(super) fn prefetch_off_file_exists() -> bool { let file = crate::settings::process().memory.pool.prefetch_off_file.as_ref(); file.is_some_and(|f| std::path::Path::new(f).exists()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix.rs index b574490b..61fe6f06 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix.rs @@ -35,18 +35,22 @@ pub(crate) enum PrefixBudget { /// Checkpoints between two grid points (`--prefix-cache-tail`): the position where the NEXT turn of an agent resumes. /// -/// An agent resends its whole history, and the next prompt is the previous prompt, the model's reply (token for token) and -/// about a hundred new tokens. A grid node alone makes the next turn re-read the part of the last block, the whole reply and +/// An agent resends its whole history, and the next prompt is the previous prompt, the model's reply (token for token) +/// and +/// about a hundred new tokens. A grid node alone makes the next turn re-read the part of the last block, the whole +/// reply and /// the new tokens; a checkpoint at the exact end of the previous request makes it read only the new tokens. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum TailMode { /// Grid nodes only: every checkpoint is a pure function of its tokens and a hit equals a full read on the grid. Off, - /// A checkpoint at the end of the PROMPT's prefill (position `n - 1`): the cut is an extra chunk boundary, the state is a + /// A checkpoint at the end of the PROMPT's prefill (position `n - 1`): the cut is an extra chunk boundary, the + /// state is a /// prefill state. The next turn re-reads the reply and the new tokens. Prompt, /// Also a checkpoint at the end of the DECODE (the prompt and the committed reply): the state is the one the model - /// generated from (the Original's live continuation), the cut and the arithmetic differ from a full read at rounding level. + /// generated from (the Original's live continuation), the cut and the arithmetic differ from a full read at + /// rounding level. /// The next turn re-reads only the new tokens. Reply, } @@ -56,7 +60,8 @@ pub(crate) struct PrefixConfig { pub(crate) budget: PrefixBudget, /// Checkpoints at request ends (default off). pub(crate) tail: TailMode, - /// Tokens per block and per chunk-grid step; 0 = the prefill capacity (a grid step is then one full chunk, so the prefill runs + /// Tokens per block and per chunk-grid step; 0 = the prefill capacity (a grid step is then one full chunk, so the + /// prefill runs /// at the speed of the chunk size the operator chose). pub(crate) block_tokens: usize, pub(crate) max_nodes: usize, @@ -79,7 +84,8 @@ pub(super) trait PrefixDevice { fn park_state(&mut self) -> Result; /// Park the cells `first .. first + tokens`. fn park_block(&mut self, first: usize, tokens: usize) -> Result; - /// Park the cells `first .. first + tokens` where `tokens` need not be a multiple of the 4-cell page (a request-end checkpoint's + /// Park the cells `first .. first + tokens` where `tokens` need not be a multiple of the 4-cell page (a + /// request-end checkpoint's /// partial block: whole pages, the cells past the end are never read). fn park_tail(&mut self, first: usize, tokens: usize) -> Result; /// Install `state` and write `blocks` (`(block index, payload)`, each `block_tokens` cells from diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixconfig.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixconfig.rs index 099b828d..6871db35 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixconfig.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixconfig.rs @@ -44,10 +44,14 @@ impl PrefixConfig { } } -/// The available memory a checkpoint of `additional` bytes is judged against. On Windows the engine's touched mapped expert pages sit in its -/// working set and count as used although they are trimmable, and the periodic trim only runs below the soft floor: a host that reads a little -/// above the soft floor and below the admit floor (soft + reserve) refused every checkpoint (the prompt-end tail of turn 1 of the laptop session, -/// 0.2 GiB, was refused at 8.9 GiB against a floor of 9.2 GiB, and turn 2 re-read 2,753 tokens from the last grid point). So a refusal is +/// The available memory a checkpoint of `additional` bytes is judged against. On Windows the engine's touched mapped +/// expert pages sit in its +/// working set and count as used although they are trimmable, and the periodic trim only runs below the soft floor: a +/// host that reads a little +/// above the soft floor and below the admit floor (soft + reserve) refused every checkpoint (the prompt-end tail of +/// turn 1 of the laptop session, +/// 0.2 GiB, was refused at 8.9 GiB against a floor of 9.2 GiB, and turn 2 re-read 2,753 tokens from the last grid +/// point). So a refusal is /// re-judged once after the governor hands the trimmable pages back. pub(super) fn admission_reading(reading: Option, additional: u64, floor: u64) -> Option { let needed = additional.saturating_add(floor); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs index 7b47aacb..1818289e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs @@ -65,7 +65,8 @@ impl PrefixServe { self.clock.elapsed_ms() } - /// Apply the memory governor's shed directive (`Governor::directive`): `Some(bytes)` evicts down to that budget (lowest + /// Apply the memory governor's shed directive (`Governor::directive`): `Some(bytes)` evicts down to that budget + /// (lowest /// expected-value-per-byte first), `None` restores the configured one after a shed. Returns the bytes evicted. pub(in super::super::super) fn apply_shed( &mut self, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs index 9963c4cc..2bf76ad2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs @@ -107,7 +107,8 @@ impl PrefixServe { } Ok((state, blocks)) } - /// The state and block sizes an admission is estimated with: what the last checkpoint measured, else the device's guess. + /// The state and block sizes an admission is estimated with: what the last checkpoint measured, else the device's + /// guess. fn estimate_blocks>(&self, device: &D) -> (usize, usize) { let (est_state, est_block) = device.estimate(self.block_tokens); (self.seen_state_bytes.unwrap_or(est_state), self.seen_block_bytes.unwrap_or(est_block)) @@ -140,7 +141,8 @@ impl PrefixServe { } } - /// The end of the prompt's prefill: the session stands at `prompt.len() - 1`. With `TailMode::Prompt` or `Reply`, checkpoint + /// The end of the prompt's prefill: the session stands at `prompt.len() - 1`. With `TailMode::Prompt` or `Reply`, + /// checkpoint /// there (a request-end checkpoint), unless that is a grid point. pub(in super::super::super) fn after_prefill>( &mut self, @@ -161,7 +163,8 @@ impl PrefixServe { self.admit_tail(device, &prompt[..end], None) } - /// The end of the decode: the session stands at `consumed.len()` (the prompt and the committed reply), settled, with the draft + /// The end of the decode: the session stands at `consumed.len()` (the prompt and the committed reply), settled, + /// with the draft /// ring in step. With `TailMode::Reply`, checkpoint there; the cells past the prompt are decode-produced. /// The reason the last checkpoint attempt was not taken, with the numbers; read once. pub(in super::super::super) fn take_note(&mut self) -> Option { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs index 6d8b34e6..967117ef 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs @@ -117,6 +117,22 @@ pub(super) fn request( prompt: &[i32], stop_after_chunks: Option, ) -> (Option, u64) { + let (start, resume) = begin_request(s, d, prompt); + if read_chunks(s, d, prompt, (resume, stop_after_chunks)) { + // cancelled before a chunk + s.finish(true); + return (start, d.digest); + } + assert_eq!(d.position as usize, prompt.len() - 1); + // the invariant that matters: the cells the session reads are this prompt's + assert_eq!(&d.cells[..prompt.len() - 1], &prompt[..prompt.len() - 1]); + s.after_prefill(d, prompt).unwrap(); + s.finish(true); + (start, d.digest) +} + +/// `begin` of one request; the position the prompt resumes at (0 without a hit, the owners are reset). +fn begin_request(s: &mut PrefixServe, d: &mut Fake, prompt: &[i32]) -> (Option, usize) { let start = s.begin(d, prompt).unwrap(); let resume = match &start { Some(st) => st.resume, @@ -127,26 +143,35 @@ pub(super) fn request( 0 } }; - let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); + (start, resume) +} + +fn grid_options(s: &PrefixServe, resume: usize) -> PromptOptions { // like the stack: a request that resumed between two grid points reads the way a full read of its own would let grid = if resume % s.block_tokens() == 0 { s.block_tokens() } else { 0 }; - let options = PromptOptions { + PromptOptions { grid, prompt_cache: false, turn_token: None, root_min: 0, force_batched: true, ..PromptOptions::original_mode17(1 << 16) - }; + } +} + +/// Read the chunks of the prompt plan from `resume` (the first of `at`) on the grid; `true`: the request was +/// cancelled before the chunk after which the second of `at` says to stop. +fn read_chunks(s: &mut PrefixServe, d: &mut Fake, prompt: &[i32], at: (usize, Option)) -> bool { + let (resume, stop_after_chunks) = at; + let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); + let options = grid_options(s, resume); let mut chunks = 0; for action in PromptPlan::new(&tokens, resume, None, None, options, 1024).unwrap() { if action.path == PromptPath::FinalSeed { break; } if stop_after_chunks == Some(chunks) { - // cancelled before this chunk - s.finish(true); - return (start, d.digest); + return true; } s.before_chunk(action.first); // a chunk interrupted half way would have written part of its cells: model it by a failing chunk @@ -154,16 +179,13 @@ pub(super) fn request( s.after_chunk(d, prompt, action.first + action.count).unwrap(); chunks += 1; } - assert_eq!(d.position as usize, prompt.len() - 1); - // the invariant that matters: the cells the session reads are this prompt's - assert_eq!(&d.cells[..prompt.len() - 1], &prompt[..prompt.len() - 1]); - s.after_prefill(d, prompt).unwrap(); - s.finish(true); - (start, d.digest) + false } -/// An agent turn: `request`, then the decode of `reply` (the session consumes the last prompt token and every reply token but the -/// last, which is the pending input) and the request-end checkpoint of `TailMode::Reply`. Returns (start, digest after the +/// An agent turn: `request`, then the decode of `reply` (the session consumes the last prompt token and every reply +/// token but the +/// last, which is the pending input) and the request-end checkpoint of `TailMode::Reply`. Returns (start, digest after +/// the /// prefill, the consumed tokens). fn turn( s: &mut PrefixServe, @@ -171,33 +193,8 @@ fn turn( prompt: &[i32], reply: &[i32], ) -> (Option, u64, Vec) { - let start = s.begin(d, prompt).unwrap(); - let resume = match &start { - Some(st) => st.resume, - None => { - d.position = 0; - d.digest = 0; - 0 - } - }; - let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); - let grid = if resume % s.block_tokens() == 0 { s.block_tokens() } else { 0 }; - let options = PromptOptions { - grid, - prompt_cache: false, - turn_token: None, - root_min: 0, - force_batched: true, - ..PromptOptions::original_mode17(1 << 16) - }; - for action in PromptPlan::new(&tokens, resume, None, None, options, 1024).unwrap() { - if action.path == PromptPath::FinalSeed { - break; - } - s.before_chunk(action.first); - d.read(&prompt[action.first..action.first + action.count], action.first); - s.after_chunk(d, prompt, action.first + action.count).unwrap(); - } + let (start, resume) = begin_request(s, d, prompt); + read_chunks(s, d, prompt, (resume, None)); s.after_prefill(d, prompt).unwrap(); let digest = d.digest; let mut consumed = prompt[..prompt.len() - 1].to_vec(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/one_token_prompt_reads.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/one_token_prompt_reads.rs index fd1fb0df..de6aec91 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/one_token_prompt_reads.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/one_token_prompt_reads.rs @@ -1,9 +1,14 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): a_one_token_prompt_reads_nothing_and_claims_nothing, a_failed_import_is_an_error_for_the_caller_and_invalidate_forgets_everything, the_budget_bounds_the_store_and_the_newest_frontier_survives, a_memory_shed_evicts_to_the_target_and_the_configured_budget_comes_back .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! a_one_token_prompt_reads_nothing_and_claims_nothing, +//! a_failed_import_is_an_error_for_the_caller_and_invalidate_forgets_everything, +//! the_budget_bounds_the_store_and_the_newest_frontier_survives, +//! a_memory_shed_evicts_to_the_target_and_the_configured_budget_comes_back .... #[allow(unused_imports)] use super::*; -/// Upstream 41cf05a0 `aece46db` (a 1-token prompt with `--spec`): the prompt has no token to read (the single token is the first +/// Upstream 41cf05a0 `aece46db` (a 1-token prompt with `--spec`): the prompt has no token to read (the single token is +/// the first /// verify input), so nothing is looked up, read or checkpointed and no claim is made on the buffer. #[test] fn a_one_token_prompt_reads_nothing_and_claims_nothing() { @@ -83,20 +88,29 @@ fn a_memory_shed_evicts_to_the_target_and_the_configured_budget_comes_back() { let (_, digest) = request(&mut s, &mut d, &prompts[0], None); assert_eq!(digest, full_digest(&prompts[0])); assert!(s.bytes() <= s.budget_bytes(), "the shed budget bounds the store"); + assert_a_zero_budget_admits_nothing_and_the_configured_one_comes_back(&mut s, &mut d, &prompts, &g); +} + +fn assert_a_zero_budget_admits_nothing_and_the_configured_one_comes_back( + s: &mut PrefixServe, + d: &mut Fake, + prompts: &[Vec], + g: &leleka_memory::Governor, +) { // everything goes at reject; the next request reads from 0 and is exact - s.apply_shed(Some(0), &g); + s.apply_shed(Some(0), g); assert_eq!((s.bytes(), s.node_count(), s.block_count()), (0, 0, 0)); - let (start, digest) = request(&mut s, &mut d, &prompts[1], None); + let (start, digest) = request(s, d, &prompts[1], None); assert_eq!(start, None); assert_eq!(digest, full_digest(&prompts[1])); assert_eq!(s.bytes(), 0, "nothing is admitted while the budget is zero"); // pressure over: the configured budget is restored and the cache refills - assert_eq!(s.apply_shed(None, &g), 0); + assert_eq!(s.apply_shed(None, g), 0); assert_eq!(s.budget_bytes(), 1 << 30); - request(&mut s, &mut d, &prompts[2], None); + request(s, d, &prompts[2], None); assert!(s.bytes() > 0); // a directive that asks for more than the configured budget never raises it - s.apply_shed(Some(u64::MAX), &g); + s.apply_shed(Some(u64::MAX), g); assert_eq!(s.budget_bytes(), 1 << 30); s.store().check_invariants(); } @@ -108,46 +122,64 @@ fn churn_under_random_shed_directives_keeps_every_resume_exact_and_the_store_ins let mut s = PrefixServe::new(cfg(), 1024, budget as u64, "test"); let mut d = Fake::new(); let mut prompts: Vec> = (1..=5).map(|i| session(i, 2, 4, 10)).collect(); - let mut x = 0x2545_f491_4f6c_dd1du64; - let mut next = move || { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x - }; + let mut next = xorshift(0x2545_f491_4f6c_dd1du64); let mut shed_events = 0; for turn in 0..300 { let who = (next() % 5) as usize; - match next() % 8 { - 0 => { - s.apply_shed(Some(next() % (budget as u64 + 1)), &g); - shed_events += 1; - } - 1 => { - s.apply_shed(None, &g); - } - 2 if s.bytes() > 0 => { - s.apply_shed(Some(0), &g); - shed_events += 1; - } - _ => {} - } + shed_events += random_shed(&mut s, &g, &mut next, budget); let p = &mut prompts[who]; if p.len() < 40 * G { p.extend(doc(turn + 7000, 1, 3)); } let (_, digest) = request(&mut s, &mut d, p, if next() % 9 == 0 { Some(1) } else { None }); // a cancelled request ends mid-prefill: its digest is a partial read, only complete ones are compared - if digest == full_digest(p) { - assert!(s.bytes() <= s.budget_bytes(), "turn {turn}: {} > {}", s.bytes(), s.budget_bytes()); - } - s.store().check_invariants(); - assert!(s.bytes() <= budget, "turn {turn}: the store outgrew its configured budget"); + assert_the_store_stays_inside_its_budget(&s, digest == full_digest(p), turn, budget); } assert!(shed_events > 20, "the schedule exercised shedding"); assert!(s.stats().evicted > 0); } +fn xorshift(mut x: u64) -> impl FnMut() -> u64 { + move || { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x + } +} + +/// One random shed directive of the churn schedule; 1 when it counts as a shed event. +fn random_shed( + s: &mut PrefixServe, + g: &leleka_memory::Governor, + next: &mut impl FnMut() -> u64, + budget: usize, +) -> usize { + match next() % 8 { + 0 => { + s.apply_shed(Some(next() % (budget as u64 + 1)), g); + 1 + } + 1 => { + s.apply_shed(None, g); + 0 + } + 2 if s.bytes() > 0 => { + s.apply_shed(Some(0), g); + 1 + } + _ => 0, + } +} + +fn assert_the_store_stays_inside_its_budget(s: &PrefixServe, complete: bool, turn: i32, budget: usize) { + if complete { + assert!(s.bytes() <= s.budget_bytes(), "turn {turn}: {} > {}", s.bytes(), s.budget_bytes()); + } + s.store().check_invariants(); + assert!(s.bytes() <= budget, "turn {turn}: the store outgrew its configured budget"); +} + #[test] fn low_host_memory_skips_the_checkpoint_instead_of_building_it() { let mut s = serve(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/second_session.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/second_session.rs index 139cacb1..a78870b1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/second_session.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/second_session.rs @@ -1,4 +1,8 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): a_second_session_with_the_same_system_prompt_resumes_from_the_shared_blocks_and_ends_in_the_full_reads_state, interleaved_sessions_each_resume_from_their_own_deepest_checkpoint, a_miss_resets_the_owners_so_nothing_is_claimed_even_if_the_request_is_cancelled_before_its_first_chunk, a_checkpoint_at_the_end_of_the_prefill_lets_the_next_turn_resume_at_the_exact_position .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! a_second_session_with_the_same_system_prompt_resumes_from_the_shared_blocks_and_ends_in_the_full_reads_state, +//! interleaved_sessions_each_resume_from_their_own_deepest_checkpoint, +//! a_miss_resets_the_owners_so_nothing_is_claimed_even_if_the_request_is_cancelled_before_its_first_chunk, +//! a_checkpoint_at_the_end_of_the_prefill_lets_the_next_turn_resume_at_the_exact_position .... #[allow(unused_imports)] use super::*; @@ -223,8 +227,10 @@ fn a_cancelled_prefill_never_claims_cells_it_did_not_finish() { assert_eq!(digest, full_digest(&a), "restored from the 3-block checkpoint, finished, and equal to a full read"); } -/// Upstream 41cf05a0 `8824e217`: a request cancelled before its first window lost the conversation it had restored. Here the -/// restore is the request's own `begin`: after a cancel right behind it the store still has every node, the buffer is claimed +/// Upstream 41cf05a0 `8824e217`: a request cancelled before its first window lost the conversation it had restored. +/// Here the +/// restore is the request's own `begin`: after a cancel right behind it the store still has every node, the buffer is +/// claimed /// up to the restored point (the import wrote exactly those cells) and the retry of the same session needs no copy. #[test] fn a_request_cancelled_right_after_restoring_its_session_keeps_it() { @@ -233,7 +239,8 @@ fn a_request_cancelled_right_after_restoring_its_session_keeps_it() { let mut a = session(1, 0, 6, 10); request(&mut s, &mut d, &a, None); let nodes = s.node_count(); - // another session scribbles over the buffer, then A's next turn restores its checkpoint and is cancelled before reading + // another session scribbles over the buffer, then A's next turn restores its checkpoint and is cancelled before + // reading let b = session(2, 0, 6, 10); request(&mut s, &mut d, &b, None); a.extend(doc(777, 1, 40)); @@ -250,8 +257,10 @@ fn a_request_cancelled_right_after_restoring_its_session_keeps_it() { assert_eq!(digest, full_digest(&a)); } -/// Upstream 41cf05a0 `940011da`: a full cache dropped the snapshot instead of evicting. Three sessions into a store with room -/// for about two chains: the newest is cached (the session idle longest pays for it), the store stays inside its budget, and +/// Upstream 41cf05a0 `940011da`: a full cache dropped the snapshot instead of evicting. Three sessions into a store +/// with room +/// for about two chains: the newest is cached (the session idle longest pays for it), the store stays inside its +/// budget, and /// every later resume is exact. #[test] fn a_full_store_evicts_the_session_idle_longest_so_the_newest_request_is_cached() { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs index b9c194dd..ba2122f1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs @@ -50,16 +50,20 @@ const MAX_WINDOW_ENTRIES: usize = 128; const LOAN_FLOOR: usize = 128; /// **EXPERIMENTAL, changes the output** (docs/upstream-port-plan.md row 3.1; upstream `STRATA_ROUTE_TAIL_SKIP`): -/// `LELEKA_ROUTE_TAIL_SKIP=N` (1..=9, unset or 0 = off): a missed expert that every token of the window routes at rank `N` or -/// lower (the rank of the router's descending top-10, 0 = the heaviest) is neither copied over PCIe nor computed on the CPU; -/// its contribution is zero and the other weights are not renormalised. Off while at least `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED` +/// `LELEKA_ROUTE_TAIL_SKIP=N` (1..=9, unset or 0 = off): a missed expert that every token of the window routes at rank +/// `N` or +/// lower (the rank of the router's descending top-10, 0 = the heaviest) is neither copied over PCIe nor computed on +/// the CPU; +/// its contribution is zero and the other weights are not renormalised. Off while at least +/// `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED` /// percent (default 90) of the experts are in VRAM. Not a default of any profile until its own quality gate passes. const TAIL_UNRESOLVED: u32 = u32::MAX; static TAIL_SKIP_RANK: AtomicU32 = AtomicU32::new(TAIL_UNRESOLVED); /// generate.cpp `--pcie-mode auto|dma|kernel` (`direct`, the mapped arena, is not ported): how a window stages its /// PCIe share. `Auto` is DMA on the copy stream (job 981/982, RTX 5090, 6 prompts x 2 passes: +16 % static and +12-15 % -/// adaptive over the copy kernel, which generate.cpp makes its default); `kernel` is the in-graph copy kernel, available +/// adaptive over the copy kernel, which generate.cpp makes its default); `kernel` is the in-graph copy kernel, +/// available /// wherever the expert source has device aliases (a registered resident bank). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum PcieMode { @@ -82,7 +86,8 @@ pub(crate) struct ExpertTierConfig { /// Port: the per-request verifier (bank, canonical GDN image, eight window graphs and the commit graph) /// is assembled for every decode phase, after the cache; auto sizing keeps this much more free for it. pub(crate) decode_reserve_mib: usize, - /// `--pcie-frac` (0.45 here; generate.cpp's default is 0.55): the share of a group's missed experts staged over PCIe (by the + /// `--pcie-frac` (0.45 here; generate.cpp's default is 0.55): the share of a group's missed experts staged over + /// PCIe (by the /// copy kernel or DMA, `pcie_mode`). Only used while the tier is on. pub(crate) pcie_frac: f64, /// `pcie_frac` was set by the operator. Unset, a pageable (low-RAM, file-mapped) bank stages nothing over PCIe: @@ -97,9 +102,11 @@ pub(crate) struct ExpertTierConfig { pub(crate) prefill_borrow: bool, /// `--resident-budget-gib` over the low-RAM file-mapped bank (0: off): see `pin_resident_complement`. pub(crate) resident_budget_gib: f64, - /// EXPERIMENTAL, port-only (`LELEKA_ORIGINAL_SERVE_SEED`): at the end of each request's prompt phase the experts the + /// EXPERIMENTAL, port-only (`LELEKA_ORIGINAL_SERVE_SEED`): at the end of each request's prompt phase the experts + /// the /// prompt's own prefill routed to replace the least-routed resident ones, in one batch of at most this many swaps - /// (0: off). Default when the configuration comes from the environment: `DEFAULT_SEED_SWAPS` (on); `ExpertTierConfig::off()` keeps 0. See `original_serve_seed`. + /// (0: off). Default when the configuration comes from the environment: `DEFAULT_SEED_SWAPS` (on); + /// `ExpertTierConfig::off()` keeps 0. See `original_serve_seed`. pub(crate) seed_swaps: usize, /// `_SEED_KEEP`: routed-row credit given to every resident expert when ranking the seed's swaps (the blend with the /// starting profile; 0 = the prompt's counts alone). @@ -110,15 +117,19 @@ pub(crate) struct ExpertTierConfig { /// `_SEED_DECAY`: at each prompt chunk the earlier chunks' counts are multiplied by this (1 = a plain sum over the /// prompt, 0 = the last chunk alone): the end of a long prompt predicts the answer better than its beginning. pub(crate) seed_decay: f32, - /// EXPERIMENTAL, off by default (0 = no cap; placement-class change, no quality gate yet). `_SEED_MAX_ROWS`: no seed for a prompt whose prefill routed more than this many rows through the experts. The - /// prompt's top experts cover only 9-10 % of the decode routing at 16k tokens (docs/original-serve.md), and a 100k+ prompt + /// EXPERIMENTAL, off by default (0 = no cap; placement-class change, no quality gate yet). `_SEED_MAX_ROWS`: no + /// seed for a prompt whose prefill routed more than this many rows through the experts. The + /// prompt's top experts cover only 9-10 % of the decode routing at 16k tokens (docs/original-serve.md), and a + /// 100k+ prompt /// replaces a good starting set with a worse one. pub(crate) seed_max_rows: usize, } -/// VRAM the per-request verifier (bank, canonical GDN image, window graphs, commit graph) takes at the start of a decode phase, +/// VRAM the per-request verifier (bank, canonical GDN image, window graphs, commit graph) takes at the start of a +/// decode phase, /// after the expert cache: 1,077 MiB free before it, 563 after (5090, `DBG vram` lines of `runs/speedtrain-ab`). pub(crate) const VERIFIER_ASSEMBLY_MIB: usize = 514; -/// The lowest free VRAM vanilla Strata 0.2.6 runs with at 256k (315 MiB after its window captures, `strata verify: capturing ...`): +/// The lowest free VRAM vanilla Strata 0.2.6 runs with at 256k (315 MiB after its window captures, `strata verify: +/// capturing ...`): /// the floor the reserve must keep for ours too, measured with the same context and graph pools. pub(crate) const VANILLA_FREE_FLOOR_MIB: usize = 315; @@ -168,11 +179,14 @@ pub(crate) struct SpanCache { sets: std::collections::HashMap, } -/// `LELEKA_PCIE_AUTO=lag` (claude/decode-parity): equalises the two legs of a layer's miss phase. After the CPU pool has +/// `LELEKA_PCIE_AUTO=lag` (claude/decode-parity): equalises the two legs of a layer's miss phase. After the CPU pool +/// has /// computed its share the host looks at flag B (the PCIe copies landed?) and, when they have not, spins until they do: -/// that wait is how much longer the PCIe leg took than the CPU leg (the host would wait for the GPU there anyway, so the +/// that wait is how much longer the PCIe leg took than the CPU leg (the host would wait for the GPU there anyway, so +/// the /// measurement costs nothing). Per round the mean lag drives the share in 256ths: a PCIe leg that finishes last lowers -/// it, a PCIe leg that finishes first (no lag at all) raises it a little, probing for the point where they meet. Only the +/// it, a PCIe leg that finishes first (no lag at all) raises it a little, probing for the point where they meet. Only +/// the /// split changes, never what an expert computes. #[derive(Debug)] pub(crate) struct PcieLag { @@ -184,10 +198,13 @@ pub(crate) struct PcieLag { } /// `LELEKA_PCIE_AUTO=on` (claude/decode-parity): a hill-climbing controller of the PCIe share. The static share is a -/// balance between the PCIe leg and the CPU pool of a layer, and the best value moves with the staging mode, the link and +/// balance between the PCIe leg and the CPU pool of a layer, and the best value moves with the staging mode, the link +/// and /// the hit rate. Rounds are timed from one `apply_pending` to the next; the cost of a round is its time per -/// (misses + 40) entries (the entries the PCIe/CPU legs carry, plus a floor for the fixed work). Levels are shares in 256ths; -/// every `EXPLORE_EVERY` rounds the neighbours of the incumbent are tried for `TRIAL` rounds each and the cheaper one (by +/// (misses + 40) entries (the entries the PCIe/CPU legs carry, plus a floor for the fixed work). Levels are shares in +/// 256ths; +/// every `EXPLORE_EVERY` rounds the neighbours of the incumbent are tried for `TRIAL` rounds each and the cheaper one +/// (by /// EMA) becomes the incumbent. Only the split changes, never what an expert computes. #[derive(Debug)] pub(crate) struct PcieAuto { @@ -210,7 +227,8 @@ pub(crate) struct ResidencyState { /// generate.cpp `--dump-routing FILE` (`LELEKA_ORIGINAL_SERVE_DUMP_ROUTING`): every decode window row's routed /// experts, as `tools/make_profile.py` reads them (layer i32, k i32, k ids i32, k weights f32). routing: Option>, - /// Cumulative (vram, pcie, cpu) window entries after each verified round of the current request (for the first-rounds + /// Cumulative (vram, pcie, cpu) window entries after each verified round of the current request (for the + /// first-rounds /// hit rates; recorded where the adaptive tier is asked for its round). marks: Vec<[u64; 3]>, /// The counters when the current request began. @@ -235,7 +253,8 @@ pub(in crate::qwen_forward) struct GpuExpertPool<'p, 'a, 'ctx> { pub(in crate::qwen_forward) adapt_swaps: usize, /// The route tail skip rank of this decode phase (0 = off; `effective_tail_rank`). pub(in crate::qwen_forward) tail_rank: u32, - /// `layer * 512 + expert` -> the expert's pages are page-locked (`MappedExpertBank::locked_experts`); empty = every expert may + /// `layer * 512 + expert` -> the expert's pages are page-locked (`MappedExpertBank::locked_experts`); empty = + /// every expert may /// take the PCIe share. Filled only under `LELEKA_PCIE_LOCKED_ONLY` on a pageable bank. pub(in crate::qwen_forward) pcie_locked: Vec, } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/impl_std_fmt_debug.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/impl_std_fmt_debug.rs index 8b9c4395..83e94291 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/impl_std_fmt_debug.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/impl_std_fmt_debug.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl std_fmt_Debug, fn span_cache_enabled, impl SpanCache, impl PcieLag, impl PcieAuto, impl ResidencyState .... +//! Moved out of the parent module by STRA-338: impl std_fmt_Debug, fn span_cache_enabled, impl SpanCache, impl +//! PcieLag, impl PcieAuto, impl ResidencyState .... #[allow(unused_imports)] use super::*; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier_fn.rs index f50ed2fe..b5b07bd5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn open_tier, fn pin_resident_complement, fn loan_slots, fn refill_lent, fn settle_refill, fn refill_defer_enabled. +//! Moved out of the parent module by STRA-338: fn open_tier, fn pin_resident_complement, fn loan_slots, fn +//! refill_lent, fn settle_refill, fn refill_defer_enabled. #[allow(unused_imports)] use super::*; @@ -254,9 +255,12 @@ pub(in crate::qwen_forward) fn settle_refill(cache: &mut OriginalExpertCache<'_> cache.sync_queued().map_err(|e| driver_error(&e)) } -/// `LELEKA_REFILL_DEFER=on` (EXPERIMENTAL, off by default): queue the lent-slot refill inside the decode phase's assembly, after -/// its intake uploads and before the graph capture, instead of waiting for it at the end of the prompt phase. Job 902 measured -/// the earlier variant (queued at the end of the prompt phase, waited later) as no gain: the PLE seed upload waited for the same +/// `LELEKA_REFILL_DEFER=on` (EXPERIMENTAL, off by default): queue the lent-slot refill inside the decode phase's +/// assembly, after +/// its intake uploads and before the graph capture, instead of waiting for it at the end of the prompt phase. Job 902 +/// measured +/// the earlier variant (queued at the end of the prompt phase, waited later) as no gain: the PLE seed upload waited +/// for the same /// DMA. The current variant has no GPU result yet (job 904), so it stays opt-in. pub(in crate::qwen_forward) fn refill_defer_enabled() -> bool { crate::settings::process().memory.refill_defer diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie_fn.rs index 09dcd6ed..5ea763da 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie_fn.rs @@ -1,12 +1,17 @@ -//! Moved out of the parent module by STRA-338: fn split_group_pcie, fn pcie_locked_only, fn adapt_tuning, fn adapt_decay, fn choose_swaps, fn choose_swaps_reference .... +//! Moved out of the parent module by STRA-338: fn split_group_pcie, fn pcie_locked_only, fn adapt_tuning, fn +//! adapt_decay, fn choose_swaps, fn choose_swaps_reference .... #[allow(unused_imports)] use super::*; -/// `split_group_tail` with a say in which misses may take the PCIe share: only an expert `pcie_ok` accepts is staged, the share -/// is still `nmiss * pcie_num >> 8` of ALL the misses but capped by the number that are eligible, and it is the last eligible -/// misses in routing order. `|_| true` is the unrestricted split. The pageable file-mapped bank uses it to keep PCIe to experts -/// whose pages are page-locked (`LELEKA_PCIE_LOCKED_ONLY`): a copy out of pageable pages is staged by the driver on the calling +/// `split_group_tail` with a say in which misses may take the PCIe share: only an expert `pcie_ok` accepts is staged, +/// the share +/// is still `nmiss * pcie_num >> 8` of ALL the misses but capped by the number that are eligible, and it is the last +/// eligible +/// misses in routing order. `|_| true` is the unrestricted split. The pageable file-mapped bank uses it to keep PCIe +/// to experts +/// whose pages are page-locked (`LELEKA_PCIE_LOCKED_ONLY`): a copy out of pageable pages is staged by the driver on +/// the calling /// thread, which is the thread that drives the whole window. #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn split_group_pcie( @@ -167,7 +172,8 @@ fn assign_kinds( (kinds, plan, pcie_experts) } -/// `LELEKA_PCIE_LOCKED_ONLY=on|1` (read once): over a pageable file-mapped bank only the experts whose pages `pin_resident` locked may +/// `LELEKA_PCIE_LOCKED_ONLY=on|1` (read once): over a pageable file-mapped bank only the experts whose pages +/// `pin_resident` locked may /// take the PCIe share; every other miss stays with the CPU pool. Off by default (the unrestricted split). pub(in crate::qwen_forward) fn pcie_locked_only() -> bool { crate::settings::process().memory.pcie_locked_only @@ -175,7 +181,8 @@ pub(in crate::qwen_forward) fn pcie_locked_only() -> bool { /// Experiment knobs of the adaptive tier (claude/decode-parity; the defaults are generate.cpp's constants): /// `LELEKA_ADAPT_MIN_COUNT` (2.0: the least routed count a missing expert needs to be swapped in), -/// `LELEKA_ADAPT_MARGIN` (1.5: the count lead over the victim), `LELEKA_ADAPT_DECAY` (0.7: counts decay per adaptation). +/// `LELEKA_ADAPT_MARGIN` (1.5: the count lead over the victim), `LELEKA_ADAPT_DECAY` (0.7: counts decay per +/// adaptation). pub(super) fn adapt_tuning() -> (f32, f32, f32) { static TUNING: std::sync::OnceLock<(f32, f32, f32)> = std::sync::OnceLock::new(); *TUNING.get_or_init(|| { @@ -188,8 +195,10 @@ pub(super) fn adapt_tuning() -> (f32, f32, f32) { }) } -/// `LELEKA_ADAPT_DECAY` must lie in 0..=1 (upstream 4a7e373d): above 1 the usage counts grow without end (inf after a few hundred -/// adaptations) and the swap gains turn NaN, which breaks the swap sort; below 0 the counts flip sign. Anything else (out of range, +/// `LELEKA_ADAPT_DECAY` must lie in 0..=1 (upstream 4a7e373d): above 1 the usage counts grow without end (inf after a +/// few hundred +/// adaptations) and the swap gains turn NaN, which breaks the swap sort; below 0 the counts flip sign. Anything else +/// (out of range, /// not a finite number) falls back to the default, with the line to log. Unset gives the default silently. pub(super) fn adapt_decay(raw: Option<&str>) -> (f32, Option) { let Some(text) = raw else { return (ADAPT_DECAY_DEFAULT, None) }; @@ -274,7 +283,8 @@ fn push_pairs(cand: &[(f32, usize)], vict: &[(f32, usize)], margin: f32, layer: } } -/// The earlier implementation (full sorts), kept to prove the faster one picks exactly the same swaps in the same order. +/// The earlier implementation (full sorts), kept to prove the faster one picks exactly the same swaps in the same +/// order. #[cfg(test)] pub(super) fn choose_swaps_reference( usage: &[f32], diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tail_skip_rank_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tail_skip_rank_fn.rs index 2e157b41..c5c6268c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tail_skip_rank_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tail_skip_rank_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn tail_skip_rank, fn set_tail_skip_arm, fn effective_tail_rank, impl PcieMode, impl ExpertTierConfig, fn split_group .... +//! Moved out of the parent module by STRA-338: fn tail_skip_rank, fn set_tail_skip_arm, fn effective_tail_rank, impl +//! PcieMode, impl ExpertTierConfig, fn split_group .... #[allow(unused_imports)] use super::*; @@ -13,12 +14,14 @@ pub(crate) fn tail_skip_rank() -> u32 { TAIL_SKIP_RANK.store(rank, Ordering::Relaxed); rank } -/// Set the rank of an A/B arm of the replay harness (`adaptive@0+tail7`; 0 or out of range = off); `None` goes back to the environment. +/// Set the rank of an A/B arm of the replay harness (`adaptive@0+tail7`; 0 or out of range = off); `None` goes back to +/// the environment. pub(crate) fn set_tail_skip_arm(rank: Option) { TAIL_SKIP_RANK .store(rank.map_or(TAIL_UNRESOLVED, |r| if (1..TOP_K as u32).contains(&r) { r } else { 0 }), Ordering::Relaxed); } -/// The rank this decode phase uses: `tail_skip_rank()` unless the cache holds at least the configured share of all experts. +/// The rank this decode phase uses: `tail_skip_rank()` unless the cache holds at least the configured share of all +/// experts. pub(crate) fn effective_tail_rank(cache: &OriginalExpertCache<'_>) -> u32 { let rank = tail_skip_rank(); if rank == 0 { @@ -59,7 +62,8 @@ impl PcieMode { } } impl ExpertTierConfig { - /// Free VRAM the reserves leave at the start of a decode phase, worst case (the cache's quota rounding only adds to it): the + /// Free VRAM the reserves leave at the start of a decode phase, worst case (the cache's quota rounding only adds + /// to it): the /// reserves less the verifier assembly. Negative when the verifier cannot fit. pub(crate) fn decode_headroom_mib(&self) -> isize { (self.reserve_mib + self.decode_reserve_mib) as isize - VERIFIER_ASSEMBLY_MIB as isize @@ -250,8 +254,10 @@ pub(in crate::qwen_forward) fn split_group( split_group_tail(ids, k, cap, resident, pcie_num, staging, 0) } -/// `split_group` with the route tail skip: `tail_rank > 0` (1..k) leaves out every missed expert whose best rank over the -/// entries that route it is at least `tail_rank` (expert_source.cpp `STRATA_ROUTE_TAIL_SKIP`); its entries are kind -2: not +/// `split_group` with the route tail skip: `tail_rank > 0` (1..k) leaves out every missed expert whose best rank over +/// the +/// entries that route it is at least `tail_rank` (expert_source.cpp `STRATA_ROUTE_TAIL_SKIP`); its entries are kind +/// -2: not /// in the plan, not staged, not computed. They are taken out of the miss count before the PCIe share is rounded. pub(in crate::qwen_forward) fn split_group_tail( ids: &[i32], diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs index b1375c23..622d8dc1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs @@ -10,7 +10,8 @@ fn adapt_decay_outside_zero_to_one_falls_back_to_the_default_with_a_line() { for (text, want) in [("0", 0.0), ("0.25", 0.25), (" 0.9 ", 0.9), ("1", 1.0), ("1.0", 1.0)] { assert_eq!(adapt_decay(Some(text)), (want, None), "{text}"); } - // above 1 (counts grow without end), below 0 (counts flip sign), not finite, not a number: default plus a line naming the knob + // above 1 (counts grow without end), below 0 (counts flip sign), not finite, not a number: default plus a line + // naming the knob for text in ["1.0001", "2", "1e30", "-0.1", "-1", "inf", "-inf", "NaN", "", "fast"] { let (value, line) = adapt_decay(Some(text)); assert_eq!(value, 0.7, "{text}"); @@ -79,7 +80,8 @@ fn the_selection_based_ranking_picks_the_reference_swaps_in_the_same_order() { } #[test] -#[ignore = "timing probe: cargo test --release -p leleka-engine-qwen35-cuda --lib choose_swaps_timing -- --ignored --nocapture"] +#[ignore = "timing probe: cargo test --release -p leleka-engine-qwen35-cuda --lib choose_swaps_timing \ + -- --ignored --nocapture"] fn choose_swaps_timing() { let mut x = 0x2545f4914f6cdd1du64; let mut next = move || { @@ -194,7 +196,16 @@ fn the_tail_skip_drops_missed_experts_every_token_routes_at_or_below_the_rank() assert_eq!(off.skipped_experts, 0); assert!(off.kinds.iter().all(|&k| k != -2)); let on = split_group_tail(&ids, 10, 20, resident, 0, 16, 7).unwrap(); - // 30: best rank min(7, 9) = 7 -> skipped (entries 7 and 19); 31: rank 8 -> skipped (entry 8); 15: rank 7 -> skipped (entry 17); + assert_tail_skip_at_rank_seven_keeps_the_rest(&on, &off); + // rank 8: only expert 31 (rank 8 in its only row); rank 9: nothing (the rank-9 entries are resident 40 and 30, + // best rank 7) + assert_eq!(split_group_tail(&ids, 10, 20, resident, 0, 16, 8).unwrap().skipped_experts, 1); + assert_eq!(split_group_tail(&ids, 10, 20, resident, 0, 16, 9).unwrap().skipped_experts, 0); +} + +fn assert_tail_skip_at_rank_seven_keeps_the_rest(on: &GroupSplit, off: &GroupSplit) { + // 30: best rank min(7, 9) = 7 -> skipped (entries 7 and 19); 31: rank 8 -> skipped (entry 8); 15: rank 7 -> + // skipped (entry 17); // 12: best rank min(6, 8) = 6 < 7 -> kept in both rows (entries 6 and 18) assert_eq!(on.skipped_experts, 3); assert_eq!( @@ -210,14 +221,12 @@ fn the_tail_skip_drops_missed_experts_every_token_routes_at_or_below_the_rank() } } assert_eq!(on.plan.vram(), off.plan.vram()); - // rank 8: only expert 31 (rank 8 in its only row); rank 9: nothing (the rank-9 entries are resident 40 and 30, best rank 7) - assert_eq!(split_group_tail(&ids, 10, 20, resident, 0, 16, 8).unwrap().skipped_experts, 1); - assert_eq!(split_group_tail(&ids, 10, 20, resident, 0, 16, 9).unwrap().skipped_experts, 0); } #[test] fn the_tail_skip_shrinks_the_miss_count_before_the_pcie_share_is_taken() { - // ten misses, rank 7..9 are three experts: 7 misses remain, pcie_num 141 -> m = 7 * 141 >> 8 = 3 (instead of 5 of ten) + // ten misses, rank 7..9 are three experts: 7 misses remain, pcie_num 141 -> m = 7 * 141 >> 8 = 3 (instead of 5 of + // ten) let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); let none = |_: u32| None; let s = split_group_tail(&ids, 10, 40, none, 141, 16, 7).unwrap(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs index fcb2fdb4..85fa24a0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs @@ -1,10 +1,13 @@ -//! ON by default when the configuration is read from the environment (`LELEKA_ORIGINAL_SERVE_SEED=off` disables; formerly experimental): residency seeded from the prompt's own routing. +//! ON by default when the configuration is read from the environment (`LELEKA_ORIGINAL_SERVE_SEED=off` disables; +//! formerly experimental): residency seeded from the prompt's own routing. //! //! The Original's adaptive tier learns which experts to keep in VRAM from the verified windows, a few rounds at a time //! (`ADAPT_EVERY` rounds, at most `ADAPT_SWAPS` swaps), so a first request decodes on the starting profile's placement //! while the adaptation catches up. The prompt's prefill already knows, per layer, how many of its rows each expert -//! served (the MoE stage reads the route IDs on the host to group the rows by expert, `OriginalMoePromptLayer::counts`). -//! This module adds that signal to the placement: at the end of the prompt phase, after the lent slots are refilled, the +//! served (the MoE stage reads the route IDs on the host to group the rows by expert, +//! `OriginalMoePromptLayer::counts`). +//! This module adds that signal to the placement: at the end of the prompt phase, after the lent slots are refilled, +//! the //! most-routed missing experts of every layer replace the least-routed resident ones (the same ranking as the adaptive //! tier, `choose_swaps`, with the prompt's counts as the usage) in ONE batch of swaps queued on the tier's own copy //! stream. The verifier assembly that follows overlaps the copies; the first round's `apply_pending` lands them. @@ -29,7 +32,8 @@ const EXPERTS: usize = 512; /// What `LELEKA_ORIGINAL_SERVE_SEED=on` allows: every slot may change (the ranking's own gain floor decides). pub(crate) const DEFAULT_SEED_SWAPS: usize = 4096; -/// A suggested cap for `LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS` (EXPERIMENTAL, not a default): the "agent-sized prompts up to a few thousand tokens" of +/// A suggested cap for `LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS` (EXPERIMENTAL, not a default): the "agent-sized prompts +/// up to a few thousand tokens" of /// docs/original-serve.md. Prompts of 45k-247k tokens measured worse than no seed on the ranked upstream profile. #[allow(dead_code)] pub(crate) const SUGGESTED_SEED_MAX_ROWS: usize = 4096; @@ -63,7 +67,8 @@ pub(super) fn plan(counts: &[f32], cache: &OriginalExpertCache<'_>, max_swaps: u choose_swaps(&usage, |layer, expert| cache.resident_slot(layer, expert).is_some(), max_swaps) } -/// Queue `swaps` (any number, one expert per slot, distinct within a layer) on the tier's copy stream and arm the batch; +/// Queue `swaps` (any number, one expert per slot, distinct within a layer) on the tier's copy stream and arm the +/// batch; /// the caller (or the next round's `apply_pending`) lands it. The source spans of a layer's incoming experts are opened /// under one fence (the direct CPU tier's admission when it is on). pub(super) fn queue_swaps<'ctx>( @@ -95,7 +100,8 @@ pub(super) fn queue_swaps<'ctx>( /// Put the tier back on the starting placement `initial` (every slot's owner right after the profile fill, by slot): /// the same expert in the same slot, so a run after a restore cannot differ from a run in a new process by slot order. -/// Swaps are queued in rounds and awaited (blocking); a slot whose target is still held by another slot waits for it, and a +/// Swaps are queued in rounds and awaited (blocking); a slot whose target is still held by another slot waits for it, +/// and a /// cycle is broken through one temporary expert. Returns the swaps made. pub(super) fn restore_placement<'ctx>( binding: &ModelBinding, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs index d4d6566b..93a09bba 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs @@ -134,7 +134,8 @@ pub(crate) struct StackConfig { /// The VRAM expert tier (`--expert-cache`, `--expert-cache-per-layer`, `--expert-profile`, `--pcie-frac`, /// `--adapt-every/--adapt-swaps`). Off by default: every routed expert on the CPU pool. pub(crate) expert_tier: ExpertTierConfig, - /// Smaller prompt loans for smaller chunks (`LELEKA_PREFILL_LOAN_TIERS=1`; off: every chunk borrows the full loan of `capacity`). + /// Smaller prompt loans for smaller chunks (`LELEKA_PREFILL_LOAN_TIERS=1`; off: every chunk borrows the full loan + /// of `capacity`). pub(crate) loan_tiers: bool, /// The time of the request phases, the prefix cache's retention and the seed plan (the system clock by default). pub(crate) clock: AnyClock, @@ -158,7 +159,8 @@ struct StackPoint<'ctx> { draft: OriginalDraftCheckpoint, } -/// A prefix-cache checkpoint of the stack: the session's recurrent state and the draft ring's snapshot at one grid point. +/// A prefix-cache checkpoint of the stack: the session's recurrent state and the draft ring's snapshot at one grid +/// point. struct StackState { session: ParkedSession, draft: OriginalDraftCheckpoint, @@ -182,7 +184,8 @@ pub(crate) struct OriginalServeStack<'a, 'ctx> { full_policy: OriginalMtpFullPolicy, scalar_policy: OriginalMtpScalarPolicy, controller: OriginalSpecController, - /// Window policies other than the live one (`LELEKA_SPEC_ARMS`), parked with their controllers (each keeps its learned + /// Window policies other than the live one (`LELEKA_SPEC_ARMS`), parked with their controllers (each keeps its + /// learned /// state across requests), and the live one's label. The verifier is built for `verifier_max_t`, the widest arm. parked: Vec<(String, OriginalServeSettings, OriginalSpecController)>, arm_label: String, @@ -197,7 +200,8 @@ pub(crate) struct OriginalServeStack<'a, 'ctx> { conversation: Option>>, /// The prefix cache (`StackConfig::prefix`); replaces `conversation` when set. prefix: Option>, - /// The tokens the session holds at the end of a decode that left it settled with the draft ring in step (`TailMode::Reply`). + /// The tokens the session holds at the end of a decode that left it settled with the draft ring in step + /// (`TailMode::Reply`). tail_consumed: Option>, /// Prompt tokens the last request did not read again. reused: usize, @@ -214,8 +218,10 @@ pub(crate) struct OriginalServeStack<'a, 'ctx> { /// that survive requests. expert_cache: Option>, loan: Option, - /// Smaller loans for smaller chunks, ascending by rows (empty unless `LELEKA_PREFILL_LOAN_TIERS=1`: only `loan`): a chunk of at most - /// `rows` rows borrows `slots` slots instead of the full loan, so a request that reads a few hundred tokens refills a few + /// Smaller loans for smaller chunks, ascending by rows (empty unless `LELEKA_PREFILL_LOAN_TIERS=1`: only `loan`): + /// a chunk of at most + /// `rows` rows borrows `slots` slots instead of the full loan, so a request that reads a few hundred tokens + /// refills a few /// hundred slots, not the 1.9 GB of an 8192-row arena. loan_tiers: Vec, residency: ResidencyState, @@ -233,7 +239,8 @@ pub(crate) struct OriginalServeStack<'a, 'ctx> { refill_due: bool, /// Wall-clock milliseconds of the last request's prompt and decode phases (operator measurements). timing: (f64, f64), - /// Milliseconds since the request entered `serve` at which each stage of the time to first token ended (`ttft_marks`). + /// Milliseconds since the request entered `serve` at which each stage of the time to first token ended + /// (`ttft_marks`). marks: TtftMarks, executor: OriginalPromptExecutor<'ctx>, draft: super::session::original_prompt::draft::OriginalDraftSession<'ctx>, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_default_for_ttftmarks.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_default_for_ttftmarks.rs index 8074a828..31d52b3d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_default_for_ttftmarks.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_default_for_ttftmarks.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Default_for_TtftMarks, impl TtftMarks, impl StackConfig, fn prefill_bytes, fn tier_for .... +//! Moved out of the parent module by STRA-338: impl Default_for_TtftMarks, impl TtftMarks, impl StackConfig, fn +//! prefill_bytes, fn tier_for .... #[allow(unused_imports)] use super::*;