STRA-338 size4 s13: wrap comments, split test functions and the open/qsa helpers (decode_phase follows)

This commit is contained in:
Pavlo Ratushnyi
2026-11-07 10:40:18 +01:00
parent 5b77c18213
commit 409b95e664
41 changed files with 598 additions and 379 deletions
@@ -90,8 +90,7 @@ pub(super) fn load_buffers<'a, 'ctx>(
context,
OriginalNativePenaltyHistory::new(binding, context).map_err(at("OriginalNativePenaltyHistory::new"))?
);
let ple_history = context.allocate(PLE_HISTORY_BYTES).map_err(at("ple_history"))?;
let ple_scratch = context.allocate(PLE_SCRATCH_BYTES).map_err(at("ple_scratch"))?;
let (ple_history, ple_scratch) = ple_buffers(context)?;
let pool = staged!(
"CPU expert pool",
context,
@@ -101,6 +100,14 @@ pub(super) fn load_buffers<'a, 'ctx>(
Ok(Buffers { arena, history, ple_history, ple_scratch, pool, empty_session, empty_draft })
}
fn ple_buffers<'ctx>(
context: &'ctx Context<'ctx>,
) -> std::result::Result<(DeviceBuffer<'ctx>, DeviceBuffer<'ctx>), ServeFailure> {
let ple_history = context.allocate(PLE_HISTORY_BYTES).map_err(at("ple_history"))?;
let ple_scratch = context.allocate(PLE_SCRATCH_BYTES).map_err(at("ple_scratch"))?;
Ok((ple_history, ple_scratch))
}
fn empty_checkpoints<'ctx>(
ctx: &OpenCtx<'_, '_, 'ctx>,
core: &mut Core<'ctx>,
@@ -24,8 +24,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
result
}
/// Follow the memory governor between requests: under pressure the prefix cache evicts (and restores its budget when the
/// pressure is over), and the conversation checkpoints are dropped. Cheap: a few atomics when nothing changed.
/// Follow the memory governor between requests: under pressure the prefix cache evicts (and restores its budget
/// when the pressure is over), and the conversation checkpoints are dropped. Cheap: a few atomics when nothing
/// changed.
pub(in super::super) fn apply_memory_directive(&mut self) {
let Some(governor) = leleka_memory::Governor::global() else { return };
let used = self.prefix.as_ref().map_or(0, |p| p.bytes() as u64);
@@ -182,12 +183,14 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
}
}
/// Labels of the window policies of `LELEKA_SPEC_ARMS` in the order given (empty when unset), the live one included.
/// Labels of the window policies of `LELEKA_SPEC_ARMS` in the order given (empty when unset), the live one
/// included.
#[allow(dead_code)]
pub(crate) fn spec_arms(&self) -> Vec<String> {
self.arm_order.clone()
}
/// Make `label` the window policy of the following requests (between requests only). Returns false for an unknown label.
/// Make `label` the window policy of the following requests (between requests only). Returns false for an unknown
/// label.
#[allow(dead_code)]
pub(crate) fn select_spec_arm(&mut self, label: &str) -> bool {
if self.arm_label == label {
@@ -36,9 +36,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
(read, _, _) => read,
}
}
/// A failed or cancelled read still refills at once (generate.cpp `refill`); a good one overlaps the copies with the
/// decode phase's host-side assembly (the prompt-routing seed needs the lent slots refilled first, so it turns the
/// deferral off for its requests).
/// A failed or cancelled read still refills at once (generate.cpp `refill`); a good one overlaps the copies with
/// the decode phase's host-side assembly (the prompt-routing seed needs the lent slots refilled first, so it
/// turns the deferral off for its requests).
fn refill_deferred(&self, read_ok: bool, seeding: bool) -> bool {
read_ok
&& !seeding
@@ -120,9 +120,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
Ok(())
}
/// `LELEKA_SEED_TRACE`: how much of the request's decode routing (the adaptive counts, so for a static arm) the resident
/// set covers: the starting profile's set, the prompt's top experts (what the seed installs, per layer slot counts of the
/// profile) and the best any static set could do (the decode's own top experts).
/// `LELEKA_SEED_TRACE`: how much of the request's decode routing (the adaptive counts, so for a static arm) the
/// resident set covers: the starting profile's set, the prompt's top experts (what the seed installs, per layer
/// slot counts of the profile) and the best any static set could do (the decode's own top experts).
pub(in super::super) fn seed_coverage_trace(&mut self) {
let Some(prompt) = self.seed_counts.take() else { return };
let usage = self.residency.usage();
@@ -306,7 +306,8 @@ fn trace_seed_report(report: &SeedReport) {
);
}
}
/// What the decode's routing hits per layer in the prompt's top experts, the decode's own top experts and the starting set.
/// What the decode's routing hits per layer in the prompt's top experts, the decode's own top experts and the
/// starting set.
fn coverage_by_layer(usage: &[f32], prompt: &[f32], (slots, initial): (&[usize; 48], &[bool])) -> (f64, f64, f64) {
let (mut by_prompt, mut oracle, mut by_initial) = (0f64, 0f64, 0f64);
for layer in 0..48 {
@@ -38,8 +38,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
ran.inspect(|()| super::super::super::prefill_profile::end_chunk(first, count))
}
/// The prefix cache at the end of the prefill: with `TailMode::Prompt` or `Reply` a checkpoint at `n - 1`, where the next turn of
/// the session resumes (its prompt starts with this one). A checkpoint that cannot be taken costs only itself.
/// The prefix cache at the end of the prefill: with `TailMode::Prompt` or `Reply` a checkpoint at `n - 1`, where
/// the next turn of the session resumes (its prompt starts with this one). A checkpoint that cannot be taken
/// costs only itself.
pub(in super::super) fn prefix_after_prefill(&mut self, prompt: &[i32]) {
let Some(mut prefix) = self.prefix.take() else { return };
let _span = profile::span("prefix.after_prefill");
@@ -62,8 +63,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
self.prefix = Some(prefix);
}
/// The end of the decode (`TailMode::Reply`): a checkpoint at the end of the prompt and the committed reply. The session is settled and the
/// draft ring stands at its position (`decode_phase` made sure); the cells past the prompt were produced by the decode.
/// The end of the decode (`TailMode::Reply`): a checkpoint at the end of the prompt and the committed reply. The
/// session is settled and the draft ring stands at its position (`decode_phase` made sure); the cells past the
/// prompt were produced by the decode.
pub(in super::super) fn prefix_after_decode(&mut self, consumed: &[i32]) {
let Some(mut prefix) = self.prefix.take() else { return };
let _span = profile::span("prefix.after_decode");
@@ -116,9 +118,10 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
self.prefix = Some(prefix);
}
/// A cancel between two prompt chunks leaves the session at the last published one: that is still the request's conversation
/// (`ServeConversation::note_cancelled_prefill`). The claim needs the same state a live continuation needs at the next
/// request: nothing lost, the recurrent state settled and the draft ring at the session's position.
/// A cancel between two prompt chunks leaves the session at the last published one: that is still the request's
/// conversation (`ServeConversation::note_cancelled_prefill`). The claim needs the same state a live continuation
/// needs at the next request: nothing lost, the recurrent state settled and the draft ring at the session's
/// position.
pub(in super::super) fn keep_conversation_after_cancelled_prefill(&mut self, request: &ServeRequest) {
let Some(mut conversation) = self.conversation.take() else { return };
if let Ok(position) = ResumeDevice::position(self) {
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl PrefixDevice_for_OriginalServeStack, impl RequestOwners_for_OriginalServeStack.
//! Moved out of the parent module by STRA-338: impl PrefixDevice_for_OriginalServeStack, impl
//! RequestOwners_for_OriginalServeStack.
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl PromptChunk, fn vram_note, fn dbg_el, fn report_kernel_selection, fn operator_note, fn operator_line ....
//! Moved out of the parent module by STRA-338: impl PromptChunk, fn vram_note, fn dbg_el, fn report_kernel_selection,
//! fn operator_note, fn operator_line ....
#[allow(unused_imports)]
use super::*;
@@ -30,6 +30,11 @@ fn a_graph_out_of_memory_names_the_widest_window_worth_recording() {
#[test]
fn the_assembly_is_repeated_with_narrower_windows_until_one_fits() {
assert_narrows_until_one_fits();
assert_fits_at_once();
}
fn assert_narrows_until_one_fits() {
// 8 and 6 do not fit, 5 does
let mut tried = Vec::new();
let mut notes = Vec::new();
@@ -48,6 +53,9 @@ fn the_assembly_is_repeated_with_narrower_windows_until_one_fits() {
assert_eq!((used, outcome), (5, Ok(50)));
assert_eq!(tried, [8, 6, 5]);
assert_eq!(notes, [(8, 6), (6, 5)]);
}
fn assert_fits_at_once() {
// it fits at once: one attempt, nothing noted
let mut calls = 0;
let (used, outcome) = assemble_with_window_fallback::<_, &str>(
@@ -1,10 +1,11 @@
//! The `LELEKA_SPEC_*` variables of the adaptive window policy, read through the settings source (the pure policy lives in
//! `leleka-engine-core::spec::adaptive`; it does not know where its constants come from).
//! The `LELEKA_SPEC_*` variables of the adaptive window policy, read through the settings source (the pure policy
//! lives in `leleka-engine-core::spec::adaptive`; it does not know where its constants come from).
use leleka_engine_core::spec::adaptive::AdaptiveConfig;
/// `LELEKA_SPEC_EXPLORE` (period), `_MARGIN`, `_MIN_P_LO`, `_DRAFT_STEP_MS`, `_COST_ALPHA`, `_DECAY`, `_BIAS_RATE`, `_FLOOR_CEILING`; `LELEKA_SPEC_POLICY=legacy`
/// first restores the constants the policy shipped with before the draft-round change (see `AdaptiveConfig::with_policy`).
/// `LELEKA_SPEC_EXPLORE` (period), `_MARGIN`, `_MIN_P_LO`, `_DRAFT_STEP_MS`, `_COST_ALPHA`, `_DECAY`, `_BIAS_RATE`,
/// `_FLOOR_CEILING`; `LELEKA_SPEC_POLICY=legacy` first restores the constants the policy shipped with before the
/// draft-round change (see `AdaptiveConfig::with_policy`).
pub(crate) fn from_environment(mut config: AdaptiveConfig, env: &impl crate::settings::EnvSource) -> AdaptiveConfig {
config = config.with_policy(env.get("LELEKA_SPEC_POLICY").as_deref());
override_with(env, "LELEKA_SPEC_FLOOR_CEILING", &mut config.min_p_hi);
@@ -40,8 +40,9 @@ pub(crate) trait OriginalSpecEngine: OriginalDraftEngine<Self::Verified> {
/// Real verified-prefix replay/publication; no position-only truncation.
fn commit_verified(&mut self, verified: &mut Self::Verified, input_rows: usize) -> Result<()>;
fn drain_verified(&mut self, verified: Self::Verified) -> Result<()>;
/// Take back the physical effects of a window that was drained without a commit (and whose checkpoints were restored), so that
/// `verify` accepts the same position again. Nothing outstanding is not an error. Only the NaN guard's retry calls it.
/// Take back the physical effects of a window that was drained without a commit (and whose checkpoints were
/// restored), so that `verify` accepts the same position again. Nothing outstanding is not an error. Only the NaN
/// guard's retry calls it.
fn discard_window(&mut self) -> Result<()>;
/// Starts host adaptive work beside commit/draft at actual completed-round
/// cadence. Return a real pending owner even for an empty/no-work round.
@@ -51,11 +52,12 @@ pub(crate) trait OriginalSpecEngine: OriginalDraftEngine<Self::Verified> {
fn wait_commit(&mut self) -> Result<()>;
}
/// Upstream's NaN guard with self-healing (`STRATA_NAN_GUARD`, f332a855 / 894f133b): how many times a verify window whose logits or stage
/// outputs are not finite (`Error::NonFinite`) is run again from its round's checkpoint before the request fails. Upstream ends the request
/// and lets its gateway send it again from token 0; here the window itself is repeated, which costs one window and keeps the request.
/// `LELEKA_ORIGINAL_SERVE_NAN_GUARD=on|off` (a profile `engine_env` key), `..._NAN_GUARD_RETRIES=N` (default 2),
/// `..._NAN_INJECT=n[xK]` (debug: the n-th checked window reads as non-finite K times, default 1, to exercise the path).
/// Upstream's NaN guard with self-healing (`STRATA_NAN_GUARD`, f332a855 / 894f133b): how many times a verify window
/// whose logits or stage outputs are not finite (`Error::NonFinite`) is run again from its round's checkpoint before
/// the request fails. Upstream ends the request and lets its gateway send it again from token 0; here the window
/// itself is repeated, which costs one window and keeps the request. `LELEKA_ORIGINAL_SERVE_NAN_GUARD=on|off` (a
/// profile `engine_env` key), `..._NAN_GUARD_RETRIES=N` (default 2), `..._NAN_INJECT=n[xK]` (debug: the n-th checked
/// window reads as non-finite K times, default 1, to exercise the path).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct NanGuard {
pub(crate) retries: u32,
@@ -86,7 +88,8 @@ struct Request {
drafts: DraftBatch,
pending_draft: bool,
finished: bool,
/// The part of `consumed` the draft stage already range-checked (`consumed` only grows within a request; see `token_memo`).
/// The part of `consumed` the draft stage already range-checked (`consumed` only grows within a request; see
/// `token_memo`).
vetted: PrefixMemo,
}
pub(crate) struct OriginalSpecController {
@@ -97,13 +100,15 @@ pub(crate) struct OriginalSpecController {
rounds: u64,
failed: bool,
owner: Rc<()>,
/// Draft the window after the LAST round too (generate.cpp skips it on EOS/length), so the draft ring stands at the session's
/// position when the request ends and a checkpoint of both can be taken there. Off unless the caller asks, per request.
/// Draft the window after the LAST round too (generate.cpp skips it on EOS/length), so the draft ring stands at
/// the session's position when the request ends and a checkpoint of both can be taken there. Off unless the
/// caller asks, per request.
final_draft: bool,
adaptive: Option<AdaptivePolicy>,
plan: Option<DraftPlan>,
stats: SpecStats,
/// The last draft stage ran a chain shortened by the context's end: the next stage restores the full chain in the engine's plan.
/// The last draft stage ran a chain shortened by the context's end: the next stage restores the full chain in the
/// engine's plan.
chain_clamped: bool,
/// Verify windows checked by the NaN guard so far (the injection counts them).
windows_checked: u64,
@@ -264,9 +264,9 @@ impl OriginalSpecController {
Some(self.abort(engine, round.target, round.draft, e.into()))
}
/// The window ran on the device and nothing was committed: restoring the checkpoints puts the lineage back, taking the
/// window back lets the verifier stage the same rows again (a completed, uncommitted window refuses the next one).
/// `None`: restarted; `Some`: the state is unknown and the round ends.
/// The window ran on the device and nothing was committed: restoring the checkpoints puts the lineage back,
/// taking the window back lets the verifier stage the same rows again (a completed, uncommitted window refuses
/// the next one). `None`: restarted; `Some`: the state is unknown and the round ends.
fn retry_window<E: OriginalSpecEngine>(
&mut self,
engine: &mut E,
@@ -33,8 +33,8 @@ struct Fake {
fail_n: u32,
/// every restore of the target fails (the checkpoint cannot be reached)
fail_restore_target: bool,
/// a window completed and nothing was committed for it yet: like the driver's `window_ready`, it refuses the next window until
/// the commit or `discard_window` takes it back (the live stack answered `InvalidDimension`)
/// a window completed and nothing was committed for it yet: like the driver's `window_ready`, it refuses the next
/// window until the commit or `discard_window` takes it back (the live stack answered `InvalidDimension`)
open: bool,
}
impl Fake {
@@ -220,8 +220,8 @@ fn begin(c: &mut OriginalSpecController, p: &[i32], max_new: usize, eos: &[i32])
c.begin_request(p, max_new, 0.0, eos).unwrap();
}
/// Upstream 41cf05a0 `e85567b6`: the window and the MTP chain near the context's end must stay inside `max_context` cells
/// (before: the whole request died with "ran out of context", or the draft wrote cells that do not exist).
/// Upstream 41cf05a0 `e85567b6`: the window and the MTP chain near the context's end must stay inside `max_context`
/// cells (before: the whole request died with "ran out of context", or the draft wrote cells that do not exist).
fn run_to_the_end(
max_context: i64,
prompt_len: usize,
@@ -247,8 +247,9 @@ fn run_to_the_end(
(e, out, c)
}
/// Upstream 41cf05a0 `f332a855` / `894f133b` (STRATA_NAN_GUARD, #879): a window whose output is not finite is not emitted; upstream ends the
/// request and its gateway repeats it. Here the window itself is run again from its round's checkpoint.
/// Upstream 41cf05a0 `f332a855` / `894f133b` (STRATA_NAN_GUARD, #879): a window whose output is not finite is not
/// emitted; upstream ends the request and its gateway repeats it. Here the window itself is run again from its
/// round's checkpoint.
fn guarded(guard: NanGuard, max_new: usize) -> (Fake, OriginalSpecController, Vec<i32>) {
let p = prompt(6);
let e = Fake::new(&p[..5]);
@@ -1,4 +1,7 @@
//! Tests of tests by topic (moved out of the test file by STRA-338): adaptation_join_failure_is_reported_even_after_a_good_draft, finish_round_refuses_a_receipt_from_another_controller, a_request_cannot_restart_while_a_draft_is_pending, policy_and_adaptive_cadence_survive_across_requests ....
//! Tests of tests by topic (moved out of the test file by STRA-338):
//! adaptation_join_failure_is_reported_even_after_a_good_draft,
//! finish_round_refuses_a_receipt_from_another_controller, a_request_cannot_restart_while_a_draft_is_pending,
//! policy_and_adaptive_cadence_survive_across_requests ....
#[allow(unused_imports)]
use super::*;
@@ -67,9 +70,8 @@ fn policy_and_adaptive_cadence_survive_across_requests() {
assert_eq!(e2.committed.len(), 4 + 1 + 4 + 4, "windows of 1, 4, 4 input rows for max_new=6");
}
#[test]
fn suffix_lookup_takes_a_longer_window_when_it_agrees_with_the_first_draft() {
// the fake model's orbit is a cycle: the suffix index proposes the continuation the MTP also drafts
/// The fake model's orbit is a cycle: repeated, it makes the prompt of the suffix index.
fn cyclic_prompt() -> Vec<i32> {
let mut x = 11;
let mut seq = vec![x];
let mut seen = std::collections::HashMap::new();
@@ -86,7 +88,13 @@ fn suffix_lookup_takes_a_longer_window_when_it_agrees_with_the_first_draft() {
while seq.len() < 1200 {
seq.extend_from_slice(&cycle);
}
let prompt = seq;
seq
}
#[test]
fn suffix_lookup_takes_a_longer_window_when_it_agrees_with_the_first_draft() {
// the fake model's orbit is a cycle: the suffix index proposes the continuation the MTP also drafts
let prompt = cyclic_prompt();
let mut e = Fake::new(&prompt[..prompt.len() - 1]);
let mut c = OriginalSpecController::new(config(8, 2, 3)).unwrap();
begin(&mut c, &prompt, 40, &[]);
@@ -100,6 +108,78 @@ fn suffix_lookup_takes_a_longer_window_when_it_agrees_with_the_first_draft() {
assert!(windows.iter().skip(1).any(|&(t, lookup)| lookup && t > 2), "{windows:?}");
}
/// The prompt and its greedy continuation every shape of the output-invariance test is compared with.
struct Greedy {
p: Vec<i32>,
full: Vec<i32>,
}
/// One cell of the output-invariance matrix.
#[derive(Clone, Copy)]
struct Shape {
max_t: usize,
mtp: usize,
suffix: usize,
bad: Option<usize>,
pr: [f32; 8],
min_p: f32,
max_new: usize,
eos_at: Option<usize>,
}
fn check_shape(g: &Greedy, shape: Shape) {
let Shape { max_t, mtp, suffix, bad, pr, min_p, max_new, eos_at } = shape;
let eos: Vec<i32> = eos_at.map(|i| g.full[i]).into_iter().collect();
let mut e = Fake::new(&g.p[..g.p.len() - 1]);
e.bad_draft = bad;
e.probs = pr.to_vec();
let mut c = OriginalSpecController::new(SpecConfig::new(max_t, mtp, 4096, VOCAB, suffix, false).unwrap()).unwrap();
c.begin_request(&g.p, max_new, min_p, &eos).unwrap();
let out = drive(&mut c, &mut e, &mut || false).unwrap();
c.finish_request(&mut e).unwrap();
let mut want = g.full[..max_new].to_vec();
if let Some(i) = eos_at {
if i < max_new {
want.truncate(i + 1);
}
}
let ctx = format!(
"max_t {max_t} mtp {mtp} suffix {suffix} bad {bad:?} probs {:?} min_p {min_p} max_new {max_new} \
eos {eos_at:?}",
&pr[..3]
);
assert_greedy_run(&mut c, &e, (out, want), &ctx);
}
fn assert_greedy_run(c: &mut OriginalSpecController, e: &Fake, (out, want): (Vec<i32>, Vec<i32>), ctx: &str) {
assert_eq!(out, want, "{ctx}");
assert_eq!(c.consumed().unwrap(), e.committed.as_slice(), "{ctx}");
assert_eq!(e.count("begin_adaptation"), e.count("join_adaptation"), "{ctx}");
assert_eq!(e.count("drain_verified"), e.count("verify"), "{ctx}");
assert_eq!(e.count("drain_draft"), e.count("seed"), "{ctx}");
assert_eq!(e.count("restore_target") + e.count("restore_draft"), 0, "{ctx}");
}
fn check_stop_rules(g: &Greedy, base: Shape) {
for min_p in [0.0f32, 0.5] {
for max_new in [0usize, 1, 3, 17] {
for eos_at in [None, Some(2usize), Some(9)] {
check_shape(g, Shape { min_p, max_new, eos_at, ..base });
}
}
}
}
fn check_noise(g: &Greedy, base: Shape) {
let noisy = [None, Some(0), Some(1), Some(2), Some(5)];
let probs: [[f32; 8]; 3] = [[0.9; 8], [0.9, 0.1, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9], [0.02; 8]];
for bad in noisy {
for pr in probs {
check_stop_rules(g, Shape { bad, pr, ..base });
}
}
}
#[test]
fn output_is_the_greedy_text_for_every_window_shape_noise_and_stop_rule() {
// Output invariance: whatever the window sizes, the draft noise, the confidence floor, the suffix
@@ -107,81 +187,47 @@ fn output_is_the_greedy_text_for_every_window_shape_noise_and_stop_rule() {
// max_new) and the session ends up holding exactly the consumed tokens.
let p = prompt(40);
let full = expected(&p, 64);
let noisy = [None, Some(0), Some(1), Some(2), Some(5)];
let probs: [[f32; 8]; 3] = [[0.9; 8], [0.9, 0.1, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9], [0.02; 8]];
let g = Greedy { p, full };
let base = Shape { max_t: 0, mtp: 0, suffix: 0, bad: None, pr: [0.9; 8], min_p: 0.0, max_new: 0, eos_at: None };
for max_t in 1..=8usize {
for mtp in [0usize, 1, 2, max_t, 9] {
for suffix in [0usize, 3] {
for bad in noisy {
for pr in probs {
for min_p in [0.0f32, 0.5] {
for max_new in [0usize, 1, 3, 17] {
for eos_at in [None, Some(2usize), Some(9)] {
let eos: Vec<i32> = eos_at.map(|i| full[i]).into_iter().collect();
let mut e = Fake::new(&p[..p.len() - 1]);
e.bad_draft = bad;
e.probs = pr.to_vec();
let mut c = OriginalSpecController::new(
SpecConfig::new(max_t, mtp, 4096, VOCAB, suffix, false).unwrap(),
)
.unwrap();
c.begin_request(&p, max_new, min_p, &eos).unwrap();
let out = drive(&mut c, &mut e, &mut || false).unwrap();
c.finish_request(&mut e).unwrap();
let mut want = full[..max_new].to_vec();
if let Some(i) = eos_at {
if i < max_new {
want.truncate(i + 1);
}
}
let ctx = format!(
"max_t {max_t} mtp {mtp} suffix {suffix} bad {bad:?} probs {:?} min_p {min_p} max_new {max_new} eos {eos_at:?}",
&pr[..3]
);
assert_eq!(out, want, "{ctx}");
assert_eq!(c.consumed().unwrap(), e.committed.as_slice(), "{ctx}");
assert_eq!(e.count("begin_adaptation"), e.count("join_adaptation"), "{ctx}");
assert_eq!(e.count("drain_verified"), e.count("verify"), "{ctx}");
assert_eq!(e.count("drain_draft"), e.count("seed"), "{ctx}");
assert_eq!(e.count("restore_target") + e.count("restore_draft"), 0, "{ctx}");
}
}
}
}
}
check_noise(&g, Shape { max_t, mtp, suffix, ..base });
}
}
}
}
struct First {
log: Vec<&'static str>,
fail: bool,
}
impl OriginalFirstDraftEngine<u8> for First {
fn replay_first_seed_kv(&mut self, _: &u8, t: usize, cell: i64, token: i32) -> Result<()> {
self.log.push("replay");
assert_eq!((t, cell, token), (4, 9, 5));
Ok(())
}
fn full_first_seed(&mut self, _: &u8, _cell: i64, token: i32, _c: bool) -> Result<DraftPick> {
self.log.push("seed");
if self.fail {
return Err(Error::CudaExecution);
}
Ok(DraftPick { token: next(token), probability: 0.9 })
}
fn first_chain_step(&mut self, _cell: i64, _j: usize, prev: i32, _c: bool) -> Result<DraftPick> {
self.log.push("chain");
Ok(DraftPick { token: next(prev), probability: 0.9 })
}
fn drain_first_seed(&mut self) -> Result<()> {
self.log.push("drain");
Ok(())
}
}
#[test]
fn draft_first_entry_is_a_separate_literal_path_and_drains() {
struct First {
log: Vec<&'static str>,
fail: bool,
}
impl OriginalFirstDraftEngine<u8> for First {
fn replay_first_seed_kv(&mut self, _: &u8, t: usize, cell: i64, token: i32) -> Result<()> {
self.log.push("replay");
assert_eq!((t, cell, token), (4, 9, 5));
Ok(())
}
fn full_first_seed(&mut self, _: &u8, _cell: i64, token: i32, _c: bool) -> Result<DraftPick> {
self.log.push("seed");
if self.fail {
return Err(Error::CudaExecution);
}
Ok(DraftPick { token: next(token), probability: 0.9 })
}
fn first_chain_step(&mut self, _cell: i64, _j: usize, prev: i32, _c: bool) -> Result<DraftPick> {
self.log.push("chain");
Ok(DraftPick { token: next(prev), probability: 0.9 })
}
fn drain_first_seed(&mut self) -> Result<()> {
self.log.push("drain");
Ok(())
}
}
let prep = DraftPreparation::new(4, 3, VOCAB).unwrap();
let mut f = First { log: Vec::new(), fail: false };
let b = prep.from_committed_seed(&mut f, &0u8, 9, 5, 0.0, false).unwrap();
@@ -1,4 +1,7 @@
//! Tests of tests by topic (moved out of the test file by STRA-338): config_rejects_out_of_range_and_mtp_zero_means_max_t, host_budget_is_checked_and_grows_with_the_request, begin_request_validates_tokens_and_rejects_a_live_request, the_adaptive_window_emits_the_same_text_as_a_fixed_one_under_any_drafter ....
//! Tests of tests by topic (moved out of the test file by STRA-338):
//! config_rejects_out_of_range_and_mtp_zero_means_max_t, host_budget_is_checked_and_grows_with_the_request,
//! begin_request_validates_tokens_and_rejects_a_live_request,
//! the_adaptive_window_emits_the_same_text_as_a_fixed_one_under_any_drafter ....
#[allow(unused_imports)]
use super::*;
@@ -183,7 +186,8 @@ fn a_window_near_the_context_end_takes_only_the_rows_that_fit() {
let mut c = OriginalSpecController::new(cfg).unwrap();
begin(&mut c, &p, 100, &[]);
let out = drive(&mut c, &mut e, &mut || false).unwrap();
// position 3: T=1; position 4: T=4 does not fit (4 + 4 > 6), so the window shrinks to the 2 rows left, not to "length"
// position 3: T=1; position 4: T=4 does not fit (4 + 4 > 6), so the window shrinks to the 2 rows left, not to
// "length"
assert!(c.finished());
assert_eq!(e.committed.len(), 6, "every cell of the context is used");
assert_eq!(out, expected(&p, 3), "the tokens of rows 3, 4 and 5 are all emitted");
@@ -216,7 +220,8 @@ fn spec_windows_and_drafts_never_pass_max_context_at_any_distance_from_the_end()
#[test]
fn the_chain_is_shortened_near_the_end_and_restored_after_it() {
// fixed window, perfect drafter: 4-wide windows, 3 drafts. The last round before the end drafts only the cells left.
// fixed window, perfect drafter: 4-wide windows, 3 drafts. The last round before the end drafts only the cells
// left.
let (e, _, _) = run_to_the_end(30, 10, 1000, 4, 4, 0, 0.0, false);
assert!(e.max_end <= 30);
// plans: a clamped chain is asked for explicitly, never longer than the cells left
@@ -245,38 +250,13 @@ fn a_chain_clamped_by_one_request_is_restored_for_the_next() {
assert_eq!(e2.plans.first().map(|x| x.0), Some(3), "{:?}", e2.plans);
}
/// Upstream 41cf05a0 `aece46db`: position 0 was the CLI's "speculation not started" value, so a 1-token prompt on a native pack
/// (its only token is the first verify input, at position 0) never speculated. Here position 0 is a real start.
/// Upstream 41cf05a0 `aece46db`: position 0 was the CLI's "speculation not started" value, so a 1-token prompt on a
/// native pack (its only token is the first verify input, at position 0) never speculated. Here position 0 is a real
/// start.
#[test]
fn a_one_token_prompt_speculates_from_position_zero() {
for (suffix, adaptive) in [(0usize, false), (3, false), (0, true)] {
use super::super::super::original_spec_adaptive::AdaptiveConfig;
let p = prompt(1);
let mut e = Fake::new(&[]);
let mut cfg = config(4, 4, suffix);
if adaptive {
cfg = cfg.with_adaptive(Some(AdaptiveConfig::new(4, 3)));
}
let mut c = OriginalSpecController::new(cfg).unwrap();
begin(&mut c, &p, 40, &[]);
assert_eq!(c.consumed().unwrap().len(), 0);
let mut widths = Vec::new();
while let Some(round) = c.verify_commit(&mut e, &mut || false).unwrap() {
widths.push(round.offered() + 1);
c.finish_round(&mut e, round, || 1.0, &mut || false).unwrap();
}
c.finish_request(&mut e).unwrap();
assert_eq!(widths[0], 1, "the first window has nothing drafted yet");
assert!(
widths[1..].iter().any(|&t| t > 1),
"suffix {suffix} adaptive {adaptive}: no window ever speculated: {widths:?}"
);
assert!(e.count("verify") < 40, "suffix {suffix} adaptive {adaptive}: one window per token: {widths:?}");
assert_eq!(
e.committed.len(),
widths.iter().sum::<usize>(),
"every round committed its accepted rows only: windows {widths:?}"
);
assert_one_token_prompt_speculates(suffix, adaptive);
}
let p = prompt(1);
let mut e = Fake::new(&[]);
@@ -286,6 +266,36 @@ fn a_one_token_prompt_speculates_from_position_zero() {
assert_eq!(out, expected(&p, 40));
}
fn assert_one_token_prompt_speculates(suffix: usize, adaptive: bool) {
use super::super::super::original_spec_adaptive::AdaptiveConfig;
let p = prompt(1);
let mut e = Fake::new(&[]);
let mut cfg = config(4, 4, suffix);
if adaptive {
cfg = cfg.with_adaptive(Some(AdaptiveConfig::new(4, 3)));
}
let mut c = OriginalSpecController::new(cfg).unwrap();
begin(&mut c, &p, 40, &[]);
assert_eq!(c.consumed().unwrap().len(), 0);
let mut widths = Vec::new();
while let Some(round) = c.verify_commit(&mut e, &mut || false).unwrap() {
widths.push(round.offered() + 1);
c.finish_round(&mut e, round, || 1.0, &mut || false).unwrap();
}
c.finish_request(&mut e).unwrap();
assert_eq!(widths[0], 1, "the first window has nothing drafted yet");
assert!(
widths[1..].iter().any(|&t| t > 1),
"suffix {suffix} adaptive {adaptive}: no window ever speculated: {widths:?}"
);
assert!(e.count("verify") < 40, "suffix {suffix} adaptive {adaptive}: one window per token: {widths:?}");
assert_eq!(
e.committed.len(),
widths.iter().sum::<usize>(),
"every round committed its accepted rows only: windows {widths:?}"
);
}
#[test]
fn the_guard_reads_its_three_switches_and_refuses_a_malformed_one() {
assert_eq!(
@@ -1,10 +1,11 @@
//! Round-by-round transcripts of the speculative controller driven through the fake device (STRA-338 S2).
//!
//! Each scenario runs whole requests against `Fake` and compares the operations the controller issued, the draft plans it asked
//! for and the tokens it emitted with a golden file in `golden/`. The goldens were recorded on the code before the engine
//! extraction (S19..S22) and give those steps a GPU-free identity check: a refactor that changes the order, the number or the
//! arguments of the port calls fails here before it reaches the 5090.
//! Re-record after an intended change with `LELEKA_UPDATE_GOLDEN=1 cargo test -p leleka-engine-qwen35-cuda --lib golden` and review the diff.
//! Each scenario runs whole requests against `Fake` and compares the operations the controller issued, the draft
//! plans it asked for and the tokens it emitted with a golden file in `golden/`. The goldens were recorded on the
//! code before the engine extraction (S19..S22) and give those steps a GPU-free identity check: a refactor that
//! changes the order, the number or the arguments of the port calls fails here before it reaches the 5090.
//! Re-record after an intended change with `LELEKA_UPDATE_GOLDEN=1 cargo test -p leleka-engine-qwen35-cuda --lib
//! golden` and review the diff.
use super::super::super::original_spec_adaptive::AdaptiveConfig;
use super::*;
@@ -1,4 +1,7 @@
//! Tests of tests by topic (moved out of the test file by STRA-338): a_non_finite_window_is_run_again_from_its_checkpoint_and_the_request_completes, the_guard_costs_nothing_when_nothing_is_wrong, a_window_that_stays_non_finite_fails_the_request_after_the_retries, only_a_non_finite_failure_is_retried_and_a_guard_that_is_off_retries_nothing ....
//! Tests of tests by topic (moved out of the test file by STRA-338):
//! a_non_finite_window_is_run_again_from_its_checkpoint_and_the_request_completes,
//! the_guard_costs_nothing_when_nothing_is_wrong, a_window_that_stays_non_finite_fails_the_request_after_the_retries,
//! only_a_non_finite_failure_is_retried_and_a_guard_that_is_off_retries_nothing ....
#[allow(unused_imports)]
use super::*;
@@ -96,6 +99,12 @@ fn a_checkpoint_that_cannot_be_restored_ends_the_healing_with_the_original_error
#[test]
fn the_injection_exercises_the_same_path_on_a_good_window_and_counts_windows_across_requests() {
assert_injected_window_heals_once();
assert_injection_retries_are_bounded();
assert_windows_are_counted_across_requests();
}
fn assert_injected_window_heals_once() {
// the 3rd checked window fails once: healed, text unchanged
let (mut e, mut c, p) = guarded(NanGuard::with_retries(2).with_injection(3, 1), 20);
c.begin_request(&p, 20, 0.0, &[]).unwrap();
@@ -106,6 +115,9 @@ fn the_injection_exercises_the_same_path_on_a_good_window_and_counts_windows_acr
assert_eq!(e.count("discard_window"), 1, "the injected window was taken back once");
// the window that was injected was a real, good one: it was drained before the retry
assert_eq!(e.count("drain_verified"), e.count("verify"));
}
fn assert_injection_retries_are_bounded() {
// two failures in a row on one window, two retries: healed after two restarts
let (mut e, mut c, p) = guarded(NanGuard::with_retries(2).with_injection(2, 2), 20);
c.begin_request(&p, 20, 0.0, &[]).unwrap();
@@ -115,6 +127,9 @@ fn the_injection_exercises_the_same_path_on_a_good_window_and_counts_windows_acr
let (mut e, mut c, p) = guarded(NanGuard::with_retries(2).with_injection(2, 3), 20);
c.begin_request(&p, 20, 0.0, &[]).unwrap();
assert_eq!(drive(&mut c, &mut e, &mut || false).err(), Some(SpecError::Forward(Error::NonFinite)));
}
fn assert_windows_are_counted_across_requests() {
// windows are counted across the requests of one controller
let (mut e, mut c, p) = guarded(NanGuard::with_retries(2).with_injection(4, 1), 6);
c.begin_request(&p, 6, 0.0, &[]).unwrap();
@@ -130,7 +145,8 @@ fn the_injection_exercises_the_same_path_on_a_good_window_and_counts_windows_acr
#[test]
fn the_retry_takes_the_refused_window_back_before_it_stages_the_rows_again() {
// the live stack's first failure: a completed window that nothing was committed for refuses the next one (InvalidDimension)
// the live stack's first failure: a completed window that nothing was committed for refuses the next one
// (InvalidDimension)
let (mut e, mut c, p) = guarded(NanGuard::with_retries(2).with_injection(1, 1), 20);
c.begin_request(&p, 20, 0.0, &[]).unwrap();
let _first = c.verify_commit(&mut e, &mut || false).unwrap().unwrap();
@@ -1,13 +1,16 @@
//! Moved out of the parent module by STRA-338: fn trace_enabled, fn stats_enabled, impl From_for_SpecError, impl NanGuard, impl SpecConfig, impl CommittedRound.
//! Moved out of the parent module by STRA-338: fn trace_enabled, fn stats_enabled, impl From_for_SpecError, impl
//! NanGuard, impl SpecConfig, impl CommittedRound.
#[allow(unused_imports)]
use super::*;
/// `LELEKA_SPEC_TRACE`: one `DBG spec-trace` line per timed round (width, source, accepted, round ms, the policy's expectation).
/// `LELEKA_SPEC_TRACE`: one `DBG spec-trace` line per timed round (width, source, accepted, round ms, the policy's
/// expectation).
pub(crate) fn trace_enabled() -> bool {
crate::settings::process().decode.spec_trace
}
/// `LELEKA_SPEC_STATS`: one `DBG spec-stats` line per request (rounds, tokens per round, T and accepted histograms, ms per T).
/// `LELEKA_SPEC_STATS`: one `DBG spec-stats` line per request (rounds, tokens per round, T and accepted histograms,
/// ms per T).
pub(crate) fn stats_enabled() -> bool {
crate::settings::process().decode.spec_stats
}
@@ -61,7 +64,8 @@ impl NanGuard {
times.parse::<u32>().ok().filter(|&n| n > 0).ok_or_else(bad)?,
))
}
/// From the three values; a malformed one is refused with its name (a guard that silently differs from what the operator wrote is worse than none).
/// From the three values; a malformed one is refused with its name (a guard that silently differs from what the
/// operator wrote is worse than none).
pub(crate) fn parse(
switch: Option<&str>,
retries: Option<&str>,
@@ -48,9 +48,9 @@ impl<'context, 'driver> OutputStage<'context, 'driver> {
Ok(())
}
/// Upload the activation, project it through the Q6_K head into a candidate logit buffer and hand that to `consume`.
/// Both short-lived buffers are explicitly accounted for before the result is published; any teardown failure is a
/// refusal, and the first error stays primary.
/// Upload the activation, project it through the Q6_K head into a candidate logit buffer and hand that to
/// `consume`. Both short-lived buffers are explicitly accounted for before the result is published; any teardown
/// failure is a refusal, and the first error stays primary.
fn with_projected(
&self,
context: &Context<'_>,
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl OutputStage, fn greedy, fn selected_token, fn validate_weight_owner, fn encode_activation, fn decode_logits ....
//! Moved out of the parent module by STRA-338: impl OutputStage, fn greedy, fn selected_token, fn
//! validate_weight_owner, fn encode_activation, fn decode_logits ....
#[allow(unused_imports)]
use super::*;
@@ -15,8 +15,8 @@ pub(in crate::qwen_forward) struct OriginalNativePenaltyHistory<'ctx> {
device: Option<DeviceBuffer<'ctx>>,
staging: Box<[u8]>,
failed: bool,
/// The part of the controller's `consumed` already range-checked (it only grows within a request): each window checks the tokens
/// appended since, not the whole history again (`token_memo`).
/// The part of the controller's `consumed` already range-checked (it only grows within a request): each window
/// checks the tokens appended since, not the whole history again (`token_memo`).
tail_checked: PrefixMemo,
}
impl<'ctx> OriginalNativePenaltyHistory<'ctx> {
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl Role, impl Transport, impl Drop_for_Transport, fn at, fn compose, fn admit.
//! Moved out of the parent module by STRA-338: impl Role, impl Transport, impl Drop_for_Transport, fn at, fn compose,
//! fn admit.
#[allow(unused_imports)]
use super::*;
@@ -1,11 +1,13 @@
//! Whether a CPU expert group runs the page-touch pass over its mapped experts before the compute (`PrefetchVirtualMemory` on the three
//! matrices of each expert, then a touching phase on every worker), or leaves the page-ins to the compute itself.
//! Whether a CPU expert group runs the page-touch pass over its mapped experts before the compute
//! (`PrefetchVirtualMemory` on the three matrices of each expert, then a touching phase on every worker), or leaves
//! the page-ins to the compute itself.
//!
//! Measured on the 3080 laptop (docs/laptop-vs-vanilla.md sections 7 and 8): with a warm page cache the pass is pure overhead (decode at 233k
//! tokens: 8.70 -> 10.58 tok/s without it); with a cold one the pass's parallel page-ins win (the first decode of a fresh engine: 6.85 tok/s
//! with it, 5.22 without). So the choice is made by measurement: the cost per expert of each mode is tracked as a moving average, the faster
//! mode is used, and the other one is tried on every [`PROBE_EVERY`]th group so a change of the cache's state is noticed. The bytes read and the
//! arithmetic are the same in both modes. Pure and model-free: the pool feeds it times, it answers a bool.
//! Measured on the 3080 laptop (docs/laptop-vs-vanilla.md sections 7 and 8): with a warm page cache the pass is pure
//! overhead (decode at 233k tokens: 8.70 -> 10.58 tok/s without it); with a cold one the pass's parallel page-ins win
//! (the first decode of a fresh engine: 6.85 tok/s with it, 5.22 without). So the choice is made by measurement: the
//! cost per expert of each mode is tracked as a moving average, the faster mode is used, and the other one is tried
//! on every [`PROBE_EVERY`]th group so a change of the cache's state is noticed. The bytes read and the arithmetic
//! are the same in both modes. Pure and model-free: the pool feeds it times, it answers a bool.
/// Moving-average weight of a new sample once the first samples are in.
const ALPHA: f64 = 0.05;
@@ -16,7 +18,8 @@ pub(super) const PROBE_EVERY: u64 = 16;
/// The other mode takes over when its average is this much lower (3 %: near-ties keep the current mode).
const MARGIN: f64 = 0.97;
/// `LELEKA_CPU_PREFETCH`: `on` / `off` are hard overrides, anything else (or unset on Windows) is adaptive; elsewhere unset means on.
/// `LELEKA_CPU_PREFETCH`: `on` / `off` are hard overrides, anything else (or unset on Windows) is adaptive; elsewhere
/// unset means on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Mode {
On,
@@ -52,7 +55,8 @@ impl PrefetchPolicy {
Self { mode, cost: [0.0; 2], samples: [0; 2], preferred: PASS, groups: 0 }
}
/// Run the pass for the next group? `forced_skip`: a bring-up file asks for the pass to be skipped (A/B inside one engine).
/// Run the pass for the next group? `forced_skip`: a bring-up file asks for the pass to be skipped (A/B inside
/// one engine).
pub(super) fn decide(&mut self, forced_skip: bool) -> bool {
if forced_skip {
return false;
@@ -74,7 +78,8 @@ impl PrefetchPolicy {
use_mode == PASS
}
/// The group that just ran took `ms_per_expert` (open + compute, over the experts the CPU served) in the mode `used_pass`.
/// The group that just ran took `ms_per_expert` (open + compute, over the experts the CPU served) in the mode
/// `used_pass`.
pub(super) fn record(&mut self, used_pass: bool, ms_per_expert: f64) {
if self.mode != Mode::Adaptive || !ms_per_expert.is_finite() || ms_per_expert <= 0.0 {
return;
@@ -118,7 +123,8 @@ impl PrefetchPolicy {
mod tests {
use super::*;
/// Drive `groups` groups where the pass costs `pass` and a skip costs `skip` ms per expert; returns how many ran the pass.
/// Drive `groups` groups where the pass costs `pass` and a skip costs `skip` ms per expert; returns how many ran
/// the pass.
fn drive(policy: &mut PrefetchPolicy, groups: u64, pass: f64, skip: f64) -> u64 {
let mut ran = 0;
for _ in 0..groups {
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl PromptDeviceRead, fn produce_original_gdn, fn produce_original_qsa, impl PromptDeviceNormedRows, impl PromptDeviceRead.
//! Moved out of the parent module by STRA-338: impl PromptDeviceRead, fn produce_original_gdn, fn
//! produce_original_qsa, impl PromptDeviceNormedRows, impl PromptDeviceRead.
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn produce_original_gdn, fn produce_original_qsa, impl PromptDeviceNormedRows, impl PromptDeviceRead.
//! Moved out of the parent module by STRA-338: fn produce_original_gdn, fn produce_original_qsa, impl
//! PromptDeviceNormedRows, impl PromptDeviceRead.
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl std_ops_Deref, impl PromptDeviceSource, impl PromptDeviceFinal, impl Sources, impl PromptDeviceRows.
//! Moved out of the parent module by STRA-338: impl std_ops_Deref, impl PromptDeviceSource, impl PromptDeviceFinal,
//! impl Sources, impl PromptDeviceRows.
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl std_ops_Deref, impl PromptDeviceSource, impl PromptDeviceFinal, impl Sources.
//! Moved out of the parent module by STRA-338: impl std_ops_Deref, impl PromptDeviceSource, impl PromptDeviceFinal,
//! impl Sources.
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl Role, impl RetainedColumns, impl Drop_for_RetainedColumns, impl RetainedRow, impl ProjectionRow, fn project ....
//! Moved out of the parent module by STRA-338: impl Role, impl RetainedColumns, impl Drop_for_RetainedColumns, impl
//! RetainedRow, impl ProjectionRow, fn project ....
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn decode_selected_cached, fn attend_retained, fn gate_retained, fn upload_retained_bytes, fn upload_retained_f32, fn release_retained ....
//! Moved out of the parent module by STRA-338: fn decode_selected_cached, fn attend_retained, fn gate_retained, fn
//! upload_retained_bytes, fn upload_retained_f32, fn release_retained ....
#[allow(unused_imports)]
use super::*;
@@ -128,6 +128,10 @@ mod tests {
assert_eq!(prior.0.pages[0].k[(4 + 2) * 256], 0x3c02);
assert_eq!(prior.0.pooled.len(), 1);
assert_eq!(*prior.0.pooled[0], [-0.5; 128]);
assert_head_major_cells(&prior);
assert!(!Rc::ptr_eq(&first.0.pages[0], &prior.0.pages[0]));
}
fn assert_head_major_cells(prior: &QsaPrior) {
let (k, v) = prior.gather(&[0, 1, 2, 3]).unwrap();
for cell in 0..4 {
for head in 0..2 {
@@ -136,7 +140,6 @@ mod tests {
assert_eq!(&v[start..start + 2], &0x8000u16.to_le_bytes());
}
}
assert!(!Rc::ptr_eq(&first.0.pages[0], &prior.0.pages[0]));
}
#[test]
fn pending_is_exact_prior_bound_and_failed_append_rolls_back() {
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn dispatch_projection, fn project_input_columns, fn project_input, fn project_input_numeric, fn project_cached_out, fn project_out_numeric ....
//! Moved out of the parent module by STRA-338: fn dispatch_projection, fn project_input_columns, fn project_input, fn
//! project_input_numeric, fn project_cached_out, fn project_out_numeric ....
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn validate_ids, fn validate_half, fn validate_values, fn reserve, fn upload, fn upload_bytes ....
//! Moved out of the parent module by STRA-338: fn validate_ids, fn validate_half, fn validate_values, fn reserve, fn
//! upload, fn upload_bytes ....
#[allow(unused_imports)]
use super::*;
@@ -36,15 +36,12 @@ mod tests {
);
QsaPending::new(prior, identity, &[0; KV * 2], &[0; KV * 2], &index).unwrap().into_prior()
}
#[test]
fn resident_plan_exact_bytes_across_append_reuse_branch_reset() {
let owner = QsaOwner::new();
let empty = QsaPrior::empty(
BindingIdentity::test_identity(),
&owner,
LayerId::new(3, Dimension::new(48).unwrap()).unwrap(),
)
.unwrap();
fn empty_prior(owner: &QsaOwner) -> QsaPrior {
QsaPrior::empty(BindingIdentity::test_identity(), owner, LayerId::new(3, Dimension::new(48).unwrap()).unwrap())
.unwrap()
}
/// Twenty appends: the device image follows the plan exactly; returns the last prior and the bytes moved.
fn replay_appends(empty: &QsaPrior) -> (QsaPrior, usize) {
let mut prior = empty.clone();
let mut bytes = Vec::new();
let mut transferred = 0;
@@ -68,25 +65,25 @@ mod tests {
assert_eq!(update(&next, &next).unwrap(), Update::Reuse);
prior = next;
}
assert_eq!(transferred, 512 + 5 * 1024);
let reset = QsaPrior::empty(
BindingIdentity::test_identity(),
&owner,
LayerId::new(3, Dimension::new(48).unwrap()).unwrap(),
)
.unwrap();
assert_eq!(update(&prior, &pending(&reset, 0)).unwrap(), Update::Reload);
let branch1 = pending(&prior, 20);
let branch2 = pending(&prior, 20);
(prior, transferred)
}
fn assert_reset_branch_and_owner_reload(owner: &QsaOwner, prior: &QsaPrior) {
let reset = empty_prior(owner);
assert_eq!(update(prior, &pending(&reset, 0)).unwrap(), Update::Reload);
let branch1 = pending(prior, 20);
let branch2 = pending(prior, 20);
assert_eq!(update(&branch1, &branch2).unwrap(), Update::Reload);
assert_eq!(update(&prior, &branch1).unwrap(), Update::Reuse);
let other = QsaPrior::empty(
BindingIdentity::test_identity(),
&QsaOwner::new(),
LayerId::new(3, Dimension::new(48).unwrap()).unwrap(),
)
.unwrap();
assert_eq!(update(&prior, &pending(&other, 0)).unwrap(), Update::Reload);
assert_eq!(update(prior, &branch1).unwrap(), Update::Reuse);
let other = empty_prior(&QsaOwner::new());
assert_eq!(update(prior, &pending(&other, 0)).unwrap(), Update::Reload);
}
#[test]
fn resident_plan_exact_bytes_across_append_reuse_branch_reset() {
let owner = QsaOwner::new();
let empty = empty_prior(&owner);
let (prior, transferred) = replay_appends(&empty);
assert_eq!(transferred, 512 + 5 * 1024);
assert_reset_branch_and_owner_reload(&owner, &prior);
}
#[test]
fn resident_capacity_and_tail_guards_at_190k() {
@@ -138,24 +135,23 @@ mod gpu {
use super::*;
use crate::qwen_forward::contract::{Dimension, TokenId};
use leleka_cuda_driver::Driver;
#[test]
#[ignore = "Root-only serial installed-driver QSA transport proof, no model inference"]
fn resident_index_transport_matches_uncached_at_190k_and_reset() {
let driver = Driver::load().unwrap();
let context = driver.device(0).unwrap().create_context(1024 * 1024 * 1024).unwrap();
let binding = BindingIdentity::test_identity();
let failed = Rc::new(Cell::new(false));
struct Rig<'ctx> {
binding: BindingIdentity,
context: &'ctx Context<'ctx>,
failed: Rc<Cell<bool>>,
iq: [f32; 512],
}
fn assert_eager_footprint(rig: &Rig<'_>) {
// the legacy footprint (LELEKA_FOOTPRINT_LEGACY=1) allocates all twelve mirrors at construction
let eager = QsaIndexKeyCache::with_eager(binding.clone(), &context, failed.clone(), true).unwrap();
assert_eq!(context.allocated_bytes(), 402659328);
let eager = QsaIndexKeyCache::with_eager(rig.binding.clone(), rig.context, rig.failed.clone(), true).unwrap();
assert_eq!(rig.context.allocated_bytes(), 402659328);
assert_eq!(eager.allocated_layers(), 12);
eager.close().unwrap();
assert_eq!(context.allocated_bytes(), 0);
// the default holds nothing until a layer is selected
let mut cache = QsaIndexKeyCache::with_eager(binding.clone(), &context, failed.clone(), false).unwrap();
assert_eq!(context.allocated_bytes(), 0);
assert_eq!(cache.allocated_layers(), 0);
let iq = [0.1; 512];
assert_eq!(rig.context.allocated_bytes(), 0);
}
/// Five appends at 190k: every selection equals the uncached one; returns the selected ids.
fn select_appends<'ctx>(rig: &Rig<'ctx>, cache: &mut QsaIndexKeyCache<'ctx>) -> usize {
let (binding, context, iq) = (&rig.binding, rig.context, &rig.iq);
let mut prior = synthetic_late_prior_for(binding.clone(), 190000);
let mut total = 0;
for p in 190000..190005 {
@@ -168,36 +164,68 @@ mod gpu {
prior.layer(),
);
let next = QsaPending::new(&prior, identity, &[0; KV * 2], &[0; KV * 2], &index).unwrap().into_prior();
let expected = select(&context, &next.score_keys().unwrap(), &next.0.dead, &iq, p as u32).unwrap();
let actual = cache.select(&binding, &context, &next, &iq, p as u32).unwrap();
let expected = select(context, &next.score_keys().unwrap(), &next.0.dead, iq, p as u32).unwrap();
let actual = cache.select(binding, context, &next, iq, p as u32).unwrap();
assert_eq!(actual.as_ref(), expected.as_ref());
total += actual.len();
prior = next;
}
total
}
/// A reset prior misses and repeats hit; returns the replacement prior and the uploads so far.
fn reset_then_repeat<'ctx>(rig: &Rig<'ctx>, cache: &mut QsaIndexKeyCache<'ctx>) -> (QsaPrior, usize) {
let (binding, context, iq) = (&rig.binding, rig.context, &rig.iq);
let replacement = synthetic_late_prior_for(binding.clone(), 190004);
let expected = select(context, &replacement.score_keys().unwrap(), &replacement.0.dead, iq, 190003).unwrap();
let actual = cache.select(binding, context, &replacement, iq, 190003).unwrap();
assert_eq!(actual.as_ref(), expected.as_ref());
let uploads = cache.uploads;
assert_eq!(cache.select(binding, context, &replacement, iq, 190003).unwrap().as_ref(), expected.as_ref());
assert_eq!(cache.uploads, uploads);
(replacement, uploads)
}
fn assert_guarded_refusals<'ctx>(
rig: &Rig<'ctx>,
cache: &mut QsaIndexKeyCache<'ctx>,
replacement: &QsaPrior,
uploads: usize,
) {
let (binding, context, iq) = (&rig.binding, rig.context, &rig.iq);
let wrong = BindingIdentity::test_identity();
// Bound position and malformed source must refuse before any transfer.
assert!(cache.select(&wrong, context, replacement, iq, 190002).is_err());
let mut bad = *iq;
bad[511] = f32::NAN;
assert!(cache.select(binding, context, replacement, &bad, 190003).is_err());
assert_eq!(cache.uploads, uploads);
}
#[test]
#[ignore = "Root-only serial installed-driver QSA transport proof, no model inference"]
fn resident_index_transport_matches_uncached_at_190k_and_reset() {
let driver = Driver::load().unwrap();
let context = driver.device(0).unwrap().create_context(1024 * 1024 * 1024).unwrap();
let binding = BindingIdentity::test_identity();
let failed = Rc::new(Cell::new(false));
let rig = Rig { binding, context: &context, failed, iq: [0.1; 512] };
assert_eager_footprint(&rig);
// the default holds nothing until a layer is selected
let mut cache = QsaIndexKeyCache::with_eager(rig.binding.clone(), &context, rig.failed.clone(), false).unwrap();
assert_eq!(context.allocated_bytes(), 0);
assert_eq!(cache.allocated_layers(), 0);
let total = select_appends(&rig, &mut cache);
assert_eq!(cache.uploads, (47500 + 1) * ROW_BYTES + 1024);
// layer 3 is mirror slot 0: only that one exists
assert_eq!(cache.allocated_layers(), 1);
assert_eq!(context.allocated_bytes(), 402659328 / 12);
let replacement = synthetic_late_prior_for(binding.clone(), 190004);
let expected = select(&context, &replacement.score_keys().unwrap(), &replacement.0.dead, &iq, 190003).unwrap();
let actual = cache.select(&binding, &context, &replacement, &iq, 190003).unwrap();
assert_eq!(actual.as_ref(), expected.as_ref());
let uploads = cache.uploads;
assert_eq!(cache.select(&binding, &context, &replacement, &iq, 190003).unwrap().as_ref(), expected.as_ref());
assert_eq!(cache.uploads, uploads);
let wrong = BindingIdentity::test_identity();
// Bound position and malformed source must refuse before any transfer.
assert!(cache.select(&wrong, &context, &replacement, &iq, 190002).is_err());
let mut bad = iq;
bad[511] = f32::NAN;
assert!(cache.select(&binding, &context, &replacement, &bad, 190003).is_err());
assert_eq!(cache.uploads, uploads);
assert!(!failed.get());
let (replacement, uploads) = reset_then_repeat(&rig, &mut cache);
assert_guarded_refusals(&rig, &mut cache, &replacement, uploads);
assert!(!rig.failed.get());
cache.close().unwrap();
assert_eq!(context.allocated_bytes(), 0);
context.close().unwrap();
eprintln!(
"qsa-resident synthetic-190k exact-selected-ids={} reset-miss=true repeat-hit=true guarded-refusals=2 allocated=0 model-inference=false",
"qsa-resident synthetic-190k exact-selected-ids={} reset-miss=true repeat-hit=true \
guarded-refusals=2 allocated=0 model-inference=false",
total
);
}
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn max_rows, fn update, fn capacity, fn upload_words, fn delta, impl QsaIndexKeyCache.
//! Moved out of the parent module by STRA-338: fn max_rows, fn update, fn capacity, fn upload_words, fn delta, impl
//! QsaIndexKeyCache.
#[allow(unused_imports)]
use super::*;
@@ -72,9 +73,10 @@ impl<'ctx> QsaIndexKeyCache<'ctx> {
pub(super) fn layer_bytes() -> Result<usize> {
max_rows().checked_mul(ROW_BYTES).ok_or(Error::Overflow)
}
/// The mirror serves the legacy host-canonical QSA path (`qsa_index.rs`, `QsaPrior`); the serve path keeps its keys in the resident index
/// (`OriginalQsaResidentIndex`) and never calls `select`, so the twelve 32 MiB buffers (384 MiB, 408 MiB for the driver) are allocated
/// by the first `select` of a layer instead of at construction. `LELEKA_FOOTPRINT_LEGACY=1` allocates all twelve here, as before.
/// The mirror serves the legacy host-canonical QSA path (`qsa_index.rs`, `QsaPrior`); the serve path keeps its
/// keys in the resident index (`OriginalQsaResidentIndex`) and never calls `select`, so the twelve 32 MiB buffers
/// (384 MiB, 408 MiB for the driver) are allocated by the first `select` of a layer instead of at construction.
/// `LELEKA_FOOTPRINT_LEGACY=1` allocates all twelve here, as before.
pub(in crate::qwen_forward) fn new(
binding: BindingIdentity,
context: &'ctx Context<'ctx>,
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn concat_mixed, fn check_batches, fn check_shapes, fn retained_matrices, fn split_rows, fn row_values ....
//! Moved out of the parent module by STRA-338: fn concat_mixed, fn check_batches, fn check_shapes, fn
//! retained_matrices, fn split_rows, fn row_values ....
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn native_error, fn native, impl NativeProjectionRow, fn project, fn chunk_owners, fn check_batch ....
//! Moved out of the parent module by STRA-338: fn native_error, fn native, impl NativeProjectionRow, fn project, fn
//! chunk_owners, fn check_batch ....
#[allow(unused_imports)]
use super::*;
@@ -79,7 +79,8 @@ impl<'ctx> ResidentQsaLayer<'ctx> {
Ok(())
}
#[allow(clippy::too_many_arguments)]
/// Start the layer's KV prefix copy on a side stream before `prepare` runs (LELEKA_PREFILL_QSA_PREFETCH; a no-op with the switch off).
/// Start the layer's KV prefix copy on a side stream before `prepare` runs (LELEKA_PREFILL_QSA_PREFETCH; a no-op
/// with the switch off).
pub(in crate::qwen_forward) fn begin_prefix(
&mut self,
ws: &mut NativeBatchWorkspace<'ctx>,
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl ResidentQsaLayer (2), impl ResidentQsaPublication, impl ResidentQsaSeal, impl ResidentQsaSelection, impl ResidentQsaRow.
//! Moved out of the parent module by STRA-338: impl ResidentQsaLayer (2), impl ResidentQsaPublication, impl
//! ResidentQsaSeal, impl ResidentQsaSelection, impl ResidentQsaRow.
#[allow(unused_imports)]
use super::impl_residentqsalayer::rehome;
@@ -299,79 +299,5 @@ impl Drop for QsaSelectedCache<'_> {
}
#[cfg(test)]
mod tests {
use super::*;
use crate::qwen_forward::contract::{Dimension, TokenId};
fn append(prior: &QsaPrior, word: u16) -> Result<QsaPrior> {
let identity = TokenLayer::new(
TokenId::new(7, Dimension::new(248320)?)?,
Position::new(prior.next_position(), crate::qwen_forward::contract::position_dimension())?,
prior.layer(),
);
let mut index = [0.0; 640];
index[384..512].fill(0.25);
index[512..].fill(-0.5);
QsaPending::new(prior, identity, &word.to_le_bytes().repeat(KV), &0x8000u16.to_le_bytes().repeat(KV), &index)
.map(QsaPending::into_prior)
}
// Pure planning fixture; it never claims a device upload or invents a ModelBinding.
// Real immutable QsaPending pages supply all cell lineage and halfword payloads.
#[test]
fn selected_cell_plan_preserves_page_lineage_tail_checkpoint_reset_and_order() {
let binding = BindingIdentity::test_identity();
let owner = QsaOwner::new();
let layer = LayerId::new(3, Dimension::new(48).unwrap()).unwrap();
let empty = QsaPrior::empty(binding.clone(), &owner, layer).unwrap();
let mut four = empty.clone();
for offset in 0..4 {
four = append(&four, 0x3c00 + offset).unwrap();
}
let empty_directory = LayerDirectory::empty().unwrap();
let first = plan(&empty_directory, &four, &[0, 1, 2, 3]).unwrap();
let (original_k, original_v) = four.gather(&[0, 1, 2, 3]).unwrap();
assert_eq!(first.k.as_slice(), original_k.as_ref());
assert_eq!(first.v.as_slice(), original_v.as_ref());
assert_eq!(first.misses, [0, 1, 2, 3]);
let reuse = plan(&first.next, &four, &[0, 1, 2, 3]).unwrap();
assert!(reuse.misses.is_empty() && reuse.k.is_empty() && reuse.v.is_empty());
assert_eq!(reuse.selected, first.selected);
let five = append(&four, 0x3c04).unwrap();
let added = plan(&reuse.next, &five, &[0, 1, 2, 3, 4]).unwrap();
assert_eq!(added.misses.len(), 1);
assert_eq!(&added.selected[..4], first.selected.as_slice());
let six = append(&five, 0x3c05).unwrap();
let replaced_tail = plan(&added.next, &six, &[0, 1, 2, 3, 4, 5]).unwrap();
assert_eq!(replaced_tail.misses.len(), 2);
assert_eq!(&replaced_tail.selected[..4], first.selected.as_slice());
// A live checkpoint can reuse its exact old immutable tail, never a newer tail.
let checkpoint = plan(&replaced_tail.next, &five, &[0, 1, 2, 3, 4]).unwrap();
assert!(checkpoint.misses.is_empty());
assert_eq!(checkpoint.selected, added.selected);
let reset = QsaPrior::empty(binding, &QsaOwner::new(), layer).unwrap();
let reset = append(&reset, 0x3c00).unwrap();
let reset_plan = plan(&checkpoint.next, &reset, &[0]).unwrap();
assert_eq!(reset_plan.misses.len(), 1);
assert!(matches!(plan(&checkpoint.next, &five, &[0, 1, 3, 2, 4]), Err(Error::InvalidPosition)));
assert!(matches!(plan(&checkpoint.next, &five, &[0, 1, 2, 3, 5]), Err(Error::InvalidPosition)));
assert!(matches!(append(&five, 0x7c00), Err(Error::NonFinite)));
assert!(plan(&checkpoint.next, &five, &[0, 1, 2, 3, 4]).unwrap().misses.is_empty());
// Weak entries retain neither reset pages nor speculative branch host payloads.
let retired = Rc::downgrade(&six.0.pages[1]);
drop(six);
assert!(retired.upgrade().is_none());
assert!(
replaced_tail
.next
.cells
.iter()
.flatten()
.filter(|cell| cell.offset <= 1)
.any(|cell| cell.page.upgrade().is_none())
);
}
}
#[path = "qsa_selected_cache/tests.rs"]
mod tests;
@@ -0,0 +1,101 @@
//! Unit tests of the selected-cell cache (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
use crate::qwen_forward::contract::{Dimension, TokenId};
fn append(prior: &QsaPrior, word: u16) -> Result<QsaPrior> {
let identity = TokenLayer::new(
TokenId::new(7, Dimension::new(248320)?)?,
Position::new(prior.next_position(), crate::qwen_forward::contract::position_dimension())?,
prior.layer(),
);
let mut index = [0.0; 640];
index[384..512].fill(0.25);
index[512..].fill(-0.5);
QsaPending::new(prior, identity, &word.to_le_bytes().repeat(KV), &0x8000u16.to_le_bytes().repeat(KV), &index)
.map(QsaPending::into_prior)
}
// Pure planning fixture; it never claims a device upload or invents a ModelBinding.
// Real immutable QsaPending pages supply all cell lineage and halfword payloads.
#[test]
fn selected_cell_plan_preserves_page_lineage_tail_checkpoint_reset_and_order() {
let binding = BindingIdentity::test_identity();
let owner = QsaOwner::new();
let layer = LayerId::new(3, Dimension::new(48).unwrap()).unwrap();
let empty = QsaPrior::empty(binding.clone(), &owner, layer).unwrap();
let mut four = empty.clone();
for offset in 0..4 {
four = append(&four, 0x3c00 + offset).unwrap();
}
let (first, reuse) = assert_four_cell_plans(&four);
let grown = grow_past_the_tail(&four, &first, &reuse);
assert_reset_and_refusals(binding, layer, &grown);
assert_weak_entries_retire(grown);
}
/// The prior with five and six cells, and the plans that followed it.
struct Grown {
five: QsaPrior,
six: QsaPrior,
replaced_tail: Plan,
checkpoint: Plan,
}
fn assert_four_cell_plans(four: &QsaPrior) -> (Plan, Plan) {
let empty_directory = LayerDirectory::empty().unwrap();
let first = plan(&empty_directory, four, &[0, 1, 2, 3]).unwrap();
let (original_k, original_v) = four.gather(&[0, 1, 2, 3]).unwrap();
assert_eq!(first.k.as_slice(), original_k.as_ref());
assert_eq!(first.v.as_slice(), original_v.as_ref());
assert_eq!(first.misses, [0, 1, 2, 3]);
let reuse = plan(&first.next, four, &[0, 1, 2, 3]).unwrap();
assert!(reuse.misses.is_empty() && reuse.k.is_empty() && reuse.v.is_empty());
assert_eq!(reuse.selected, first.selected);
(first, reuse)
}
fn grow_past_the_tail(four: &QsaPrior, first: &Plan, reuse: &Plan) -> Grown {
let five = append(four, 0x3c04).unwrap();
let added = plan(&reuse.next, &five, &[0, 1, 2, 3, 4]).unwrap();
assert_eq!(added.misses.len(), 1);
assert_eq!(&added.selected[..4], first.selected.as_slice());
let six = append(&five, 0x3c05).unwrap();
let replaced_tail = plan(&added.next, &six, &[0, 1, 2, 3, 4, 5]).unwrap();
assert_eq!(replaced_tail.misses.len(), 2);
assert_eq!(&replaced_tail.selected[..4], first.selected.as_slice());
// A live checkpoint can reuse its exact old immutable tail, never a newer tail.
let checkpoint = plan(&replaced_tail.next, &five, &[0, 1, 2, 3, 4]).unwrap();
assert!(checkpoint.misses.is_empty());
assert_eq!(checkpoint.selected, added.selected);
Grown { five, six, replaced_tail, checkpoint }
}
fn assert_reset_and_refusals(binding: BindingIdentity, layer: LayerId, grown: &Grown) {
let (five, checkpoint) = (&grown.five, &grown.checkpoint);
let reset = QsaPrior::empty(binding, &QsaOwner::new(), layer).unwrap();
let reset = append(&reset, 0x3c00).unwrap();
let reset_plan = plan(&checkpoint.next, &reset, &[0]).unwrap();
assert_eq!(reset_plan.misses.len(), 1);
assert!(matches!(plan(&checkpoint.next, five, &[0, 1, 3, 2, 4]), Err(Error::InvalidPosition)));
assert!(matches!(plan(&checkpoint.next, five, &[0, 1, 2, 3, 5]), Err(Error::InvalidPosition)));
assert!(matches!(append(five, 0x7c00), Err(Error::NonFinite)));
assert!(plan(&checkpoint.next, five, &[0, 1, 2, 3, 4]).unwrap().misses.is_empty());
}
fn assert_weak_entries_retire(grown: Grown) {
let Grown { six, replaced_tail, .. } = grown;
// Weak entries retain neither reset pages nor speculative branch host payloads.
let retired = Rc::downgrade(&six.0.pages[1]);
drop(six);
assert!(retired.upgrade().is_none());
assert!(
replaced_tail
.next
.cells
.iter()
.flatten()
.filter(|cell| cell.offset <= 1)
.any(|cell| cell.page.upgrade().is_none())
);
}
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl Report, fn valid_product, fn float_bytes, fn close_all, fn finish, fn original_project ....
//! Moved out of the parent module by STRA-338: impl Report, fn valid_product, fn float_bytes, fn close_all, fn
//! finish, fn original_project ....
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,8 @@
//! Tests of tests by topic (moved out of the test file by STRA-338): gdn_session_commit_advances_all_state_once_and_failed_reset_preserves_owner, full_forward_guard_refuses_skipped_layers_missing_logits_and_wrong_callback_token, context_seam_missing_owner_refuses_after_identity_checks, context_seam_wrong_thread_refuses_before_backend_access ....
//! Tests of tests by topic (moved out of the test file by STRA-338):
//! gdn_session_commit_advances_all_state_once_and_failed_reset_preserves_owner,
//! full_forward_guard_refuses_skipped_layers_missing_logits_and_wrong_callback_token,
//! context_seam_missing_owner_refuses_after_identity_checks, context_seam_wrong_thread_refuses_before_backend_access
//! ....
#[allow(unused_imports)]
use super::*;
@@ -34,6 +38,25 @@ fn gdn_session_commit_advances_all_state_once_and_failed_reset_preserves_owner()
assert_eq!(committed.validate(&binding, &session.gdn_owner, layer, position(1)), Err(Error::IdentityMismatch));
}
fn assert_guard_refuses(
binding: &BindingIdentity,
(completed, proved_output): (u32, Option<TokenId>),
expected: Error,
) {
let mut session = QwenSession::test_session(binding.clone());
session.layer_count = 1;
assert_eq!(
session.transact(token(3), position(0), binding, |txn| {
txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?;
txn.completed_layers = completed;
txn.forward_output = proved_output;
Ok(token(4))
}),
Err(expected)
);
assert_eq!((session.next_position, session.predecessors), (0, [-1, -1]));
}
#[test]
fn full_forward_guard_refuses_skipped_layers_missing_logits_and_wrong_callback_token() {
let binding = BindingIdentity::test_identity();
@@ -42,18 +65,7 @@ fn full_forward_guard_refuses_skipped_layers_missing_logits_and_wrong_callback_t
(1, None, Error::Unsupported(Stage::Executor)),
(1, Some(token(5)), Error::IdentityMismatch),
] {
let mut session = QwenSession::test_session(binding.clone());
session.layer_count = 1;
assert_eq!(
session.transact(token(3), position(0), &binding, |txn| {
txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?;
txn.completed_layers = completed;
txn.forward_output = proved_output;
Ok(token(4))
}),
Err(expected)
);
assert_eq!((session.next_position, session.predecessors), (0, [-1, -1]));
assert_guard_refuses(&binding, (completed, proved_output), expected);
}
let mut session = QwenSession::test_session(binding);
session.layer_count = 2;
@@ -1,4 +1,8 @@
//! Tests of tests by topic (moved out of the test file by STRA-338): retained_gr_handoff_identity_is_lazy_and_refuses_same_position_rebegin, headfree_prefill_refuses_metadata_completion_without_actual_final_producer, headfree_prefill_refuses_zero_layer_fixture_and_preserves_history, qsa_session_prior_is_private_and_required_state_cannot_be_skipped ....
//! Tests of tests by topic (moved out of the test file by STRA-338):
//! retained_gr_handoff_identity_is_lazy_and_refuses_same_position_rebegin,
//! headfree_prefill_refuses_metadata_completion_without_actual_final_producer,
//! headfree_prefill_refuses_zero_layer_fixture_and_preserves_history,
//! qsa_session_prior_is_private_and_required_state_cannot_be_skipped ....
#[allow(unused_imports)]
use super::*;
@@ -48,6 +52,17 @@ fn headfree_prefill_refuses_zero_layer_fixture_and_preserves_history() {
assert_eq!((session.next_position, session.predecessors), (0, [-1, -1]));
}
fn assert_qsa_prior_is_private(session: &mut QwenSession, binding: &BindingIdentity, layer: LayerId) {
let mut txn = session.begin(token(3), position(0)).unwrap();
let prior = txn.qsa_prior(layer).unwrap();
assert!(txn.qsa_prior(layer).unwrap().same_state(&prior));
let foreign = QsaIndexPrior::empty(binding.clone(), &QsaOwner::new(), layer).unwrap();
assert_eq!(txn.validate_qsa_prior(&foreign, layer), Err(Error::IdentityMismatch));
assert_eq!(txn.validate_qsa_prior(&prior, layer), Ok(()));
let gdn_layer = LayerId::new(0, Dimension::new(4).unwrap()).unwrap();
assert!(matches!(txn.qsa_prior(gdn_layer), Err(Error::InvalidLayer)));
}
#[test]
fn qsa_session_prior_is_private_and_required_state_cannot_be_skipped() {
let binding = BindingIdentity::test_identity();
@@ -55,16 +70,7 @@ fn qsa_session_prior_is_private_and_required_state_cannot_be_skipped() {
session.layer_count = 4;
session.qsa_layers[3] = true;
let layer = LayerId::new(3, Dimension::new(4).unwrap()).unwrap();
{
let mut txn = session.begin(token(3), position(0)).unwrap();
let prior = txn.qsa_prior(layer).unwrap();
assert!(txn.qsa_prior(layer).unwrap().same_state(&prior));
let foreign = QsaIndexPrior::empty(binding.clone(), &QsaOwner::new(), layer).unwrap();
assert_eq!(txn.validate_qsa_prior(&foreign, layer), Err(Error::IdentityMismatch));
assert_eq!(txn.validate_qsa_prior(&prior, layer), Ok(()));
let gdn_layer = LayerId::new(0, Dimension::new(4).unwrap()).unwrap();
assert!(matches!(txn.qsa_prior(gdn_layer), Err(Error::InvalidLayer)));
}
assert_qsa_prior_is_private(&mut session, &binding, layer);
assert!(session.qsa_states[3].is_none());
assert_eq!((session.next_position, session.predecessors), (0, [-1, -1]));
assert_eq!(
@@ -97,15 +103,9 @@ fn qsa_session_reset_invalidates_old_generation_even_at_position_zero() {
assert_eq!(txn.validate_qsa_prior(&fresh, layer), Ok(()));
}
#[test]
fn ple_session_candidate_is_not_published_on_late_failure_or_missing_history() {
let binding = BindingIdentity::test_identity();
let mut session = QwenSession::test_session(binding.clone());
session.layer_count = 2;
session.ple_required = true;
let layer = LayerId::new(1, Dimension::new(2).unwrap()).unwrap();
fn fail_late_with_staged_ple(session: &mut QwenSession, binding: &BindingIdentity, layer: LayerId) {
let identity = TokenLayer::new(token(3), position(0), layer);
let result = session.transact(token(3), position(0), &binding, |txn| {
let result = session.transact(token(3), position(0), binding, |txn| {
txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?;
let prior = txn.ple_prior()?;
let foreign = PlePrior::zero(binding.clone(), &PleOwner::new())?;
@@ -116,6 +116,16 @@ fn ple_session_candidate_is_not_published_on_late_failure_or_missing_history() {
Err(Error::NonFinite)
});
assert_eq!(result, Err(Error::NonFinite));
}
#[test]
fn ple_session_candidate_is_not_published_on_late_failure_or_missing_history() {
let binding = BindingIdentity::test_identity();
let mut session = QwenSession::test_session(binding.clone());
session.layer_count = 2;
session.ple_required = true;
let layer = LayerId::new(1, Dimension::new(2).unwrap()).unwrap();
fail_late_with_staged_ple(&mut session, &binding, layer);
assert!(session.ple_state.is_none());
assert_eq!((session.next_position, session.predecessors), (0, [-1, -1]));
assert_eq!(
@@ -132,15 +142,9 @@ fn ple_session_candidate_is_not_published_on_late_failure_or_missing_history() {
assert_eq!(session.next_position, 0);
}
#[test]
fn ple_session_commit_and_reset_preserve_exact_owner_and_prior_identity() {
let binding = BindingIdentity::test_identity();
let mut session = QwenSession::test_session(binding.clone());
session.layer_count = 2;
session.ple_required = true;
let layer = LayerId::new(1, Dimension::new(2).unwrap()).unwrap();
fn commit_one_ple_token(session: &mut QwenSession, binding: &BindingIdentity, layer: LayerId) {
session
.transact(token(3), position(0), &binding, |txn| {
.transact(token(3), position(0), binding, |txn| {
txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?;
let prior = txn.ple_prior()?;
txn.stage_ple(&prior, PlePending::test_next(&prior, &TokenLayer::new(token(3), position(0), layer))?)?;
@@ -150,6 +154,16 @@ fn ple_session_commit_and_reset_preserve_exact_owner_and_prior_identity() {
Ok(token(4))
})
.unwrap();
}
#[test]
fn ple_session_commit_and_reset_preserve_exact_owner_and_prior_identity() {
let binding = BindingIdentity::test_identity();
let mut session = QwenSession::test_session(binding.clone());
session.layer_count = 2;
session.ple_required = true;
let layer = LayerId::new(1, Dimension::new(2).unwrap()).unwrap();
commit_one_ple_token(&mut session, &binding, layer);
let committed = session.ple_state.as_ref().unwrap().clone();
assert_eq!((session.next_position, committed.next_position()), (1, 1));
{
@@ -165,15 +179,9 @@ fn ple_session_commit_and_reset_preserve_exact_owner_and_prior_identity() {
assert_eq!(committed.validate(&binding, &session.ple_owner, position(1)), Err(Error::IdentityMismatch));
}
#[test]
fn gdn_session_late_failure_discards_candidates_and_required_state_cannot_be_skipped() {
let binding = BindingIdentity::test_identity();
let mut session = QwenSession::test_session(binding.clone());
session.layer_count = 48;
session.gdn_layers[0] = true;
let layer = LayerId::new(0, Dimension::new(48).unwrap()).unwrap();
fn fail_late_with_staged_gdn(session: &mut QwenSession, binding: &BindingIdentity, layer: LayerId) {
let identity = TokenLayer::new(token(3), position(0), layer);
let result = session.transact(token(3), position(0), &binding, |txn| {
let result = session.transact(token(3), position(0), binding, |txn| {
txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?;
let prior = txn.gdn_prior(layer)?;
let foreign = GdnPrior::zero(binding.clone(), &GdnOwner::new(), layer)?;
@@ -185,6 +193,16 @@ fn gdn_session_late_failure_discards_candidates_and_required_state_cannot_be_ski
Err(Error::NonFinite)
});
assert_eq!(result, Err(Error::NonFinite));
}
#[test]
fn gdn_session_late_failure_discards_candidates_and_required_state_cannot_be_skipped() {
let binding = BindingIdentity::test_identity();
let mut session = QwenSession::test_session(binding.clone());
session.layer_count = 48;
session.gdn_layers[0] = true;
let layer = LayerId::new(0, Dimension::new(48).unwrap()).unwrap();
fail_late_with_staged_gdn(&mut session, &binding, layer);
assert_eq!((session.next_position, session.predecessors), (0, [-1, -1]));
assert!(session.gdn_states[0].is_none());
assert_eq!(