STRA-338 size2 en1: gpu proof test-support functions split into helpers, shared single-load rig

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 22:50:01 +01:00
parent 0fb059869c
commit 2ee93e05ab
15 changed files with 1330 additions and 1097 deletions
@@ -26,8 +26,8 @@ fn finished_one() -> Recorder {
record
}
#[test]
fn measurement_framed_eos_bounds_usage_rewind_and_callback_isolation() {
/// The verifier emits anchor7 plus matched drafts8/9; authoritative EOS13 is an output token.
fn framed_eos_is_an_output_token_not_a_draft() {
// The verifier emits anchor7 plus matched drafts8/9; authoritative EOS13
// is an output token, never an accepted draft or a persistent target ID.
let mut record = Recorder::new(&[4, 5, 4], 4);
@@ -61,7 +61,10 @@ fn measurement_framed_eos_bounds_usage_rewind_and_callback_isolation() {
assert!(window.authoritative_eos);
assert_eq!(measured.cache_before.expert_source_bytes, 13);
assert_eq!(measured.cache_after.expert_source_bytes, 33);
}
/// Every bound of the recorder refuses with `Bounds`.
fn out_of_bounds_recordings_are_refused() {
let oversized = vec![0; 262145];
let mut bounds = vec![Recorder::new(&oversized, 1), Recorder::new(&[4], 4097)];
let mut invalid_retained = finished_one();
@@ -87,7 +90,10 @@ fn measurement_framed_eos_bounds_usage_rewind_and_callback_isolation() {
Some(MeasurementFailure::Bounds)
);
}
}
/// A complete event stream must reconcile usage; failures never become a measurement.
fn usage_must_reconcile_and_incomplete_recordings_fail() {
// A complete event stream must exactly reconcile input/output/retained
// usage; failures never become a successful measurement by default.
for usage in [None, Some((2, 1, 0)), Some((3, 2, 0)), Some((3, 1, 1))] {
@@ -108,6 +114,10 @@ fn measurement_framed_eos_bounds_usage_rewind_and_callback_isolation() {
Some(MeasurementFailure::Incomplete)
);
}
}
/// A rewound cache counter fails; the outcome flags describe, never invent.
fn rewound_counters_fail_and_flags_never_invent_completion() {
for field in 0..8 {
let mut rewound = [10; 8];
rewound[field] = 9;
@@ -121,7 +131,10 @@ fn measurement_framed_eos_bounds_usage_rewind_and_callback_isolation() {
.finish(counts([0; 8]), counts([0; 8]), false, false, false, Some((3, 1, 0)))
.expect("flags describe outcome, never invent completion");
assert!(!unpublished.completed && !unpublished.stopped && !unpublished.terminal_published);
}
/// A refusing or panicking observer cannot unwind or block later delivery.
fn callback_failures_are_isolated() {
let deliveries = Arc::new(AtomicUsize::new(0));
let seen = Arc::clone(&deliveries);
let accepting: EvaluationObserver = Arc::new(move |result| {
@@ -139,3 +152,12 @@ fn measurement_framed_eos_bounds_usage_rewind_and_callback_isolation() {
assert!(notify(&accepting, Err(MeasurementFailure::Incomplete)));
assert_eq!(deliveries.load(Ordering::SeqCst), 2);
}
#[test]
fn measurement_framed_eos_bounds_usage_rewind_and_callback_isolation() {
framed_eos_is_an_output_token_not_a_draft();
out_of_bounds_recordings_are_refused();
usage_must_reconcile_and_incomplete_recordings_fail();
rewound_counters_fail_and_flags_never_invent_completion();
callback_failures_are_isolated();
}
@@ -19,37 +19,39 @@ pub(super) struct ArmSpec {
pub decay: f32,
}
/// One `+`-joined arm spec.
fn parse_arm(label: &str) -> ArmSpec {
let mut arm = ArmSpec { label: label.to_owned(), adapt_every: 0, seed_swaps: 0, keep: 0.0, usage: 0.0, decay: 1.0 };
for token in label.split('+') {
apply_token(&mut arm, label, token);
}
arm
}
/// One `name` or `name=value` token of an arm spec.
fn apply_token(arm: &mut ArmSpec, label: &str, token: &str) {
let (name, value) = token.split_once('=').map_or((token, None), |(n, v)| (n, Some(v)));
let num =
|v: Option<&str>| v.map(|v| v.parse::<f64>().unwrap_or_else(|_| panic!("arm {label}: bad number in {token}")));
match name {
"static" => arm.adapt_every = 0,
"adaptive" => arm.adapt_every = 4,
"every" => arm.adapt_every = num(value).expect("every=N") as u32,
"seed" => {
arm.seed_swaps =
num(value).map_or(crate::qwen_forward::original_serve_seed::DEFAULT_SEED_SWAPS, |n| n as usize)
}
"keep" => arm.keep = num(value).expect("keep=F") as f32,
"usage" => arm.usage = num(value).expect("usage=F") as f32,
"id" => {}
"decay" => arm.decay = num(value).expect("decay=F") as f32,
other => panic!("arm {label}: unknown token {other}"),
}
}
/// `LELEKA_..._ARMS` text: comma-separated arm specs.
pub(super) fn parse_arms(text: &str) -> Vec<ArmSpec> {
text.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(|label| {
let mut arm =
ArmSpec { label: label.to_owned(), adapt_every: 0, seed_swaps: 0, keep: 0.0, usage: 0.0, decay: 1.0 };
for token in label.split('+') {
let (name, value) = token.split_once('=').map_or((token, None), |(n, v)| (n, Some(v)));
let num = |v: Option<&str>| {
v.map(|v| v.parse::<f64>().unwrap_or_else(|_| panic!("arm {label}: bad number in {token}")))
};
match name {
"static" => arm.adapt_every = 0,
"adaptive" => arm.adapt_every = 4,
"every" => arm.adapt_every = num(value).expect("every=N") as u32,
"seed" => {
arm.seed_swaps = num(value)
.map_or(crate::qwen_forward::original_serve_seed::DEFAULT_SEED_SWAPS, |n| n as usize)
}
"keep" => arm.keep = num(value).expect("keep=F") as f32,
"usage" => arm.usage = num(value).expect("usage=F") as f32,
"id" => {}
"decay" => arm.decay = num(value).expect("decay=F") as f32,
other => panic!("arm {label}: unknown token {other}"),
}
}
arm
})
.collect()
text.split(',').map(str::trim).filter(|s| !s.is_empty()).map(parse_arm).collect()
}
/// The arms of prompt number `k`: as listed, reversed on odd prompts.
@@ -76,25 +78,16 @@ fn rate(hit: &[[u64; 3]], rounds: usize, which: usize) -> String {
}
}
/// Apply `arm`, bring the tier to a first-request state, serve `request` and print the `DBG arm` lines.
pub(super) fn serve_arm(
stack: &mut OriginalServeStack<'_, '_>,
arm: &ArmSpec,
request: &ServeRequest,
tag: &str,
max_context_note: &str,
) -> ArmRun {
{
let tier = stack.expert_tier_mut();
tier.adapt_every = arm.adapt_every;
tier.seed_swaps = arm.seed_swaps;
tier.seed_keep = arm.keep;
tier.seed_usage = arm.usage;
tier.seed_decay = arm.decay;
}
let reset_started = std::time::Instant::now();
let restored = stack.reset_expert_tier().unwrap_or_else(|e| panic!("reset_expert_tier failed: {e:?}"));
let reset_ms = reset_started.elapsed().as_secs_f64() * 1e3;
/// What one timed serve of an arm produced.
struct TimedServe {
out: Vec<i32>,
rounds: usize,
ttft: std::time::Duration,
decode_tps: f64,
}
/// Serve `request` collecting the emitted tokens and the time to the first round.
fn timed_serve(stack: &mut OriginalServeStack<'_, '_>, arm: &ArmSpec, request: &ServeRequest, tag: &str) -> TimedServe {
let started = std::time::Instant::now();
let mut first: Option<std::time::Duration> = None;
let mut out = Vec::new();
@@ -115,19 +108,34 @@ pub(super) fn serve_arm(
let ttft = first.unwrap_or(total);
let decode_s = (total - ttft).as_secs_f64();
let decode_tps = if out.len() > 1 && decode_s > 0.0 { (out.len() - 1) as f64 / decode_s } else { 0.0 };
TimedServe { out, rounds: outcome.rounds, ttft, decode_tps }
}
/// The prompt-routing seed of the last request as one token, `none` without a seed.
fn seed_note(stack: &OriginalServeStack<'_, '_>) -> String {
stack.last_seed().map_or("none".to_owned(), |s| {
format!("rows{}:swaps{}:plan{:.1}ms:queue{:.1}ms", s.rows, s.planned, s.plan_ms, s.queue_ms)
})
}
/// The `DBG arm` line of one served arm; `reset` is (swaps restored, reset ms).
fn arm_line(
stack: &OriginalServeStack<'_, '_>,
(arm, tag, max_context_note): (&ArmSpec, &str, &str),
run: &TimedServe,
(restored, reset_ms): (usize, f64),
) -> String {
let (prompt_ms, decode_ms) = stack.last_timing();
let marks = stack.round_marks();
let seed = stack.last_seed().map_or("none".to_owned(), |s| {
format!("rows{}:swaps{}:plan{:.1}ms:queue{:.1}ms", s.rows, s.planned, s.plan_ms, s.queue_ms)
});
let stats = stack.expert_tier_stats();
eprintln!(
"DBG arm {} {tag} {max_context_note} produced={} rounds={} ttft_ms={:.1} prompt_ms={prompt_ms:.1} decode_ms={decode_ms:.1} decode_tok_s={decode_tps:.2} \
vram%@4={} @8={} @16={} @32={} @all={} pcie%@8={} @all={} seed={seed} reset_swaps={restored} reset_ms={reset_ms:.0} adaptations_total={}",
let seed = seed_note(stack);
let (produced, ttft_ms, decode_tps) = (run.out.len(), run.ttft.as_secs_f64() * 1e3, run.decode_tps);
format!(
"DBG arm {} {tag} {max_context_note} produced={produced} rounds={} ttft_ms={ttft_ms:.1} \
prompt_ms={prompt_ms:.1} decode_ms={decode_ms:.1} decode_tok_s={decode_tps:.2} \
vram%@4={} @8={} @16={} @32={} @all={} pcie%@8={} @all={} seed={seed} reset_swaps={restored} \
reset_ms={reset_ms:.0} adaptations_total={}",
arm.label,
out.len(),
outcome.rounds,
ttft.as_secs_f64() * 1e3,
run.rounds,
rate(&marks, 4, 0),
rate(&marks, 8, 0),
rate(&marks, 16, 0),
@@ -135,14 +143,48 @@ pub(super) fn serve_arm(
rate(&marks, marks.len(), 0),
rate(&marks, 8, 1),
rate(&marks, marks.len(), 1),
stats.map_or(0, |s| s.adaptations),
);
stack.expert_tier_stats().map_or(0, |s| s.adaptations),
)
}
/// The `DBG arm` and `DBG arm-output` lines of one served arm.
fn print_arm_lines(
stack: &OriginalServeStack<'_, '_>,
labels: (&ArmSpec, &str, &str),
run: &TimedServe,
reset: (usize, f64),
) {
eprintln!("{}", arm_line(stack, labels, run, reset));
eprintln!(
"DBG arm-output {} {tag}: {}",
arm.label,
out.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(" ")
"DBG arm-output {} {}: {}",
labels.0.label,
labels.1,
run.out.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(" ")
);
ArmRun { tokens: out }
}
/// Apply `arm`, bring the tier to a first-request state, serve `request` and print the `DBG arm` lines.
pub(super) fn serve_arm(
stack: &mut OriginalServeStack<'_, '_>,
arm: &ArmSpec,
request: &ServeRequest,
tag: &str,
max_context_note: &str,
) -> ArmRun {
{
let tier = stack.expert_tier_mut();
tier.adapt_every = arm.adapt_every;
tier.seed_swaps = arm.seed_swaps;
tier.seed_keep = arm.keep;
tier.seed_usage = arm.usage;
tier.seed_decay = arm.decay;
}
let reset_started = std::time::Instant::now();
let restored = stack.reset_expert_tier().unwrap_or_else(|e| panic!("reset_expert_tier failed: {e:?}"));
let reset_ms = reset_started.elapsed().as_secs_f64() * 1e3;
let run = timed_serve(stack, arm, request, tag);
print_arm_lines(stack, (arm, tag, max_context_note), &run, (restored, reset_ms));
ArmRun { tokens: run.out }
}
#[cfg(test)]
@@ -27,7 +27,8 @@
//! original_serve_laptop_bench`.
use super::*;
use crate::qwen_forward::{
original_serve_request::ServeRequest,
original_serve_engine::ServeOutcome,
original_serve_request::{ServeError, ServeRequest},
original_serve_stack::{OriginalServeStack, StackConfig},
};
use std::env;
@@ -64,20 +65,20 @@ fn elapsed(start: std::time::Instant) -> f64 {
start.elapsed().as_secs_f64()
}
#[test]
#[ignore = "one explicitly scheduled real-model load and GPU (laptop profile)"]
fn original_serve_laptop_bench() {
assert!(env::var("LELEKA_LAPTOP_BENCH").is_ok_and(|v| v == "yes"), "explicit laptop bench opt-in required");
let start = std::time::Instant::now();
/// The pinned shards, verified.
fn verify_shards(start: std::time::Instant) -> (VerifiedGgufFile, VerifiedGgufFile) {
let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0)
.expect("pinned shard0 verification failed");
let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1)
.expect("pinned shard1 verification failed");
eprintln!("LAPTOP load: shards verified in {:.1} s; {}", elapsed(start), memory_line());
let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed");
let eos = *artifact.tokenizer().special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent");
(shard0, shard1)
}
/// The inherited KAR archive: a read-only file or the sealed memfd.
fn open_inherited() -> InheritedKarArchive {
let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE");
let inherited = match env::var_os("LELEKA_LAPTOP_KAR_FILE") {
match env::var_os("LELEKA_LAPTOP_KAR_FILE") {
Some(path) => InheritedKarArchive::open_read_only_file(std::path::Path::new(&path), provenance)
.expect("read-only KAR admission failed"),
None => {
@@ -87,7 +88,22 @@ fn original_serve_laptop_bench() {
.expect("invalid descriptor");
InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed")
}
};
}
}
/// The bound model with its expert source loaded; the archive handle stays alive beside it.
struct Loaded {
binding: ModelBinding,
eos: u32,
_inherited: InheritedKarArchive,
}
/// Bind the pinned artifact to the KAR and MTP inputs, then load the expert source of `LELEKA_LAPTOP_EXPERTS`.
fn bind_laptop(start: std::time::Instant) -> Loaded {
let (shard0, shard1) = verify_shards(start);
let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed");
let eos = *artifact.tokenizer().special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent");
let inherited = open_inherited();
let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp(
artifact,
&inherited,
@@ -101,6 +117,11 @@ fn original_serve_laptop_bench() {
elapsed(start),
memory_line()
);
load_experts(&mut binding, start);
Loaded { binding, eos, _inherited: inherited }
}
fn load_experts(binding: &mut ModelBinding, start: std::time::Instant) {
let experts = env::var("LELEKA_LAPTOP_EXPERTS").unwrap_or_else(|_| "mapped".to_owned());
let report = match experts.as_str() {
"mapped" => binding.load_mapped_expert_source().expect("mapped expert source load failed"),
@@ -114,18 +135,35 @@ fn original_serve_laptop_bench() {
elapsed(start),
memory_line()
);
}
// Experimental: a process geometry of N cells instead of the trained 262144 (the Original sizes its KV by
// --max-context). Unscaled RoPE; must precede the first CUDA context user.
/// Experimental: a process geometry of N cells instead of the trained 262144 (the Original sizes its KV by
/// --max-context). Unscaled RoPE; must precede the first CUDA context user.
fn configure_cells() {
if let Ok(cells) = env::var("LELEKA_LAPTOP_CELLS") {
let cells: usize = cells.parse().expect("LELEKA_LAPTOP_CELLS must be a count");
leleka_cuda_driver::configure_serving_context(cells, &Default::default()).expect("serving context refused");
eprintln!("LAPTOP config: process geometry {cells} cells (experimental)");
}
let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 15);
let driver = Driver::load().expect("CUDA driver load failed");
let device = driver.device(0).expect("CUDA device 0 unavailable");
let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable"));
}
/// The cross-session prefix cache of `LELEKA_LAPTOP_PREFIX_MIB` (`auto` or MiB), when set.
fn laptop_prefix() -> Option<crate::qwen_forward::original_serve_stack::PrefixConfig> {
use crate::qwen_forward::original_serve_stack::{PrefixBudget, PrefixConfig};
let v = env::var("LELEKA_LAPTOP_PREFIX_MIB").ok()?;
let budget = match v.as_str() {
"auto" => PrefixBudget::Auto,
other => PrefixBudget::Bytes(other.parse::<u64>().expect("LELEKA_LAPTOP_PREFIX_MIB: auto or MiB") << 20),
};
Some(PrefixConfig {
budget,
block_tokens: number("LELEKA_LAPTOP_PREFIX_BLOCK", 0),
laptop: true,
..PrefixConfig::auto()
})
}
fn laptop_stack_config() -> StackConfig {
let mut config = StackConfig::new(number("LELEKA_LAPTOP_MAX_CONTEXT", 8192) as i64);
config.capacity = number("LELEKA_ORIGINAL_SERVE_CAPACITY", 2048);
config.cpu_workers = number("LELEKA_LAPTOP_CPU_WORKERS", 7) as i32;
@@ -139,158 +177,240 @@ fn original_serve_laptop_bench() {
}
config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment()
.expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting");
if let Ok(v) = env::var("LELEKA_LAPTOP_PREFIX_MIB") {
use crate::qwen_forward::original_serve_stack::{PrefixBudget, PrefixConfig};
let budget = match v.as_str() {
"auto" => PrefixBudget::Auto,
other => PrefixBudget::Bytes(other.parse::<u64>().expect("LELEKA_LAPTOP_PREFIX_MIB: auto or MiB") << 20),
};
config.prefix = Some(PrefixConfig {
budget,
block_tokens: number("LELEKA_LAPTOP_PREFIX_BLOCK", 0),
laptop: true,
..PrefixConfig::auto()
});
if let Some(prefix) = laptop_prefix() {
config.prefix = Some(prefix);
}
config
}
fn read_prompts() -> Vec<Vec<i32>> {
std::fs::read_to_string(required_path("LELEKA_LAPTOP_PROMPT_IDS"))
.expect("prompt id file unreadable")
.lines()
.filter(|l| !l.trim().is_empty())
.map(|l| l.split(',').map(|t| t.trim().parse().expect("token id")).collect())
.collect()
}
/// The parameters every request of the bench shares.
struct Plan {
max_new: usize,
repeat: usize,
/// setup.py's `--spec-min-p 0.5` (the draft-probability floor; greedy output does not depend on it)
spec_min_p: f32,
eos: u32,
}
fn laptop_request(ids: Vec<i32>, plan: &Plan) -> ServeRequest {
ServeRequest::new(
ids,
plan.max_new,
None,
7,
plan.spec_min_p,
crate::qwen_forward::original_serve_request::original_stop_tokens(plan.eos),
)
}
/// `LELEKA_LAPTOP_ARMS` (see backend_original_serve_arms.rs): first-request A/B of the expert tier's policies; every
/// prompt of `LELEKA_LAPTOP_ORDER` (default: file order) once per arm from a first-request tier state, `repeat` times.
fn run_arms(stack: &mut OriginalServeStack<'_, '_>, prompts: &[Vec<i32>], plan: &Plan, arms: &str) {
let arms = super::original_serve_arms::parse_arms(arms);
let order: Vec<usize> = env::var("LELEKA_LAPTOP_ORDER")
.map(|v| v.split(',').map(|t| t.trim().parse().expect("LELEKA_LAPTOP_ORDER: indices")).collect())
.unwrap_or_else(|_| (0..prompts.len()).collect());
for rep in 0..plan.repeat {
for (k, &index) in order.iter().enumerate() {
for arm in super::original_serve_arms::arms_for(&arms, k + rep) {
let request = laptop_request(prompts[index].clone(), plan);
super::original_serve_arms::serve_arm(
stack,
&arm,
&request,
&format!("p{} rep{rep}", index + 1),
&format!("prompt={}", prompts[index].len()),
);
}
}
}
}
/// The serving sequence and the soak limits.
struct Soak {
sequence: Vec<usize>,
soak_s: f64,
skip_failed: bool,
}
fn soak_settings(prompt_count: usize) -> Soak {
let sequence: Vec<usize> = env::var("LELEKA_LAPTOP_SEQUENCE")
.map(|v| v.split(',').map(|t| t.trim().parse().expect("LELEKA_LAPTOP_SEQUENCE: indices")).collect())
.unwrap_or_else(|_| (0..prompt_count).collect());
assert!(sequence.iter().all(|&i| i < prompt_count), "LELEKA_LAPTOP_SEQUENCE index out of range");
let soak_s: f64 =
env::var("LELEKA_LAPTOP_SOAK_S").ok().map(|v| v.parse().expect("LELEKA_LAPTOP_SOAK_S")).unwrap_or(0.0);
let skip_failed = env::var("LELEKA_LAPTOP_SKIP_FAILED").is_ok_and(|v| v == "1");
Soak { sequence, soak_s, skip_failed }
}
/// Progress of the serving passes.
struct SoakRun {
served_from: std::time::Instant,
done_requests: usize,
}
/// The wall times of one request in milliseconds: time to the first round, the whole request, and the stack's
/// own prompt and decode phases.
struct RequestTimes {
ttft: f64,
total: f64,
prompt_ms: f64,
decode_ms: f64,
}
/// The `LAPTOP request` line of one served request.
fn request_line(
(index, pass): (usize, usize),
(prompt_len, out_len, rounds): (usize, usize, usize),
times: &RequestTimes,
run: &SoakRun,
) -> String {
let RequestTimes { ttft, total, prompt_ms, decode_ms } = *times;
let prefill = if prompt_ms > 0.0 { prompt_len as f64 * 1e3 / prompt_ms } else { 0.0 };
let decode = if decode_ms > 0.0 { out_len as f64 * 1e3 / decode_ms } else { 0.0 };
format!(
"LAPTOP request p{} pass={pass} prompt={} produced={} rounds={} \
ttft_ms={ttft:.1} prompt_ms={prompt_ms:.1} \
decode_ms={decode_ms:.1} total_ms={total:.1} prefill_tok_s={prefill:.1} decode_tok_s={decode:.2} t={:.1}; {}",
index + 1,
prompt_len,
out_len,
rounds,
run.served_from.elapsed().as_secs_f64(),
memory_line()
)
}
/// Serve `request`, collecting its tokens and the wall times (the stack's phase times are read after the serve).
fn serve_timed(
stack: &mut OriginalServeStack<'_, '_>,
request: &ServeRequest,
) -> (Result<ServeOutcome, ServeError>, Vec<i32>, RequestTimes) {
let mut out = Vec::new();
let begun = std::time::Instant::now();
let mut first = None;
let served = stack.serve(
request,
&mut |round| {
if first.is_none() {
first = Some(begun.elapsed());
}
out.extend_from_slice(round);
Ok(())
},
&mut || false,
);
let total = begun.elapsed().as_secs_f64() * 1e3;
let ttft = first.map_or(total, |d| d.as_secs_f64() * 1e3);
let (prompt_ms, decode_ms) = stack.last_timing();
(served, out, RequestTimes { ttft, total, prompt_ms, decode_ms })
}
/// Serve prompt `index` of `pass`; false when a failed request ended the soak (`LELEKA_LAPTOP_SKIP_FAILED=1`).
fn serve_index(
stack: &mut OriginalServeStack<'_, '_>,
(index, pass): (usize, usize),
(ids, plan, soak): (&[i32], &Plan, &Soak),
run: &mut SoakRun,
) -> bool {
let request = laptop_request(ids.to_vec(), plan);
let (served, out, times) = serve_timed(stack, &request);
match served {
Ok(outcome) => {
run.done_requests += 1;
eprintln!("{}", request_line((index, pass), (ids.len(), out.len(), outcome.rounds), &times, run));
if let Some(stats) = stack.expert_tier_stats() {
eprintln!("LAPTOP tier p{} pass={pass}: {}", index + 1, stats.describe());
}
if pass == 0 {
let line = out.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(",");
eprintln!("LAPTOP output p{}: {line}", index + 1);
}
true
}
Err(e) if soak.skip_failed => {
let done = run.done_requests;
eprintln!(
"LAPTOP failed p{} pass={pass} after {done} requests: {e:?} health={:?}; {}",
index + 1,
stack.health(),
memory_line()
);
false
}
Err(e) => panic!("request p{} pass {pass} failed: {e:?} health={:?}", index + 1, stack.health()),
}
}
/// Serve the sequence `repeat` times, then keep going until the soak time has passed (at a request boundary).
fn serve_passes(stack: &mut OriginalServeStack<'_, '_>, prompts: &[Vec<i32>], plan: &Plan, soak: &Soak) -> SoakRun {
let mut run = SoakRun { served_from: std::time::Instant::now(), done_requests: 0 };
'passes: for pass in 0.. {
if pass >= plan.repeat && (soak.soak_s <= 0.0 || run.served_from.elapsed().as_secs_f64() >= soak.soak_s) {
break;
}
for &index in &soak.sequence {
if pass >= plan.repeat && run.served_from.elapsed().as_secs_f64() >= soak.soak_s {
break 'passes;
}
if !serve_index(stack, (index, pass), (&prompts[index], plan, soak), &mut run) {
break 'passes;
}
}
}
run
}
/// The context goes after the stack that borrowed it has been closed.
fn close_context(context: Rc<leleka_cuda_driver::Context<'_>>) {
Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed");
}
#[test]
#[ignore = "one explicitly scheduled real-model load and GPU (laptop profile)"]
fn original_serve_laptop_bench() {
assert!(env::var("LELEKA_LAPTOP_BENCH").is_ok_and(|v| v == "yes"), "explicit laptop bench opt-in required");
let start = std::time::Instant::now();
let loaded = bind_laptop(start);
configure_cells();
let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 15);
let driver = Driver::load().expect("CUDA driver load failed");
let device = driver.device(0).expect("CUDA device 0 unavailable");
let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable"));
let config = laptop_stack_config();
eprintln!(
"LAPTOP config: capacity {} cpu_workers {} max_context {} kv_resident {} budget {budget_gib} GiB tier {:?}",
config.capacity, config.cpu_workers, config.max_context, config.kv_resident, config.expert_tier
);
let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) {
let mut stack = match OriginalServeStack::open(&loaded.binding, context.as_ref(), Rc::clone(&context), config) {
Ok(stack) => stack,
Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()),
};
eprintln!("LAPTOP load: stack open at {:.1} s; {}", elapsed(start), memory_line());
let prompts: Vec<Vec<i32>> = std::fs::read_to_string(required_path("LELEKA_LAPTOP_PROMPT_IDS"))
.expect("prompt id file unreadable")
.lines()
.filter(|l| !l.trim().is_empty())
.map(|l| l.split(',').map(|t| t.trim().parse().expect("token id")).collect())
.collect();
let max_new = number("LELEKA_LAPTOP_MAX_NEW", 128);
let repeat = number("LELEKA_LAPTOP_REPEAT", 2).max(1);
// setup.py's `--spec-min-p 0.5` (the draft-probability floor; greedy output does not depend on it)
let prompts = read_prompts();
let (max_new, repeat) = (number("LELEKA_LAPTOP_MAX_NEW", 128), number("LELEKA_LAPTOP_REPEAT", 2).max(1));
let spec_min_p: f32 =
env::var("LELEKA_LAPTOP_SPEC_MIN_P").ok().map(|v| v.parse().expect("LELEKA_LAPTOP_SPEC_MIN_P")).unwrap_or(0.5);
// LELEKA_LAPTOP_ARMS (see backend_original_serve_arms.rs): first-request A/B of the expert tier's policies; every
// prompt of LELEKA_LAPTOP_ORDER (default: file order) once per arm from a first-request tier state, `repeat` times.
let plan = Plan { max_new, repeat, spec_min_p, eos: loaded.eos };
if let Ok(arms) = env::var("LELEKA_LAPTOP_ARMS") {
let arms = super::original_serve_arms::parse_arms(&arms);
let order: Vec<usize> = env::var("LELEKA_LAPTOP_ORDER")
.map(|v| v.split(',').map(|t| t.trim().parse().expect("LELEKA_LAPTOP_ORDER: indices")).collect())
.unwrap_or_else(|_| (0..prompts.len()).collect());
for rep in 0..repeat {
for (k, &index) in order.iter().enumerate() {
for arm in super::original_serve_arms::arms_for(&arms, k + rep) {
let request = ServeRequest::new(
prompts[index].clone(),
max_new,
None,
7,
spec_min_p,
crate::qwen_forward::original_serve_request::original_stop_tokens(eos),
);
super::original_serve_arms::serve_arm(
&mut stack,
&arm,
&request,
&format!("p{} rep{rep}", index + 1),
&format!("prompt={}", prompts[index].len()),
);
}
}
}
run_arms(&mut stack, &prompts, &plan, &arms);
stack.close().expect("stack cleanup failed");
Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed");
return;
return close_context(context);
}
let sequence: Vec<usize> = env::var("LELEKA_LAPTOP_SEQUENCE")
.map(|v| v.split(',').map(|t| t.trim().parse().expect("LELEKA_LAPTOP_SEQUENCE: indices")).collect())
.unwrap_or_else(|_| (0..prompts.len()).collect());
assert!(sequence.iter().all(|&i| i < prompts.len()), "LELEKA_LAPTOP_SEQUENCE index out of range");
let soak_s: f64 =
env::var("LELEKA_LAPTOP_SOAK_S").ok().map(|v| v.parse().expect("LELEKA_LAPTOP_SOAK_S")).unwrap_or(0.0);
let skip_failed = env::var("LELEKA_LAPTOP_SKIP_FAILED").is_ok_and(|v| v == "1");
let served_from = std::time::Instant::now();
let mut done_requests = 0usize;
'passes: for pass in 0.. {
if pass >= repeat && (soak_s <= 0.0 || served_from.elapsed().as_secs_f64() >= soak_s) {
break;
}
for &index in &sequence {
if pass >= repeat && served_from.elapsed().as_secs_f64() >= soak_s {
break 'passes;
}
let ids = &prompts[index];
let request = ServeRequest::new(
ids.clone(),
max_new,
None,
7,
spec_min_p,
crate::qwen_forward::original_serve_request::original_stop_tokens(eos),
);
let mut out = Vec::new();
let begun = std::time::Instant::now();
let mut first = None;
let served = stack.serve(
&request,
&mut |round| {
if first.is_none() {
first = Some(begun.elapsed());
}
out.extend_from_slice(round);
Ok(())
},
&mut || false,
);
let total = begun.elapsed().as_secs_f64() * 1e3;
let ttft = first.map_or(total, |d| d.as_secs_f64() * 1e3);
let (prompt_ms, decode_ms) = stack.last_timing();
match served {
Ok(outcome) => {
done_requests += 1;
let prefill = if prompt_ms > 0.0 { ids.len() as f64 * 1e3 / prompt_ms } else { 0.0 };
let decode = if decode_ms > 0.0 { out.len() as f64 * 1e3 / decode_ms } else { 0.0 };
eprintln!(
"LAPTOP request p{} pass={pass} prompt={} produced={} rounds={} ttft_ms={ttft:.1} prompt_ms={prompt_ms:.1} decode_ms={decode_ms:.1} total_ms={total:.1} prefill_tok_s={prefill:.1} decode_tok_s={decode:.2} t={:.1}; {}",
index + 1,
ids.len(),
out.len(),
outcome.rounds,
served_from.elapsed().as_secs_f64(),
memory_line()
);
if let Some(stats) = stack.expert_tier_stats() {
eprintln!("LAPTOP tier p{} pass={pass}: {}", index + 1, stats.describe());
}
if pass == 0 {
eprintln!(
"LAPTOP output p{}: {}",
index + 1,
out.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(",")
);
}
}
Err(e) if skip_failed => {
eprintln!(
"LAPTOP failed p{} pass={pass} after {done_requests} requests: {e:?} health={:?}; {}",
index + 1,
stack.health(),
memory_line()
);
break 'passes;
}
Err(e) => panic!("request p{} pass {pass} failed: {e:?} health={:?}", index + 1, stack.health()),
}
}
}
eprintln!(
"LAPTOP done: {done_requests} requests in {:.1} s; {}",
served_from.elapsed().as_secs_f64(),
memory_line()
);
let run = serve_passes(&mut stack, &prompts, &plan, &soak_settings(prompts.len()));
let (done, secs) = (run.done_requests, run.served_from.elapsed().as_secs_f64());
eprintln!("LAPTOP done: {done} requests in {secs:.1} s; {}", memory_line());
stack.close().expect("stack cleanup failed");
Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed");
close_context(context);
}
@@ -21,14 +21,12 @@ fn required_path(name: &str) -> PathBuf {
env::var_os(name).map(PathBuf::from).unwrap_or_else(|| panic!("missing operator-owned input {name}"))
}
#[test]
#[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; time-to-first-token sweep"]
fn original_serve_ttft_sweep() {
let _ = dbg_el();
assert!(env::var("LELEKA_ORIGINAL_SERVE_REPLAY").is_ok_and(|v| v == "yes"), "explicit replay opt-in required");
let number = |name: &str, default: usize| -> usize {
env::var(name).ok().map(|v| v.parse().unwrap_or_else(|_| panic!("{name} must be a count"))).unwrap_or(default)
};
fn count_env(name: &str, default: usize) -> usize {
env::var(name).ok().map(|v| v.parse().unwrap_or_else(|_| panic!("{name} must be a count"))).unwrap_or(default)
}
/// The first captured prompt of at least `LELEKA_SWEEP_CONTEXT` tokens.
fn find_base_prompt() -> Vec<i32> {
let dir = required_path("LELEKA_REPLAY_DIR");
let mut files: Vec<PathBuf> = std::fs::read_dir(&dir)
.expect("capture directory unreadable")
@@ -38,7 +36,7 @@ fn original_serve_ttft_sweep() {
})
.collect();
files.sort();
let want = number("LELEKA_SWEEP_CONTEXT", 52_000);
let want = count_env("LELEKA_SWEEP_CONTEXT", 52_000);
let mut base: Option<Vec<i32>> = None;
for file in &files {
let doc: serde_json::Value =
@@ -50,13 +48,17 @@ fn original_serve_ttft_sweep() {
break;
}
}
let base = base.expect("no captured prompt is long enough for the sweep");
let ks: Vec<usize> = env::var("LELEKA_SWEEP_KS")
.map(|v| v.split(',').map(|t| t.trim().parse().expect("LELEKA_SWEEP_KS: counts")).collect())
.unwrap_or_else(|_| vec![1, 16, 64, 128, 256, 340, 512, 1024]);
let max_new = number("LELEKA_SWEEP_MAX_NEW", 4);
let reps = number("LELEKA_SWEEP_REPS", 3);
base.expect("no captured prompt is long enough for the sweep")
}
/// The bound model with its resident expert source; the archive handle stays alive beside it.
struct Loaded {
binding: ModelBinding,
eos: u32,
_inherited: InheritedKarArchive,
}
fn load_sweep_binding() -> Loaded {
let fd: u32 = env::var("LELEKA_STRA169_KAR_FD")
.expect("missing inherited sealed archive descriptor")
.parse()
@@ -77,15 +79,12 @@ fn original_serve_ttft_sweep() {
)
.expect("actual pinned KAR+MTP binding failed");
binding.load_resident_expert_source().expect("resident expert source load failed");
let driver = Driver::load().expect("CUDA driver load failed");
let device = driver.device(0).expect("CUDA device 0 unavailable");
let context = Rc::new(
device
.create_context(number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 24) << 30)
.expect("bounded Context unavailable"),
);
let mut config = StackConfig::new(number("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64);
config.capacity = number("LELEKA_REPLAY_CAPACITY", 2048);
Loaded { binding, eos, _inherited: inherited }
}
fn sweep_stack_config() -> StackConfig {
let mut config = StackConfig::new(count_env("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64);
config.capacity = count_env("LELEKA_REPLAY_CAPACITY", 2048);
config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from);
config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment()
.expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting");
@@ -98,13 +97,71 @@ fn original_serve_ttft_sweep() {
},
..PrefixConfig::auto()
});
config
}
/// Serve the first `n` tokens of `base` and print the `SWEEP` line with every stage timed.
fn sweep_serve(
stack: &mut OriginalServeStack<'_, '_>,
(base, max_new, eos): (&[i32], usize, u32),
(n, label): (usize, &str),
) {
let prompt = base[..n].to_vec();
let started = std::time::Instant::now();
let mut first: Option<f64> = None;
let served = stack.serve(
&ServeRequest::new(prompt, max_new, None, 7, 0.0, vec![eos as i32]),
&mut |_round| {
if first.is_none() {
first = Some(started.elapsed().as_secs_f64() * 1e3);
}
Ok(())
},
&mut || false,
);
match served {
Ok(_) => {
let m = stack.ttft_marks();
let reused = stack.reused_tokens();
eprintln!(
"SWEEP {label} n={n} reused={reused} reprefill={} ttft_ms={:.1} resume_ms={:.1} prefill_ms={:.1} \
assemble_ms={:.1} first_round_ms={:.1}",
n - reused,
first.unwrap_or(f64::NAN),
m[0],
m[1] - m[0],
m[2] - m[1],
m[3] - m[2]
);
}
Err(e) => panic!("SWEEP {label} failed: {e:?} health={:?}", stack.health()),
}
}
#[test]
#[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; time-to-first-token sweep"]
fn original_serve_ttft_sweep() {
let _ = dbg_el();
assert!(env::var("LELEKA_ORIGINAL_SERVE_REPLAY").is_ok_and(|v| v == "yes"), "explicit replay opt-in required");
let base = find_base_prompt();
let ks: Vec<usize> = env::var("LELEKA_SWEEP_KS")
.map(|v| v.split(',').map(|t| t.trim().parse().expect("LELEKA_SWEEP_KS: counts")).collect())
.unwrap_or_else(|_| vec![1, 16, 64, 128, 256, 340, 512, 1024]);
let max_new = count_env("LELEKA_SWEEP_MAX_NEW", 4);
let reps = count_env("LELEKA_SWEEP_REPS", 3);
let loaded = load_sweep_binding();
let driver = Driver::load().expect("CUDA driver load failed");
let device = driver.device(0).expect("CUDA device 0 unavailable");
let budget = count_env("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 24) << 30;
let context = Rc::new(device.create_context(budget).expect("bounded Context unavailable"));
let config = sweep_stack_config();
let capacity = config.capacity;
eprintln!(
"SWEEP config: base prompt {} tokens, capacity {capacity}, ks {ks:?}, reps {reps}, tier {:?}",
base.len(),
config.expert_tier
);
let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) {
let mut stack = match OriginalServeStack::open(&loaded.binding, context.as_ref(), Rc::clone(&context), config) {
Ok(stack) => stack,
Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()),
};
@@ -112,43 +169,13 @@ fn original_serve_ttft_sweep() {
// a node every `capacity` tokens (and every 8192 for the coarse capacity): N is a multiple of both
let node = (base.len().saturating_sub(max_k + 8) / 8192) * 8192;
assert!(node >= 8192 && node + max_k + 2 <= base.len(), "the base prompt is too short");
let serve = |stack: &mut OriginalServeStack<'_, '_>, n: usize, label: &str| {
let prompt = base[..n].to_vec();
let started = std::time::Instant::now();
let mut first: Option<f64> = None;
let served = stack.serve(
&ServeRequest::new(prompt, max_new, None, 7, 0.0, vec![eos as i32]),
&mut |_round| {
if first.is_none() {
first = Some(started.elapsed().as_secs_f64() * 1e3);
}
Ok(())
},
&mut || false,
);
match served {
Ok(_) => {
let m = stack.ttft_marks();
let reused = stack.reused_tokens();
eprintln!(
"SWEEP {label} n={n} reused={reused} reprefill={} ttft_ms={:.1} resume_ms={:.1} prefill_ms={:.1} assemble_ms={:.1} first_round_ms={:.1}",
n - reused,
first.unwrap_or(f64::NAN),
m[0],
m[1] - m[0],
m[2] - m[1],
m[3] - m[2]
);
}
Err(e) => panic!("SWEEP {label} failed: {e:?} health={:?}", stack.health()),
}
};
let shared = (base.as_slice(), max_new, loaded.eos);
// the cold read builds the nodes (the last grid point at or below `node + 100` is `node`)
serve(&mut stack, node + 101, "cold");
serve(&mut stack, node + 101, "warm-same");
sweep_serve(&mut stack, shared, (node + 101, "cold"));
sweep_serve(&mut stack, shared, (node + 101, "warm-same"));
for rep in 0..reps {
for &k in &ks {
serve(&mut stack, node + k + 1, &format!("k={k} rep={rep}"));
sweep_serve(&mut stack, shared, (node + k + 1, &format!("k={k} rep={rep}")));
}
}
eprintln!("SWEEP done: node {node}");
@@ -1,114 +1,64 @@
//! Private sole new changed-path model gate; actual source identity/load preserved.
use super::*;
use std::{
env,
panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
};
const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024;
use std::env;
#[path = "combined_changed_boundary_proof/rig.rs"]
pub(super) mod rig;
use rig::{DEVICE_BUDGET, Owners, bind_pinned, fresh_owner_phase, require_opt_in, unwrap_phase};
fn required_path(name: &str) -> PathBuf {
env::var_os(name).map(PathBuf::from).expect("missing operator-owned MMQ proof path")
}
/// The native-certified activation policy of the resident MMQ proofs.
fn native_resident_mmq<'ctx>(
binding: &ModelBinding,
context: &'ctx leleka_cuda_driver::Context<'ctx>,
) -> crate::qwen_forward::contract::Result<MoeWeightCache<'ctx>> {
let execution = EvaluationExecution::ExperimentalNativeResidentMmq;
match execution {
EvaluationExecution::ExperimentalNativeResidentMmq => MoeWeightCache::new_native_mmq(binding, context),
_ => panic!("native-certified activation policy required"),
}
}
const NATIVE_MOE_REFUSAL: &str = "actual native-certified MoE/MTP device cache unavailable";
// New root-only phase: fresh real target owner; no repeated capture/prefix phases.
#[test]
#[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; no live-owner overlap"]
fn pinned_single_load_layer0_and_window_boundaries() {
assert!(
env::var("LELEKA_STRA169_RUN_COMBINED_BOUNDARIES").is_ok_and(|value| value == "yes"),
"explicit prefix GPU proof opt-in required"
);
let fd: u32 = env::var("LELEKA_STRA169_KAR_FD")
.expect("missing inherited sealed archive descriptor")
.parse()
.expect("invalid inherited sealed archive descriptor");
assert!((3..=1048576).contains(&fd));
let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0)
.expect("pinned prefix shard0 verification failed");
let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1)
.expect("pinned prefix shard1 verification failed");
let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed");
let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE"))
.expect("pinned inherited sealed KAR admission failed");
let binding = ModelBinding::from_artifact_with_inherited_kar_mtp(
artifact,
&inherited,
&required_path("LELEKA_STRA169_MTP_PACK"),
&required_path("LELEKA_STRA169_MTP_STAGING"),
)
.expect("actual pinned KAR+MTP binding failed");
require_opt_in("LELEKA_STRA169_RUN_COMBINED_BOUNDARIES");
let (binding, inherited) = bind_pinned(required_path);
let driver = Driver::load().expect("prefix CUDA driver load failed");
let device = driver.device(0).expect("prefix CUDA device0 unavailable");
let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable"));
let output = OutputStage::load(&binding, context.as_ref()).expect("resident prefix output head unavailable");
let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("actual KAR binding absent"))
.expect("actual KAR device cache unavailable");
let execution = EvaluationExecution::ExperimentalNativeResidentMmq;
let mut moe = match execution {
EvaluationExecution::ExperimentalNativeResidentMmq => {
MoeWeightCache::new_native_mmq(&binding, context.as_ref())
}
_ => panic!("native-certified activation policy required"),
}
.expect("actual native-certified MoE/MTP device cache unavailable");
let dense = DenseWeightCache::new(&binding, context.as_ref()).expect("actual dense device cache unavailable");
let numerical_layer0 = catch_unwind(AssertUnwindSafe(|| {
let mut chunk = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
let report = QwenForward::test_layer0_pair_on_loaded(&binding, &mut chunk, &output, &mut kar, &mut moe, &dense);
drop(chunk);
report
}));
let mut owners = Owners::load(&binding, context.as_ref(), (native_resident_mmq, NATIVE_MOE_REFUSAL));
let layer0 = fresh_owner_phase(&binding, &context, |chunk| {
let o = &mut owners;
QwenForward::test_layer0_pair_on_loaded(&binding, chunk, &o.output, &mut o.kar, &mut o.moe, &o.dense)
});
// Both helpers use genuine fresh target owners on the one admitted
// binding/context/cache. No second source load or CUDA context is created.
let numerical_window = if matches!(&numerical_layer0, Ok(Ok(_))) {
Some(catch_unwind(AssertUnwindSafe(|| {
let mut chunk = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
let report = QwenForward::test_window_boundaries_on_loaded(
&binding, &mut chunk, &output, &mut kar, &mut moe, &dense,
);
drop(chunk);
report
})))
} else {
None
};
// Attempt teardown even after a numerical assertion: no new device work,
// no poison reset, no current live runtime/process is involved.
let observation_disabled = crate::qwen_forward::oracle_capture::disable(&output);
let moe_closed = moe.close();
let dense_closed = dense.close();
drop(kar);
drop(output);
let synchronized = context.synchronize();
let allocated = context.allocated_bytes();
let closed = match Rc::try_unwrap(context) {
Ok(context) => Some(context.close()),
Err(context) => {
drop(context);
None
}
};
drop(binding);
drop(inherited);
let window = matches!(&layer0, Ok(Ok(_))).then(|| {
fresh_owner_phase(&binding, &context, |chunk| {
let o = &mut owners;
QwenForward::test_window_boundaries_on_loaded(&binding, chunk, &o.output, &mut o.kar, &mut o.moe, &o.dense)
})
});
let mut teardown = owners.close(true);
teardown.close_context(context);
drop((binding, inherited));
// Preserve the phase failure after every teardown attempt; a later
// cleanup assertion must not obscure its original diagnostic cause.
let report = match numerical_layer0 {
Ok(report) => report.expect("same-source layer0 diagnostic refused"),
Err(primary) => resume_unwind(primary),
};
let window = match numerical_window.expect("window proof was not admitted") {
Ok(report) => report.expect("changed window proof refused"),
Err(primary) => resume_unwind(primary),
};
assert!(observation_disabled.is_ok(), "final capture observation cleanup failed");
assert!(moe_closed.is_ok(), "prefix MoE/MTP teardown failed");
assert!(dense_closed.is_ok(), "prefix dense teardown failed");
assert!(synchronized.is_ok(), "prefix final synchronization failed");
assert_eq!(allocated, 0, "prefix proof retained owned device buffers");
assert!(matches!(closed, Some(Ok(()))), "prefix Context teardown failed");
let report = unwrap_phase(layer0, "same-source layer0 diagnostic refused");
let window = unwrap_phase(window.expect("window proof was not admitted"), "changed window proof refused");
teardown.assert_clean();
report
.write_after_cleanup(&required_path("LELEKA_STRA169_LAYER0_DIR"))
.expect("exclusive bounded layer0 diagnostic write failed");
window.assert_success_and_print();
eprintln!(
"layer0 diagnostic COMPLETE native-first same-four-rows actual-origins checked packed_down shared_scaled final_products raw_words=256080 allocated_bytes=0 unpublished=true mtp=false head=false quality_pass=false speed_claim=false"
"layer0 diagnostic COMPLETE native-first same-four-rows actual-origins checked packed_down shared_scaled \
final_products raw_words=256080 allocated_bytes=0 unpublished=true mtp=false head=false quality_pass=false \
speed_claim=false"
);
}
@@ -0,0 +1,189 @@
//! The loaded real owners the single-load GPU proofs share: the pinned binding over the inherited sealed archive,
//! the device owners built on one bounded Context, a phase run on a fresh target owner, and the teardown whose
//! results are asserted only after every attempt was made. Opening and scheduling stay with each proof.
use super::*;
use std::{
env,
panic::{AssertUnwindSafe, catch_unwind},
};
pub(in super::super) const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024;
/// Each proof names its own input-path error text.
pub(in super::super) type RequiredPath = fn(&str) -> PathBuf;
pub(in super::super) fn require_opt_in(flag: &str) {
assert!(env::var(flag).is_ok_and(|value| value == "yes"), "explicit prefix GPU proof opt-in required");
}
fn kar_descriptor() -> u32 {
let fd: u32 = env::var("LELEKA_STRA169_KAR_FD")
.expect("missing inherited sealed archive descriptor")
.parse()
.expect("invalid inherited sealed archive descriptor");
assert!((3..=1048576).contains(&fd));
fd
}
fn verified_artifact(required_path: RequiredPath) -> Qwen4ExpArtifact {
let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0)
.expect("pinned prefix shard0 verification failed");
let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1)
.expect("pinned prefix shard1 verification failed");
Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed")
}
fn bind_inherited(
artifact: Qwen4ExpArtifact,
fd: u32,
required_path: RequiredPath,
) -> (ModelBinding, InheritedKarArchive) {
let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE"))
.expect("pinned inherited sealed KAR admission failed");
let binding = ModelBinding::from_artifact_with_inherited_kar_mtp(
artifact,
&inherited,
&required_path("LELEKA_STRA169_MTP_PACK"),
&required_path("LELEKA_STRA169_MTP_STAGING"),
)
.expect("actual pinned KAR+MTP binding failed");
(binding, inherited)
}
/// The pinned binding over the inherited sealed archive.
pub(in super::super) fn bind_pinned(required_path: RequiredPath) -> (ModelBinding, InheritedKarArchive) {
let fd = kar_descriptor();
let artifact = verified_artifact(required_path);
bind_inherited(artifact, fd, required_path)
}
/// The pinned binding with the verified tokenizer and EOS of the same artifact.
pub(in super::super) struct PinnedTokenizer {
pub(in super::super) binding: ModelBinding,
pub(in super::super) inherited: InheritedKarArchive,
pub(in super::super) tokenizer: Tokenizer,
pub(in super::super) eos: u32,
}
pub(in super::super) fn bind_pinned_with_tokenizer(required_path: RequiredPath) -> PinnedTokenizer {
let fd = kar_descriptor();
let artifact = verified_artifact(required_path);
let metadata = artifact.tokenizer();
let tokenizer = Tokenizer::from_vocabulary(
&metadata.model,
&metadata.pre,
metadata.tokens.clone(),
metadata.merges.clone(),
metadata.token_types.clone(),
)
.expect("verified prefix tokenizer construction failed");
let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified prefix EOS absent");
let (binding, inherited) = bind_inherited(artifact, fd, required_path);
PinnedTokenizer { binding, inherited, tokenizer, eos }
}
/// The refusal text of the plain MoE/MTP cache constructors.
pub(in super::super) const MOE_REFUSAL: &str = "actual MoE/MTP device cache unavailable";
/// The MoE/MTP cache constructor of a proof with the text its refusal reports.
pub(in super::super) type MoeCtor<'ctx> = (
fn(
&ModelBinding,
&'ctx leleka_cuda_driver::Context<'ctx>,
) -> crate::qwen_forward::contract::Result<MoeWeightCache<'ctx>>,
&'static str,
);
/// The device owners of one proof, all on the same bounded Context.
pub(in super::super) struct Owners<'ctx> {
pub(in super::super) output: OutputStage<'ctx, 'ctx>,
pub(in super::super) kar: KarPleCache<'ctx>,
pub(in super::super) moe: MoeWeightCache<'ctx>,
pub(in super::super) dense: DenseWeightCache<'ctx>,
}
impl<'ctx> Owners<'ctx> {
pub(in super::super) fn load(
binding: &ModelBinding,
context: &'ctx leleka_cuda_driver::Context<'ctx>,
(new_moe, moe_refusal): MoeCtor<'ctx>,
) -> Self {
let output = OutputStage::load(binding, context).expect("resident prefix output head unavailable");
let kar = KarPleCache::new(context, binding.kar_ple_binding().expect("actual KAR binding absent"))
.expect("actual KAR device cache unavailable");
let moe = new_moe(binding, context).expect(moe_refusal);
let dense = DenseWeightCache::new(binding, context).expect("actual dense device cache unavailable");
Owners { output, kar, moe, dense }
}
/// Attempt teardown even after a numerical assertion: no new device work, no poison reset, no current live
/// runtime/process is involved. `disable_capture` also detaches the capture observation from the output head.
pub(in super::super) fn close(self, disable_capture: bool) -> Teardown {
let Owners { output, kar, moe, dense } = self;
let observation_disabled = !disable_capture || crate::qwen_forward::oracle_capture::disable(&output).is_ok();
let moe_closed = moe.close().is_ok();
let dense_closed = dense.close().is_ok();
drop(kar);
drop(output);
Teardown { observation_disabled, moe_closed, dense_closed, synchronized: false, allocated: 0, closed: false }
}
}
/// What the teardown attempts reported; asserted only after every attempt was made.
pub(in super::super) struct Teardown {
observation_disabled: bool,
moe_closed: bool,
dense_closed: bool,
synchronized: bool,
allocated: usize,
closed: bool,
}
impl Teardown {
/// Synchronize, count what is still allocated and close the Context when nothing else holds it.
pub(in super::super) fn close_context(&mut self, context: Rc<leleka_cuda_driver::Context<'_>>) {
self.synchronized = context.synchronize().is_ok();
self.allocated = context.allocated_bytes();
self.closed = match Rc::try_unwrap(context) {
Ok(context) => context.close().is_ok(),
Err(context) => {
drop(context);
false
}
};
}
pub(in super::super) fn assert_clean(&self) {
assert!(self.observation_disabled, "final capture observation cleanup failed");
assert!(self.moe_closed, "prefix MoE/MTP teardown failed");
assert!(self.dense_closed, "prefix dense teardown failed");
assert!(self.synchronized, "prefix final synchronization failed");
assert_eq!(self.allocated, 0, "prefix proof retained owned device buffers");
assert!(self.closed, "prefix Context teardown failed");
}
}
/// Run one phase on a genuine fresh target owner of the admitted binding/context, catching a numerical panic.
pub(in super::super) fn fresh_owner_phase<'driver, R>(
binding: &ModelBinding,
context: &Rc<leleka_cuda_driver::Context<'driver>>,
phase: impl FnOnce(&mut QwenSession<'driver>) -> R,
) -> std::thread::Result<R> {
catch_unwind(AssertUnwindSafe(|| {
let mut chunk = QwenSession::for_binding_on_shared_device(binding, Rc::clone(context));
let report = phase(&mut chunk);
drop(chunk);
report
}))
}
/// A phase's report, or its panic resumed once every teardown attempt has been made.
pub(in super::super) fn unwrap_phase<T, E: std::fmt::Debug>(
phase: std::thread::Result<Result<T, E>>,
refusal: &str,
) -> T {
match phase {
Ok(report) => report.expect(refusal),
Err(primary) => std::panic::resume_unwind(primary),
}
}
@@ -49,14 +49,23 @@ fn observe(
let logits = output.test_reset_replay_take_logits().expect("actual complete target logits observation missing");
assert_eq!(residual.len(), 10240);
assert_eq!(logits.len(), 248320);
assert_observation_charge(&target, &draft, residual.len(), logits.len());
ObservedPrefix { target, draft, residual, logits, greedy }
}
fn assert_observation_charge(
target: &ResetReplaySnapshot,
draft: &PrefixDraftSnapshot,
residual_words: usize,
logit_words: usize,
) {
let charge = target
.retained_bytes()
.and_then(|n| n.checked_add(draft.retained_bytes()?))
.and_then(|n| n.checked_add(residual.len().checked_mul(4)?))
.and_then(|n| n.checked_add(logits.len().checked_mul(4)?))
.and_then(|n| n.checked_add(residual_words.checked_mul(4)?))
.and_then(|n| n.checked_add(logit_words.checked_mul(4)?))
.expect("observation charge overflow");
assert!(charge <= SNAPSHOT_BOUND, "observation exceeds declared host bound");
ObservedPrefix { target, draft, residual, logits, greedy }
}
struct Inputs<'a, 'ctx, 'driver> {
@@ -70,10 +79,37 @@ struct Inputs<'a, 'ctx, 'driver> {
cancel: AtomicBool,
eos: u32,
}
/// The target steps of the reference, each warming the draft on the known next ID; returns the final product.
fn reference_pass<'ctx, 'driver>(
run: &mut Generation<'_, 'ctx, 'driver, SystemClock>,
decoder: &mut MtpDecoder,
vocabulary: Dimension,
) -> TargetStepProduct {
let mut latest = None;
for (position, &token) in COMPLETE.iter().enumerate() {
let product = match run.target_step(token, position) {
Ok(product) => product,
Err(_) => panic!("reference full target step failed"),
};
if let Some(&next) = COMPLETE.get(position + 1) {
let next = TokenId::new(u64::from(next), vocabulary).expect("reference known-next refused");
decoder
.warm(run.binding, run.session, &product, next, run.output, run.moe_cache)
.expect("reference actual full draft step failed");
}
latest = Some(product);
}
latest.expect("reference full final product absent")
}
impl<'a, 'ctx, 'driver> Inputs<'a, 'ctx, 'driver> {
fn reference(&mut self, session: &mut QwenSession<'ctx>) -> MtpContinuation {
let (sink, stream) = GenerationSink::bounded_channel(16).expect("reference queue refused");
let mut run = Generation {
/// The genuine generator over the borrowed owners, forced to the MTP path.
fn generation<'g>(
&'g mut self,
session: &'g mut QwenSession<'ctx>,
sink: &'g GenerationSink,
) -> Generation<'g, 'ctx, 'driver, SystemClock> {
Generation {
measurement: None,
execution: EvaluationExecution::Native,
binding: self.binding,
@@ -83,34 +119,26 @@ impl<'a, 'ctx, 'driver> Inputs<'a, 'ctx, 'driver> {
dense_cache: self.dense,
session,
tokenizer: self.tokenizer,
sink: &sink,
sink,
cancel: &self.cancel,
shared: &self.shared,
context_tokens: 128,
eos: self.eos,
mtp: true,
clock: SystemClock,
};
let vocabulary = Dimension::new(248320).expect("reference vocabulary refused");
let mut decoder = MtpDecoder::new(self.binding).expect("reference draft refused");
let mut latest = None;
for (position, &token) in COMPLETE.iter().enumerate() {
let product = match run.target_step(token, position) {
Ok(product) => product,
Err(_) => panic!("reference full target step failed"),
};
if let Some(&next) = COMPLETE.get(position + 1) {
let next = TokenId::new(u64::from(next), vocabulary).expect("reference known-next refused");
decoder
.warm(self.binding, run.session, &product, next, self.output, run.moe_cache)
.expect("reference actual full draft step failed");
}
latest = Some(product);
}
}
fn reference(&mut self, session: &mut QwenSession<'ctx>) -> MtpContinuation {
let binding = self.binding;
let (sink, stream) = GenerationSink::bounded_channel(16).expect("reference queue refused");
let mut run = self.generation(session, &sink);
let vocabulary = Dimension::new(248320).expect("reference vocabulary refused");
let mut decoder = MtpDecoder::new(binding).expect("reference draft refused");
let product = reference_pass(&mut run, &mut decoder, vocabulary);
drop(stream);
let product = latest.expect("reference full final product absent");
decoder
.validate_resume(self.binding, run.session, &product, &COMPLETE)
.validate_resume(binding, run.session, &product, &COMPLETE)
.expect("reference actual complete source validation refused");
MtpContinuation { decoder, product, tokens: COMPLETE.to_vec() }
}
@@ -124,30 +152,7 @@ impl<'a, 'ctx, 'driver> Inputs<'a, 'ctx, 'driver> {
) -> MtpContinuation {
let (sink, stream) = GenerationSink::bounded_channel(16).expect("numeric observation queue refused");
let mut pending = None;
let result = generate_mtp_resume(
Generation {
measurement: None,
execution: EvaluationExecution::Native,
binding: self.binding,
output: self.output,
kar_cache: Some(&mut *self.kar),
moe_cache: &mut *self.moe,
dense_cache: self.dense,
session,
tokenizer: self.tokenizer,
sink: &sink,
cancel: &self.cancel,
shared: &self.shared,
context_tokens: 128,
eos: self.eos,
mtp: true,
clock: SystemClock,
},
prompt,
1,
prior,
&mut pending,
);
let result = generate_mtp_resume(self.generation(session, &sink), prompt, 1, prior, &mut pending);
let usage = match result {
Ok((FinishReason::Length | FinishReason::Stop, usage)) => usage,
_ => panic!("genuine forced-input generation failed"),
@@ -162,6 +167,73 @@ impl<'a, 'ctx, 'driver> Inputs<'a, 'ctx, 'driver> {
}
}
/// The loaded owners match the proof's expectations and both sessions are fresh.
fn assert_loaded_preconditions(binding: &ModelBinding, sessions: [&QwenSession<'_>; 2]) {
assert!(SNAPSHOT_BOUND.checked_mul(4).is_some_and(|n| n <= HOST_LIMIT));
assert_eq!(binding.layer_count(), 48);
assert!(binding.kar_ple_binding().is_some());
assert!(binding.mtp_weights().is_ok());
for session in sessions {
assert!(
session
.test_reset_replay_snapshot(binding)
.expect("fresh actual session observation refused")
.has_prefix(0, [-1, -1])
);
}
}
/// The reference: the full head, nonresident QSA, five forced IDs in one pass on the fresh session.
fn reference_observation<'ctx>(
inputs: &mut Inputs<'_, 'ctx, '_>,
resumed_session: &QwenSession<'ctx>,
fresh_session: &mut QwenSession<'ctx>,
) -> ObservedPrefix {
let (binding, output) = (inputs.binding, inputs.output);
output.test_reset_replay_record(true).expect("actual logit observation refused");
crate::qwen_forward::qsa_index::combined_qsa_observer::reset_counts();
let fresh =
crate::qwen_forward::qsa_index::combined_qsa_observer::without_residency(|| inputs.reference(fresh_session));
let expected = observe(binding, fresh_session, output, &fresh);
assert_eq!(
crate::qwen_forward::qsa_index::combined_qsa_observer::counts(),
(60, 0),
"reference did not execute all original nonresident QSA selections"
);
assert!(
fresh.decoder.validate_resume(binding, resumed_session, &fresh.product, &fresh.tokens).is_err(),
"reference source must refuse rival session"
);
expected
}
/// The candidate: three forced IDs, then the complete five reusing the retained three.
fn candidate_observation<'ctx>(
inputs: &mut Inputs<'_, 'ctx, '_>,
resumed_session: &mut QwenSession<'ctx>,
fresh_session: &QwenSession<'ctx>,
) -> ObservedPrefix {
let (binding, output) = (inputs.binding, inputs.output);
let prefix = inputs.advance(resumed_session, &PREFIX, None, 0);
let resumed = inputs.advance(resumed_session, &COMPLETE, Some(prefix), 3);
let actual = observe(binding, resumed_session, output, &resumed);
assert_eq!(
crate::qwen_forward::qsa_index::combined_qsa_observer::counts(),
(60, 60),
"candidate did not execute all resident QSA selections"
);
let (reload, append, reuse) = crate::qwen_forward::qsa_index::combined_qsa_observer::actions();
assert_eq!(reload, 12, "candidate must reload exactly one actual fresh state per QSA layer");
assert_eq!(append + reuse, 48, "candidate incremental QSA action coverage differs");
assert!(append >= 12, "candidate never published completed pooled block row");
assert!(resumed.decoder.validate_resume(binding, resumed_session, &resumed.product, &resumed.tokens).is_ok());
assert!(
resumed.decoder.validate_resume(binding, fresh_session, &resumed.product, &resumed.tokens).is_err(),
"retained source must refuse rival session"
);
actual
}
/// Borrow already loaded real owners; no file opening, model replacement or
/// GPU scheduling here. Root/SDET alone select and execute an ignored GPU test.
/// Actual actor terminal_admit remains Stop-only; this test deliberately
@@ -178,60 +250,12 @@ pub(super) fn check_on_loaded<'ctx, 'driver>(
resumed_session: &mut QwenSession<'ctx>,
fresh_session: &mut QwenSession<'ctx>,
) {
assert!(SNAPSHOT_BOUND.checked_mul(4).is_some_and(|n| n <= HOST_LIMIT));
assert_eq!(binding.layer_count(), 48);
assert!(binding.kar_ple_binding().is_some());
assert!(binding.mtp_weights().is_ok());
for session in [&*resumed_session, &*fresh_session] {
assert!(
session
.test_reset_replay_snapshot(binding)
.expect("fresh actual session observation refused")
.has_prefix(0, [-1, -1])
);
}
let mut inputs = Inputs {
binding,
output,
kar,
moe,
dense,
tokenizer,
shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) },
cancel: AtomicBool::new(false),
eos,
};
output.test_reset_replay_record(true).expect("actual logit observation refused");
crate::qwen_forward::qsa_index::combined_qsa_observer::reset_counts();
let fresh =
crate::qwen_forward::qsa_index::combined_qsa_observer::without_residency(|| inputs.reference(fresh_session));
let expected = observe(binding, fresh_session, output, &fresh);
assert_eq!(
crate::qwen_forward::qsa_index::combined_qsa_observer::counts(),
(60, 0),
"reference did not execute all original nonresident QSA selections"
);
assert!(
fresh.decoder.validate_resume(binding, resumed_session, &fresh.product, &fresh.tokens).is_err(),
"reference source must refuse rival session"
);
let prefix = inputs.advance(resumed_session, &PREFIX, None, 0);
let resumed = inputs.advance(resumed_session, &COMPLETE, Some(prefix), 3);
let actual = observe(binding, resumed_session, output, &resumed);
assert_eq!(
crate::qwen_forward::qsa_index::combined_qsa_observer::counts(),
(60, 60),
"candidate did not execute all resident QSA selections"
);
let (reload, append, reuse) = crate::qwen_forward::qsa_index::combined_qsa_observer::actions();
assert_eq!(reload, 12, "candidate must reload exactly one actual fresh state per QSA layer");
assert_eq!(append + reuse, 48, "candidate incremental QSA action coverage differs");
assert!(append >= 12, "candidate never published completed pooled block row");
assert!(resumed.decoder.validate_resume(binding, resumed_session, &resumed.product, &resumed.tokens).is_ok());
assert!(
resumed.decoder.validate_resume(binding, fresh_session, &resumed.product, &resumed.tokens).is_err(),
"retained source must refuse rival session"
);
assert_loaded_preconditions(binding, [&*resumed_session, &*fresh_session]);
let shared = Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) };
let mut inputs =
Inputs { binding, output, kar, moe, dense, tokenizer, shared, cancel: AtomicBool::new(false), eos };
let expected = reference_observation(&mut inputs, resumed_session, fresh_session);
let actual = candidate_observation(&mut inputs, resumed_session, fresh_session);
assert!(expected.target.numeric_eq(&actual.target), "complete target numerical state differs");
assert!(expected.draft.numeric_eq(&actual.draft), "complete active draft numerical state differs");
assert!(expected.residual == actual.residual, "current target residual bits differ");
@@ -239,6 +263,7 @@ pub(super) fn check_on_loaded<'ctx, 'driver>(
assert_eq!(expected.greedy, actual.greedy, "actual current greedy differs");
output.test_reset_replay_record(false).expect("actual logit observation cleanup refused");
eprintln!(
"combined numeric PASS reference=full_head_nonresident_FIRST candidate=resident_headfree3+2_vs_5 reused=3 target_layers=48 gdn=36 qsa=12 draft_cells=4 logits=248320 exact_bits=true"
"combined numeric PASS reference=full_head_nonresident_FIRST candidate=resident_headfree3+2_vs_5 reused=3 \
target_layers=48 gdn=36 qsa=12 draft_cells=4 logits=248320 exact_bits=true"
);
}
@@ -1,102 +1,54 @@
//! One root-scheduled real-owner prefix equivalence gate in a disposable copy.
//! This never proves Stop-only actor publication or long-context performance.
use super::combined_changed_boundary_proof::rig::{
DEVICE_BUDGET, MOE_REFUSAL, Owners, PinnedTokenizer, bind_pinned_with_tokenizer, require_opt_in,
};
use super::*;
use std::{
env,
panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
};
const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024;
fn required_path(name: &str) -> PathBuf {
env::var_os(name).map(PathBuf::from).expect("missing operator-owned prefix test path")
}
/// The combined prefix comparison on the loaded owners and two fresh sessions.
fn check_prefix<'d>(
binding: &ModelBinding,
owners: &mut Owners<'d>,
(tokenizer, eos): (&Tokenizer, u32),
(resumed, fresh): (&mut QwenSession<'d>, &mut QwenSession<'d>),
) {
let o = owners;
super::combined_prefix_numeric::check_on_loaded(
binding, &o.output, &mut o.kar, &mut o.moe, &o.dense, tokenizer, eos, resumed, fresh,
);
}
#[test]
#[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; no live-owner overlap"]
fn pinned_combined_kar_mtp_retained_three_plus_two_matches_full_reference_five() {
assert!(
env::var("LELEKA_STRA169_RUN_COMBINED_REUSE").is_ok_and(|value| value == "yes"),
"explicit prefix GPU proof opt-in required"
);
let fd: u32 = env::var("LELEKA_STRA169_KAR_FD")
.expect("missing inherited sealed archive descriptor")
.parse()
.expect("invalid inherited sealed archive descriptor");
assert!((3..=1048576).contains(&fd));
let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0)
.expect("pinned prefix shard0 verification failed");
let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1)
.expect("pinned prefix shard1 verification failed");
let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed");
let metadata = artifact.tokenizer();
let tokenizer = Tokenizer::from_vocabulary(
&metadata.model,
&metadata.pre,
metadata.tokens.clone(),
metadata.merges.clone(),
metadata.token_types.clone(),
)
.expect("verified prefix tokenizer construction failed");
let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified prefix EOS absent");
let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE"))
.expect("pinned inherited sealed KAR admission failed");
let binding = ModelBinding::from_artifact_with_inherited_kar_mtp(
artifact,
&inherited,
&required_path("LELEKA_STRA169_MTP_PACK"),
&required_path("LELEKA_STRA169_MTP_STAGING"),
)
.expect("actual pinned KAR+MTP binding failed");
require_opt_in("LELEKA_STRA169_RUN_COMBINED_REUSE");
let PinnedTokenizer { binding, inherited, tokenizer, eos } = bind_pinned_with_tokenizer(required_path);
let driver = Driver::load().expect("prefix CUDA driver load failed");
let device = driver.device(0).expect("prefix CUDA device0 unavailable");
let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable"));
let output = OutputStage::load(&binding, context.as_ref()).expect("resident prefix output head unavailable");
let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("actual KAR binding absent"))
.expect("actual KAR device cache unavailable");
let mut moe = MoeWeightCache::new(&binding, context.as_ref()).expect("actual MoE/MTP device cache unavailable");
let dense = DenseWeightCache::new(&binding, context.as_ref()).expect("actual dense device cache unavailable");
let mut owners = Owners::load(&binding, context.as_ref(), (MoeWeightCache::new, MOE_REFUSAL));
let mut resumed = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
let mut fresh = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
let numerical = catch_unwind(AssertUnwindSafe(|| {
super::combined_prefix_numeric::check_on_loaded(
&binding,
&output,
&mut kar,
&mut moe,
&dense,
&tokenizer,
eos,
&mut resumed,
&mut fresh,
);
check_prefix(&binding, &mut owners, (&tokenizer, eos), (&mut resumed, &mut fresh));
}));
// Attempt teardown even after a numerical assertion: no new device work,
// no poison reset, no current live runtime/process is involved.
drop(resumed);
drop(fresh);
let moe_closed = moe.close();
let dense_closed = dense.close();
drop(kar);
drop(output);
let synchronized = context.synchronize();
let allocated = context.allocated_bytes();
let closed = match Rc::try_unwrap(context) {
Ok(context) => Some(context.close()),
Err(context) => {
drop(context);
None
}
};
drop(binding);
drop(inherited);
drop((resumed, fresh));
let mut teardown = owners.close(false);
teardown.close_context(context);
drop((binding, inherited));
if let Err(primary) = numerical {
resume_unwind(primary);
}
assert!(moe_closed.is_ok(), "prefix MoE/MTP teardown failed");
assert!(dense_closed.is_ok(), "prefix dense teardown failed");
assert!(synchronized.is_ok(), "prefix final synchronization failed");
assert_eq!(allocated, 0, "prefix proof retained owned device buffers");
assert!(matches!(closed, Some(Ok(()))), "prefix Context teardown failed");
teardown.assert_clean();
eprintln!("prefix proof teardown PASS allocated_bytes=0 context_closed=true");
}
@@ -36,7 +36,8 @@ fn seal_json(root: &std::path::Path, name: &str, value: &Value, uid: u32) -> (Pa
(file, sha(&actual)) // FULL actual bytes, including original newline
}
pub(super) fn prepare(inputs: &Inputs<'_, '_, '_>) -> (PathBuf, String) {
/// The fresh, owner-only frames directory under the operator's output root; returns it with the owner's uid.
fn fresh_frames_root() -> (PathBuf, u32) {
assert_eq!(env::var("LELEKA_STRA169_RUN_FIVE_PUBLIC_CASES").as_deref(), Ok("yes"));
let owner_root = path("LELEKA_STRA169_PAIR_OUTPUT");
assert!(owner_root.is_absolute());
@@ -49,9 +50,12 @@ pub(super) fn prepare(inputs: &Inputs<'_, '_, '_>) -> (PathBuf, String) {
let directory = std::fs::symlink_metadata(&root).unwrap();
assert!(directory.is_dir() && directory.uid() == owner.uid());
assert_eq!(root.canonicalize().unwrap(), root);
(root, owner.uid())
}
// Case1 is the ENTIRE original request producer, without a new template or
// guessed tokens. Other cases reuse only its sanitized public document.
/// The five genuine requests: case 1 is the ENTIRE original request producer, without a new template or guessed
/// tokens; the others reuse only its sanitized public document.
fn build_requests(inputs: &Inputs<'_, '_, '_>) -> Vec<(GenerationRequest, Vec<u32>)> {
let (original, original_ids, canonical) = request(inputs.tokenizer);
assert_eq!(original_ids.len(), 202);
assert_eq!(original.max_output_tokens, CAP);
@@ -89,11 +93,13 @@ pub(super) fn prepare(inputs: &Inputs<'_, '_, '_>) -> (PathBuf, String) {
.expect("actual admitted tokenizer refused public frame variant");
requests.push((req, ids));
}
requests
}
/// Check all five genuine products BEFORE writing the first frame. The frozen consumer later independently
/// re-tokenizes every frame again.
fn check_requests(requests: &[(GenerationRequest, Vec<u32>)]) {
assert_eq!(requests.len(), CASE_IDS.len());
let renderer = sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs"));
let mut entries = Vec::new();
// Check all five genuine products BEFORE writing the first frame. The
// frozen consumer later independently re-tokenizes every frame again.
for (index, (req, ids)) in requests.iter().enumerate() {
assert!((1..2048).contains(&ids.len()));
assert!(ids.iter().all(|id| *id < 248320));
@@ -102,28 +108,47 @@ pub(super) fn prepare(inputs: &Inputs<'_, '_, '_>) -> (PathBuf, String) {
assert_eq!(req.temperature_milli, 0);
assert!(requests[..index].iter().all(|(old, old_ids)| old.prompt != req.prompt && old_ids != ids));
}
for (index, (req, ids)) in requests.iter().enumerate() {
let frame = json!({"renderer_source_sha256":renderer,"framed_prompt":req.prompt,
"framed_prompt_sha256":sha(req.prompt.as_bytes()),"input_token_ids":ids,
"framed_count":ids.len(),"model_digest":MODEL_DIGEST,
"max_output_tokens":CAP,"temperature_milli":0});
let (file, digest) = seal_json(&root, &format!("FRAME-{}.json", index + 1), &frame, owner.uid());
let mut raw = Vec::new();
raw.try_reserve_exact(ids.len().checked_mul(4).expect("public IDs byte extent overflow"))
.expect("public IDs allocation refused");
for id in ids {
raw.extend_from_slice(&id.to_le_bytes());
}
let wire = format!("GEN 32 {}\n", ids.iter().map(u32::to_string).collect::<Vec<_>>().join(","));
assert!(wire.len() <= 32768);
entries.push(json!({"ordinal":index,"case_id":CASE_IDS[index],"frame_file":file,
"frame_sha256":digest,"framed_count":ids.len(),"input_ids_sha256":sha(&raw),
"wire_sha256":sha(wire.as_bytes()),"wire_bytes":wire.len()}));
}
/// Seal `FRAME-n.json` of one request; returns its manifest entry.
fn write_frame(
root: &std::path::Path,
uid: u32,
renderer: &str,
(index, req, ids): (usize, &GenerationRequest, &[u32]),
) -> Value {
let frame = json!({"renderer_source_sha256":renderer,"framed_prompt":req.prompt,
"framed_prompt_sha256":sha(req.prompt.as_bytes()),"input_token_ids":ids,
"framed_count":ids.len(),"model_digest":MODEL_DIGEST,
"max_output_tokens":CAP,"temperature_milli":0});
let (file, digest) = seal_json(root, &format!("FRAME-{}.json", index + 1), &frame, uid);
let mut raw = Vec::new();
raw.try_reserve_exact(ids.len().checked_mul(4).expect("public IDs byte extent overflow"))
.expect("public IDs allocation refused");
for id in ids {
raw.extend_from_slice(&id.to_le_bytes());
}
let wire = format!("GEN 32 {}\n", ids.iter().map(u32::to_string).collect::<Vec<_>>().join(","));
assert!(wire.len() <= 32768);
json!({"ordinal":index,"case_id":CASE_IDS[index],"frame_file":file,
"frame_sha256":digest,"framed_count":ids.len(),"input_ids_sha256":sha(&raw),
"wire_sha256":sha(wire.as_bytes()),"wire_bytes":wire.len()})
}
pub(super) fn prepare(inputs: &Inputs<'_, '_, '_>) -> (PathBuf, String) {
let (root, uid) = fresh_frames_root();
let requests = build_requests(inputs);
let renderer = sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs"));
check_requests(&requests);
let entries: Vec<Value> = requests
.iter()
.enumerate()
.map(|(index, (req, ids))| write_frame(&root, uid, &renderer, (index, req, ids)))
.collect();
let manifest = json!({"schema":1,"case_count":5,"baseline_frame_sha256":BASE_FRAME_SHA,
"model_digest":MODEL_DIGEST,"renderer_source_sha256":renderer,"cases":entries});
assert!(serde_json::to_vec(&manifest).unwrap().len() <= 32768);
let sealed = seal_json(&root, "CASE-MANIFEST.json", &manifest, owner.uid());
let sealed = seal_json(&root, "CASE-MANIFEST.json", &manifest, uid);
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o500)).unwrap();
assert_eq!(std::fs::symlink_metadata(&root).unwrap().mode() & 0o777, 0o500);
sealed
@@ -82,7 +82,8 @@ fn completed_boundary(arm: &Arm) -> bool {
&& arm.usage.output_tokens == u64::from(CAP)
&& arm.measurement.output_token_ids.len() == CAP as usize
}
fn admit(tokenizer: &Tokenizer, manifest: &Value) -> Vec<Case> {
/// The closed manifest header, bound to this build's renderer; returns the renderer digest.
fn admit_manifest_header(manifest: &Value) -> String {
fields(
manifest,
&["schema", "case_count", "baseline_frame_sha256", "model_digest", "renderer_source_sha256", "cases"],
@@ -93,80 +94,119 @@ fn admit(tokenizer: &Tokenizer, manifest: &Value) -> Vec<Case> {
assert_eq!(text(manifest, "model_digest"), MODEL_DIGEST);
let renderer = sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs"));
assert_eq!(text(manifest, "renderer_source_sha256"), renderer);
renderer
}
/// The sealed frame matches its manifest entry and this build's renderer and model.
fn check_frame(frame: &Value, entry: &Value, renderer: &str) {
fields(
frame,
&[
"renderer_source_sha256",
"framed_prompt",
"framed_prompt_sha256",
"input_token_ids",
"framed_count",
"model_digest",
"max_output_tokens",
"temperature_milli",
],
);
assert_eq!(text(frame, "renderer_source_sha256"), renderer);
assert_eq!(text(frame, "model_digest"), MODEL_DIGEST);
assert_eq!(number(frame, "max_output_tokens"), u64::from(CAP));
assert_eq!(number(frame, "temperature_milli"), 0);
let count = number(frame, "framed_count");
assert!((1..2048).contains(&count));
assert_eq!(count, number(entry, "framed_count"));
let prompt = text(frame, "framed_prompt");
assert!(!prompt.is_empty() && !prompt.contains('\0'));
assert_eq!(sha(prompt.as_bytes()), text(frame, "framed_prompt_sha256"));
}
/// The IDs of the frame hash to the entry's digests and fit the wire line.
fn check_ids(ids: &[u32], entry: &Value) {
assert!(ids.iter().all(|id| *id < 248320));
let mut raw = Vec::new();
for id in ids {
raw.extend_from_slice(&id.to_le_bytes());
}
assert_eq!(sha(&raw), text(entry, "input_ids_sha256"));
let wire = format!("GEN 32 {}\n", ids.iter().map(u32::to_string).collect::<Vec<_>>().join(","));
assert!(wire.len() <= 32768);
assert_eq!(wire.len() as u64, number(entry, "wire_bytes"));
assert_eq!(sha(wire.as_bytes()), text(entry, "wire_sha256"));
}
/// One manifest entry admitted against its sealed frame and the actual tokenizer; `earlier` are the admitted cases.
fn admit_case(
(i, entry): (usize, &Value),
(tokenizer, renderer, uid): (&Tokenizer, &str, u32),
earlier: &[Case],
) -> Case {
fields(
entry,
&[
"ordinal",
"case_id",
"frame_file",
"frame_sha256",
"framed_count",
"input_ids_sha256",
"wire_sha256",
"wire_bytes",
],
);
assert_eq!(number(entry, "ordinal"), i as u64);
assert_eq!(text(entry, "case_id"), PHASES[i]);
let frame = pinned_json(std::path::Path::new(text(entry, "frame_file")), text(entry, "frame_sha256"), uid);
check_frame(&frame, entry, renderer);
let ids = token_ids(&frame["input_token_ids"]);
assert_eq!(ids.len(), usize::try_from(number(&frame, "framed_count")).unwrap());
check_ids(&ids, entry);
let request = GenerationRequest {
request_id: PHASES[i].into(),
prompt: text(&frame, "framed_prompt").to_owned(),
max_output_tokens: CAP,
temperature_milli: 0,
sampling: Default::default(),
};
// Actual admitted tokenizer, never trust supplied count/IDs as a producer.
assert_eq!(prepare_prompt(tokenizer, &request, 262144).expect("genuine public frame tokenization refused"), ids);
assert!(earlier.iter().all(|old| old.ids != ids && old.request.prompt != request.prompt));
Case { request, ids, admission: entry.clone() }
}
fn admit(tokenizer: &Tokenizer, manifest: &Value) -> Vec<Case> {
let renderer = admit_manifest_header(manifest);
let entries = manifest["cases"].as_array().expect("five public cases required");
assert_eq!(entries.len(), CASE_COUNT);
let mut cases: Vec<Case> = Vec::new();
let uid = std::fs::metadata(path("LELEKA_STRA169_PAIR_OUTPUT")).unwrap().uid();
for (i, entry) in entries.iter().enumerate() {
fields(
entry,
&[
"ordinal",
"case_id",
"frame_file",
"frame_sha256",
"framed_count",
"input_ids_sha256",
"wire_sha256",
"wire_bytes",
],
);
assert_eq!(number(entry, "ordinal"), i as u64);
assert_eq!(text(entry, "case_id"), PHASES[i]);
let frame = pinned_json(std::path::Path::new(text(entry, "frame_file")), text(entry, "frame_sha256"), uid);
fields(
&frame,
&[
"renderer_source_sha256",
"framed_prompt",
"framed_prompt_sha256",
"input_token_ids",
"framed_count",
"model_digest",
"max_output_tokens",
"temperature_milli",
],
);
assert_eq!(text(&frame, "renderer_source_sha256"), renderer);
assert_eq!(text(&frame, "model_digest"), MODEL_DIGEST);
assert_eq!(number(&frame, "max_output_tokens"), u64::from(CAP));
assert_eq!(number(&frame, "temperature_milli"), 0);
let count = number(&frame, "framed_count");
assert!((1..2048).contains(&count));
assert_eq!(count, number(entry, "framed_count"));
let prompt = text(&frame, "framed_prompt");
assert!(!prompt.is_empty() && !prompt.contains('\0'));
assert_eq!(sha(prompt.as_bytes()), text(&frame, "framed_prompt_sha256"));
let ids = token_ids(&frame["input_token_ids"]);
assert_eq!(ids.len(), usize::try_from(count).unwrap());
assert!(ids.iter().all(|id| *id < 248320));
let mut raw = Vec::new();
for id in &ids {
raw.extend_from_slice(&id.to_le_bytes());
}
assert_eq!(sha(&raw), text(entry, "input_ids_sha256"));
let wire = format!("GEN 32 {}\n", ids.iter().map(u32::to_string).collect::<Vec<_>>().join(","));
assert!(wire.len() <= 32768);
assert_eq!(wire.len() as u64, number(entry, "wire_bytes"));
assert_eq!(sha(wire.as_bytes()), text(entry, "wire_sha256"));
let request = GenerationRequest {
request_id: PHASES[i].into(),
prompt: prompt.to_owned(),
max_output_tokens: CAP,
temperature_milli: 0,
sampling: Default::default(),
};
// Actual admitted tokenizer, never trust supplied count/IDs as a producer.
assert_eq!(
prepare_prompt(tokenizer, &request, 262144).expect("genuine public frame tokenization refused"),
ids
);
assert!(cases.iter().all(|old| old.ids != ids && old.request.prompt != request.prompt));
cases.push(Case { request, ids, admission: entry.clone() });
let case = admit_case((i, entry), (tokenizer, &renderer, uid), &cases);
cases.push(case);
}
assert!(serde_json::to_vec(manifest).unwrap().len() <= 32768);
cases
}
/// Run case `i` on a fresh target and draft, then preserve its completed record BEFORE the next arm.
fn run_case(
inputs: &mut Inputs<'_, '_, '_>,
(root, policy): (&std::path::Path, &'static str),
(i, case): (usize, &Case),
) -> Arm {
let arm = inputs.arm(
&case.request,
&case.ids,
EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr,
PHASES[i],
);
// Original arm has drained/joined the consumer and dropped pending draft
// and actual target session. Preserve this completed record BEFORE next arm.
save(
root,
&format!("CASE-{}.json", i + 1),
&json!({"admission":case.admission,"actual":arm.json(PHASES[i], policy)}),
);
arm
}
pub(super) fn run_on_loaded(inputs: &mut Inputs<'_, '_, '_>, file: &std::path::Path, digest: &str) -> FiveCaseReport {
run_on_loaded_with_policy(inputs, file, digest, POLICY)
}
@@ -187,19 +227,7 @@ pub(super) fn run_on_loaded_with_policy(
save(&root, "FIVE-CASE-ADMISSION.json", &admission);
let mut report = FiveCaseReport { arms: Vec::new(), admission, boundary_error: None, policy };
for (i, case) in cases.iter().enumerate() {
let arm = inputs.arm(
&case.request,
&case.ids,
EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr,
PHASES[i],
);
// Original arm has drained/joined the consumer and dropped pending draft
// and actual target session. Preserve this completed record BEFORE next arm.
save(
&root,
&format!("CASE-{}.json", i + 1),
&json!({"admission":case.admission,"actual":arm.json(PHASES[i], policy)}),
);
let arm = run_case(inputs, (&root, policy), (i, case));
let valid = completed_boundary(&arm);
report.arms.push(arm);
if !valid {
@@ -1,94 +1,56 @@
//! Private sole new changed-path model gate; actual source identity/load preserved.
use super::*;
use std::{
env,
panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
use super::combined_changed_boundary_proof::rig::{
DEVICE_BUDGET, Owners, bind_pinned, fresh_owner_phase, require_opt_in,
};
const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024;
use super::*;
use std::{env, panic::resume_unwind};
fn required_path(name: &str) -> PathBuf {
env::var_os(name).map(PathBuf::from).expect("missing operator-owned MMQ proof path")
}
/// The native-certified activation policy of the resident MMQ proofs.
fn native_resident_mmq<'ctx>(
binding: &ModelBinding,
context: &'ctx leleka_cuda_driver::Context<'ctx>,
) -> crate::qwen_forward::contract::Result<MoeWeightCache<'ctx>> {
let execution = EvaluationExecution::ExperimentalNativeResidentMmq;
match execution {
EvaluationExecution::ExperimentalNativeResidentMmq => MoeWeightCache::new_native_mmq(binding, context),
_ => panic!("native-certified activation policy required"),
}
}
const NATIVE_MOE_REFUSAL: &str = "actual native-certified MoE/MTP device cache unavailable";
// New root-only phase: fresh real target owner; no repeated capture/prefix phases.
#[test]
#[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; no live-owner overlap"]
fn pinned_single_load_layer0_native_first_mmq_diagnostic() {
assert!(
env::var("LELEKA_STRA169_RUN_LAYER0_MMQ_DIAGNOSTIC").is_ok_and(|value| value == "yes"),
"explicit prefix GPU proof opt-in required"
);
let fd: u32 = env::var("LELEKA_STRA169_KAR_FD")
.expect("missing inherited sealed archive descriptor")
.parse()
.expect("invalid inherited sealed archive descriptor");
assert!((3..=1048576).contains(&fd));
let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0)
.expect("pinned prefix shard0 verification failed");
let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1)
.expect("pinned prefix shard1 verification failed");
let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed");
let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE"))
.expect("pinned inherited sealed KAR admission failed");
let binding = ModelBinding::from_artifact_with_inherited_kar_mtp(
artifact,
&inherited,
&required_path("LELEKA_STRA169_MTP_PACK"),
&required_path("LELEKA_STRA169_MTP_STAGING"),
)
.expect("actual pinned KAR+MTP binding failed");
require_opt_in("LELEKA_STRA169_RUN_LAYER0_MMQ_DIAGNOSTIC");
let (binding, inherited) = bind_pinned(required_path);
let driver = Driver::load().expect("prefix CUDA driver load failed");
let device = driver.device(0).expect("prefix CUDA device0 unavailable");
let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable"));
let output = OutputStage::load(&binding, context.as_ref()).expect("resident prefix output head unavailable");
let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("actual KAR binding absent"))
.expect("actual KAR device cache unavailable");
let execution = EvaluationExecution::ExperimentalNativeResidentMmq;
let mut moe = match execution {
EvaluationExecution::ExperimentalNativeResidentMmq => {
MoeWeightCache::new_native_mmq(&binding, context.as_ref())
}
_ => panic!("native-certified activation policy required"),
}
.expect("actual native-certified MoE/MTP device cache unavailable");
let dense = DenseWeightCache::new(&binding, context.as_ref()).expect("actual dense device cache unavailable");
let numerical = catch_unwind(AssertUnwindSafe(|| {
let mut chunk = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
let report = QwenForward::test_layer0_pair_on_loaded(&binding, &mut chunk, &output, &mut kar, &mut moe, &dense);
drop(chunk);
report
}));
// Attempt teardown even after a numerical assertion: no new device work,
// no poison reset, no current live runtime/process is involved.
let observation_disabled = crate::qwen_forward::oracle_capture::disable(&output);
let moe_closed = moe.close();
let dense_closed = dense.close();
drop(kar);
drop(output);
let synchronized = context.synchronize();
let allocated = context.allocated_bytes();
let closed = match Rc::try_unwrap(context) {
Ok(context) => Some(context.close()),
Err(context) => {
drop(context);
None
}
};
drop(binding);
drop(inherited);
let mut owners = Owners::load(&binding, context.as_ref(), (native_resident_mmq, NATIVE_MOE_REFUSAL));
let numerical = fresh_owner_phase(&binding, &context, |chunk| {
let o = &mut owners;
QwenForward::test_layer0_pair_on_loaded(&binding, chunk, &o.output, &mut o.kar, &mut o.moe, &o.dense)
});
let mut teardown = owners.close(true);
teardown.close_context(context);
drop((binding, inherited));
let report = match numerical {
Ok(report) => report,
Err(primary) => resume_unwind(primary),
};
assert!(observation_disabled.is_ok(), "final capture observation cleanup failed");
assert!(moe_closed.is_ok(), "prefix MoE/MTP teardown failed");
assert!(dense_closed.is_ok(), "prefix dense teardown failed");
assert!(synchronized.is_ok(), "prefix final synchronization failed");
assert_eq!(allocated, 0, "prefix proof retained owned device buffers");
assert!(matches!(closed, Some(Ok(()))), "prefix Context teardown failed");
teardown.assert_clean();
let report = report.expect("same-source layer0 diagnostic refused");
report
.write_after_cleanup(&required_path("LELEKA_STRA169_LAYER0_DIR"))
.expect("exclusive bounded layer0 diagnostic write failed");
eprintln!(
"layer0 diagnostic COMPLETE native-first same-four-rows actual-origins checked packed_down shared_scaled final_products raw_words=256080 allocated_bytes=0 unpublished=true mtp=false head=false quality_pass=false speed_claim=false"
"layer0 diagnostic COMPLETE native-first same-four-rows actual-origins checked packed_down shared_scaled \
final_products raw_words=256080 allocated_bytes=0 unpublished=true mtp=false head=false quality_pass=false \
speed_claim=false"
);
}
@@ -36,11 +36,20 @@ pub fn render(messages: &[Message<'_>], effort: Effort) -> Result<String, &'stat
render_with_tools(messages, effort, &[])
}
pub fn render_with_tools(
messages: &[Message<'_>],
effort: Effort,
tools: &[Value],
) -> Result<String, &'static str> {
const TOOLS_FOOTER: &str = "\
\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\
\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n\
</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can \
span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function \
calls MUST follow the specified format: an inner <function=...></function> block must be nested \
within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide \
optional reasoning for your function call in natural language BEFORE the function call, but NOT \
after\n- If there is no function call available, answer the question like normal with your current \
knowledge and do not tell the user about function calls\n</IMPORTANT>";
/// The index of the first message that is not system or developer; those must all come first and a user message
/// must come last.
fn first_non_system(messages: &[Message<'_>]) -> Result<usize, &'static str> {
if messages.is_empty() {
return Err("prompt needs a message");
}
@@ -61,7 +70,76 @@ pub fn render_with_tools(
{
return Err("generation needs a final user message");
}
Ok(first_non_system)
}
/// One tool definition as the template prints it.
fn push_tool(prompt: &mut String, tool: &Value) -> Result<(), &'static str> {
let name = tool
.get("name")
.and_then(Value::as_str)
.ok_or("tool needs a name")?;
prompt.push('\n');
prompt.push_str("{\"type\": \"function\", \"function\": {\"name\": ");
prompt.push_str(&serde_json::to_string(name).expect("string JSON"));
if let Some(description) = tool.get("description").and_then(Value::as_str) {
prompt.push_str(", \"description\": ");
prompt.push_str(&serde_json::to_string(description).expect("string JSON"));
}
if let Some(parameters) = tool.get("parameters") {
prompt.push_str(", \"parameters\": ");
write_template_json(parameters, prompt);
}
if let Some(strict) = tool.get("strict") {
prompt.push_str(", \"strict\": ");
write_template_json(strict, prompt);
}
prompt.push_str("}}");
Ok(())
}
/// The `# Tools` section of the system block.
fn push_tools(prompt: &mut String, instruction: &str, tools: &[Value]) -> Result<(), &'static str> {
if !instruction.is_empty() {
prompt.push_str("\n\n");
}
prompt.push_str("# Tools\n\nYou have access to the following functions:\n\n<tools>");
for tool in tools {
push_tool(prompt, tool)?;
}
prompt.push_str(TOOLS_FOOTER);
Ok(())
}
/// The system block: effort instruction, tool section and the joined system messages.
fn push_system_block(
prompt: &mut String,
instruction: &str,
system: &str,
tools: &[Value],
) -> Result<(), &'static str> {
if instruction.is_empty() && system.is_empty() && tools.is_empty() {
return Ok(());
}
prompt.push_str("<|im_start|>system\n");
prompt.push_str(instruction);
if !tools.is_empty() {
push_tools(prompt, instruction, tools)?;
}
if !system.is_empty() && (!instruction.is_empty() || !tools.is_empty()) {
prompt.push_str("\n\n");
}
prompt.push_str(system);
prompt.push_str("<|im_end|>\n");
Ok(())
}
pub fn render_with_tools(
messages: &[Message<'_>],
effort: Effort,
tools: &[Value],
) -> Result<String, &'static str> {
let first_non_system = first_non_system(messages)?;
let system = messages[..first_non_system]
.iter()
.map(|message| message.content.trim())
@@ -74,44 +152,7 @@ pub fn render_with_tools(
Effort::High | Effort::XHigh => XHIGH,
};
let mut prompt = String::new();
if !instruction.is_empty() || !system.is_empty() || !tools.is_empty() {
prompt.push_str("<|im_start|>system\n");
prompt.push_str(instruction);
if !tools.is_empty() {
if !instruction.is_empty() {
prompt.push_str("\n\n");
}
prompt.push_str("# Tools\n\nYou have access to the following functions:\n\n<tools>");
for tool in tools {
let name = tool
.get("name")
.and_then(Value::as_str)
.ok_or("tool needs a name")?;
prompt.push('\n');
prompt.push_str("{\"type\": \"function\", \"function\": {\"name\": ");
prompt.push_str(&serde_json::to_string(name).expect("string JSON"));
if let Some(description) = tool.get("description").and_then(Value::as_str) {
prompt.push_str(", \"description\": ");
prompt.push_str(&serde_json::to_string(description).expect("string JSON"));
}
if let Some(parameters) = tool.get("parameters") {
prompt.push_str(", \"parameters\": ");
write_template_json(parameters, &mut prompt);
}
if let Some(strict) = tool.get("strict") {
prompt.push_str(", \"strict\": ");
write_template_json(strict, &mut prompt);
}
prompt.push_str("}}");
}
prompt.push_str("\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>");
}
if !system.is_empty() && (!instruction.is_empty() || !tools.is_empty()) {
prompt.push_str("\n\n");
}
prompt.push_str(&system);
prompt.push_str("<|im_end|>\n");
}
push_system_block(&mut prompt, instruction, &system, tools)?;
for message in &messages[first_non_system..] {
match message.role {
Role::User => {
@@ -136,25 +177,30 @@ pub fn render_with_tools(
Ok(prompt)
}
/// The keys of a JSON-schema-like object in template order: `type` first when the object has one.
fn template_keys(fields: &serde_json::Map<String, Value>) -> Vec<&String> {
let mut keys = fields.keys().collect::<Vec<_>>();
if fields.contains_key("type") {
let priority = |key: &str| match key {
"type" => 0,
"properties" => 1,
"required" => 2,
"items" => 3,
"enum" => 4,
"description" => 5,
"additionalProperties" => 6,
_ => 7,
};
keys.sort_by_key(|key| (priority(key), key.as_str()));
}
keys
}
fn write_template_json(value: &Value, output: &mut String) {
match value {
Value::Object(fields) => {
let mut keys = fields.keys().collect::<Vec<_>>();
if fields.contains_key("type") {
let priority = |key: &str| match key {
"type" => 0,
"properties" => 1,
"required" => 2,
"items" => 3,
"enum" => 4,
"description" => 5,
"additionalProperties" => 6,
_ => 7,
};
keys.sort_by_key(|key| (priority(key), key.as_str()));
}
output.push('{');
for (index, key) in keys.into_iter().enumerate() {
for (index, key) in template_keys(fields).into_iter().enumerate() {
if index > 0 {
output.push_str(", ");
}
@@ -1,119 +1,97 @@
//! Private sole new changed-path model gate; actual source identity/load preserved.
use super::*;
use std::{
env,
panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
use super::combined_changed_boundary_proof::rig::{
DEVICE_BUDGET, Owners, bind_pinned, fresh_owner_phase, require_opt_in,
};
const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024;
use super::*;
use std::{env, panic::resume_unwind};
fn required_path(name: &str) -> PathBuf {
env::var_os(name).map(PathBuf::from).expect("missing operator-owned MMQ proof path")
}
/// The native-certified activation policy of the resident MMQ proofs.
fn native_resident_mmq<'ctx>(
binding: &ModelBinding,
context: &'ctx leleka_cuda_driver::Context<'ctx>,
) -> crate::qwen_forward::contract::Result<MoeWeightCache<'ctx>> {
let execution = EvaluationExecution::ExperimentalNativeResidentMmq;
match execution {
EvaluationExecution::ExperimentalNativeResidentMmq => MoeWeightCache::new_native_mmq(binding, context),
_ => panic!("native-certified activation policy required"),
}
}
const NATIVE_MOE_REFUSAL: &str = "actual native-certified MoE/MTP device cache unavailable";
/// Run the native-resident MMQ comparison on a fresh target owner. The returned closure prints the observations
/// and asserts the greedy equalities of its report; the caller runs it once the teardown is done.
fn native_phase<'d>(
binding: &ModelBinding,
context: &Rc<leleka_cuda_driver::Context<'d>>,
owners: &mut Owners<'d>,
) -> std::thread::Result<impl FnOnce() + use<>> {
let report = fresh_owner_phase(binding, context, |chunk| {
let o = owners;
QwenForward::test_native_mmq_on_loaded(binding, chunk, &o.output, &mut o.kar, &mut o.moe, &o.dense)
})?;
Ok(move || {
for (phase, head) in [("final", &report.final_head), ("continuation", &report.continuation_head)] {
eprintln!(
"native-resident MMQ observation phase={} fullhead_words={} different={} max_abs={} native_greedy={} \
candidate_greedy={} allocated_bytes=0 GateC=false speed_claim=false",
phase, head.words, head.different, head.max_abs, head.baseline_greedy, head.candidate_greedy
);
}
eprintln!(
"native-resident MMQ state observation head_exact={} residual_exact={} target_exact={} draft_exact={} \
continued_head_exact={} continued_target_exact={} continued_draft_exact={} resident_layers={} \
resident_columns={} native_fallback_layers={} cleanup_complete=true",
report.head_exact,
report.residual_exact,
report.target_exact,
report.draft_exact,
report.continued_head_exact,
report.continued_target_exact,
report.continued_draft_exact,
report.resident_layers,
report.resident_columns,
report.native_fallback_layers
);
assert_eq!(
report.final_head.baseline_greedy, report.final_head.candidate_greedy,
"native-resident MMQ final greedy mismatch"
);
assert_eq!(
report.continuation_head.baseline_greedy, report.continuation_head.candidate_greedy,
"native-resident MMQ continuation greedy mismatch"
);
})
}
// New root-only phase: fresh real target owner; no repeated capture/prefix phases.
#[test]
#[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; no live-owner overlap"]
fn pinned_single_load_native_resident_mmq_model_numeric() {
assert!(
env::var("LELEKA_STRA169_RUN_NATIVE_RESIDENT_MMQ_MODEL").is_ok_and(|value| value == "yes"),
"explicit prefix GPU proof opt-in required"
);
let fd: u32 = env::var("LELEKA_STRA169_KAR_FD")
.expect("missing inherited sealed archive descriptor")
.parse()
.expect("invalid inherited sealed archive descriptor");
assert!((3..=1048576).contains(&fd));
let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0)
.expect("pinned prefix shard0 verification failed");
let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1)
.expect("pinned prefix shard1 verification failed");
let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed");
let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE"))
.expect("pinned inherited sealed KAR admission failed");
let binding = ModelBinding::from_artifact_with_inherited_kar_mtp(
artifact,
&inherited,
&required_path("LELEKA_STRA169_MTP_PACK"),
&required_path("LELEKA_STRA169_MTP_STAGING"),
)
.expect("actual pinned KAR+MTP binding failed");
require_opt_in("LELEKA_STRA169_RUN_NATIVE_RESIDENT_MMQ_MODEL");
let (binding, inherited) = bind_pinned(required_path);
let driver = Driver::load().expect("prefix CUDA driver load failed");
let device = driver.device(0).expect("prefix CUDA device0 unavailable");
let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable"));
let output = OutputStage::load(&binding, context.as_ref()).expect("resident prefix output head unavailable");
let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("actual KAR binding absent"))
.expect("actual KAR device cache unavailable");
let execution = EvaluationExecution::ExperimentalNativeResidentMmq;
let mut moe = match execution {
EvaluationExecution::ExperimentalNativeResidentMmq => {
MoeWeightCache::new_native_mmq(&binding, context.as_ref())
}
_ => panic!("native-certified activation policy required"),
}
.expect("actual native-certified MoE/MTP device cache unavailable");
let dense = DenseWeightCache::new(&binding, context.as_ref()).expect("actual dense device cache unavailable");
let numerical = catch_unwind(AssertUnwindSafe(|| {
let mut chunk = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
let report = QwenForward::test_native_mmq_on_loaded(&binding, &mut chunk, &output, &mut kar, &mut moe, &dense);
drop(chunk);
report
}));
// Attempt teardown even after a numerical assertion: no new device work,
// no poison reset, no current live runtime/process is involved.
let observation_disabled = crate::qwen_forward::oracle_capture::disable(&output);
let moe_closed = moe.close();
let dense_closed = dense.close();
drop(kar);
drop(output);
let synchronized = context.synchronize();
let allocated = context.allocated_bytes();
let closed = match Rc::try_unwrap(context) {
Ok(context) => Some(context.close()),
Err(context) => {
drop(context);
None
}
};
drop(binding);
drop(inherited);
let report = match numerical {
Ok(report) => report,
let mut owners = Owners::load(&binding, context.as_ref(), (native_resident_mmq, NATIVE_MOE_REFUSAL));
let numerical = native_phase(&binding, &context, &mut owners);
let mut teardown = owners.close(true);
teardown.close_context(context);
drop((binding, inherited));
let report_and_assert = match numerical {
Ok(report_and_assert) => report_and_assert,
Err(primary) => resume_unwind(primary),
};
assert!(observation_disabled.is_ok(), "final capture observation cleanup failed");
assert!(moe_closed.is_ok(), "prefix MoE/MTP teardown failed");
assert!(dense_closed.is_ok(), "prefix dense teardown failed");
assert!(synchronized.is_ok(), "prefix final synchronization failed");
assert_eq!(allocated, 0, "prefix proof retained owned device buffers");
assert!(matches!(closed, Some(Ok(()))), "prefix Context teardown failed");
teardown.assert_clean();
// No GPU/cache/session owners remain when diagnosis and strict quality
// assertions run. Tensor exactness remains reported, as in the frozen gate.
for (phase, head) in [("final", &report.final_head), ("continuation", &report.continuation_head)] {
eprintln!(
"native-resident MMQ observation phase={} fullhead_words={} different={} max_abs={} native_greedy={} candidate_greedy={} allocated_bytes=0 GateC=false speed_claim=false",
phase, head.words, head.different, head.max_abs, head.baseline_greedy, head.candidate_greedy
);
}
report_and_assert();
eprintln!(
"native-resident MMQ state observation head_exact={} residual_exact={} target_exact={} draft_exact={} continued_head_exact={} continued_target_exact={} continued_draft_exact={} resident_layers={} resident_columns={} native_fallback_layers={} cleanup_complete=true",
report.head_exact,
report.residual_exact,
report.target_exact,
report.draft_exact,
report.continued_head_exact,
report.continued_target_exact,
report.continued_draft_exact,
report.resident_layers,
report.resident_columns,
report.native_fallback_layers
);
assert_eq!(
report.final_head.baseline_greedy, report.final_head.candidate_greedy,
"native-resident MMQ final greedy mismatch"
);
assert_eq!(
report.continuation_head.baseline_greedy, report.continuation_head.candidate_greedy,
"native-resident MMQ continuation greedy mismatch"
);
eprintln!(
"native-resident MMQ bounded greedy GateB PASS rows=4 layers=48 actual_final_outputs=2 early_cancelled_prefix_unchanged=true canceled_actual_mtp_warm=true allocated_bytes=0 GateC=false longcontext=false speed_claim=false"
"native-resident MMQ bounded greedy GateB PASS rows=4 layers=48 actual_final_outputs=2 \
early_cancelled_prefix_unchanged=true canceled_actual_mtp_warm=true allocated_bytes=0 GateC=false \
longcontext=false speed_claim=false"
);
}
@@ -1,79 +1,34 @@
//! Private sole new changed-path model gate; actual source identity/load preserved.
use super::*;
use std::{
env,
panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
use super::combined_changed_boundary_proof::rig::{
DEVICE_BUDGET, MOE_REFUSAL, Owners, bind_pinned, fresh_owner_phase, require_opt_in,
};
const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024;
use super::*;
use std::{env, panic::resume_unwind};
fn required_path(name: &str) -> PathBuf {
env::var_os(name).map(PathBuf::from).expect("missing operator-owned MMQ proof path")
}
// New root-only phase: fresh real target owner; no repeated capture/prefix phases.
#[test]
#[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; no live-owner overlap"]
fn pinned_single_load_resident_mmq_model_numeric() {
assert!(
env::var("LELEKA_STRA169_RUN_RESIDENT_MMQ_MODEL").is_ok_and(|value| value == "yes"),
"explicit prefix GPU proof opt-in required"
);
let fd: u32 = env::var("LELEKA_STRA169_KAR_FD")
.expect("missing inherited sealed archive descriptor")
.parse()
.expect("invalid inherited sealed archive descriptor");
assert!((3..=1048576).contains(&fd));
let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0)
.expect("pinned prefix shard0 verification failed");
let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1)
.expect("pinned prefix shard1 verification failed");
let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed");
let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE"))
.expect("pinned inherited sealed KAR admission failed");
let binding = ModelBinding::from_artifact_with_inherited_kar_mtp(
artifact,
&inherited,
&required_path("LELEKA_STRA169_MTP_PACK"),
&required_path("LELEKA_STRA169_MTP_STAGING"),
)
.expect("actual pinned KAR+MTP binding failed");
require_opt_in("LELEKA_STRA169_RUN_RESIDENT_MMQ_MODEL");
let (binding, inherited) = bind_pinned(required_path);
let driver = Driver::load().expect("prefix CUDA driver load failed");
let device = driver.device(0).expect("prefix CUDA device0 unavailable");
let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable"));
let output = OutputStage::load(&binding, context.as_ref()).expect("resident prefix output head unavailable");
let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("actual KAR binding absent"))
.expect("actual KAR device cache unavailable");
let mut moe = MoeWeightCache::new_mmq(&binding, context.as_ref()).expect("actual MoE/MTP device cache unavailable");
let dense = DenseWeightCache::new(&binding, context.as_ref()).expect("actual dense device cache unavailable");
let numerical = catch_unwind(AssertUnwindSafe(|| {
let mut chunk = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
QwenForward::test_mmq_on_loaded(&binding, &mut chunk, &output, &mut kar, &mut moe, &dense);
drop(chunk);
}));
// Attempt teardown even after a numerical assertion: no new device work,
// no poison reset, no current live runtime/process is involved.
let observation_disabled = crate::qwen_forward::oracle_capture::disable(&output);
let moe_closed = moe.close();
let dense_closed = dense.close();
drop(kar);
drop(output);
let synchronized = context.synchronize();
let allocated = context.allocated_bytes();
let closed = match Rc::try_unwrap(context) {
Ok(context) => Some(context.close()),
Err(context) => {
drop(context);
None
}
};
drop(binding);
drop(inherited);
let mut owners = Owners::load(&binding, context.as_ref(), (MoeWeightCache::new_mmq, MOE_REFUSAL));
let numerical = fresh_owner_phase(&binding, &context, |chunk| {
let o = &mut owners;
QwenForward::test_mmq_on_loaded(&binding, chunk, &o.output, &mut o.kar, &mut o.moe, &o.dense);
});
let mut teardown = owners.close(true);
teardown.close_context(context);
drop((binding, inherited));
if let Err(primary) = numerical {
resume_unwind(primary);
}
assert!(observation_disabled.is_ok(), "final capture observation cleanup failed");
assert!(moe_closed.is_ok(), "prefix MoE/MTP teardown failed");
assert!(dense_closed.is_ok(), "prefix dense teardown failed");
assert!(synchronized.is_ok(), "prefix final synchronization failed");
assert_eq!(allocated, 0, "prefix proof retained owned device buffers");
assert!(matches!(closed, Some(Ok(()))), "prefix Context teardown failed");
teardown.assert_clean();
eprintln!("resident MMQ model proof teardown PASS allocated_bytes=0 context_closed=true");
}
@@ -1,125 +1,83 @@
//! One root-scheduled loaded owner: actual capture2 then original-reference-FIRST
//! combined prefix/QSA/headfree and chunk numeric equivalence, one verification/load.
//! This never proves Stop-only actor publication or long-context performance.
use super::combined_changed_boundary_proof::rig::{
DEVICE_BUDGET, MOE_REFUSAL, Owners, PinnedTokenizer, bind_pinned, bind_pinned_with_tokenizer, fresh_owner_phase,
require_opt_in,
};
use super::*;
use std::{
env,
panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
};
const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024;
fn required_path(name: &str) -> PathBuf {
env::var_os(name).map(PathBuf::from).expect("missing operator-owned prefix test path")
}
/// The three phases of the first proof: capture of two tokens, the combined prefix comparison, the chunk numeric.
fn capture_prefix_and_chunk<'d>(
binding: &ModelBinding,
context: &Rc<leleka_cuda_driver::Context<'d>>,
owners: &mut Owners<'d>,
(tokenizer, eos): (&Tokenizer, u32),
) {
let mut captured = QwenSession::for_binding_on_shared_device(binding, Rc::clone(context));
let capture = crate::qwen_forward::oracle_capture::check_on_loaded(
binding,
&mut captured,
&owners.output,
&mut owners.kar,
&mut owners.moe,
&owners.dense,
required_path("LELEKA_STRA169_CAPTURE_DIR"),
);
let disabled = crate::qwen_forward::oracle_capture::disable(&owners.output);
capture.expect("actual two-token capture failed");
disabled.expect("capture observation cleanup failed");
// Capture's complete target state must not coexist with two full numeric
// snapshots. Drop this owner before starting reference-FIRST comparison.
drop(captured);
let mut resumed = QwenSession::for_binding_on_shared_device(binding, Rc::clone(context));
let mut fresh = QwenSession::for_binding_on_shared_device(binding, Rc::clone(context));
let o = &mut *owners;
super::combined_prefix_numeric::check_on_loaded(
binding,
&o.output,
&mut o.kar,
&mut o.moe,
&o.dense,
tokenizer,
eos,
&mut resumed,
&mut fresh,
);
drop(resumed);
drop(fresh);
let mut chunk = QwenSession::for_binding_on_shared_device(binding, Rc::clone(context));
QwenForward::test_chunk_on_loaded(binding, &mut chunk, &o.output, &mut o.kar, &mut o.moe, &o.dense);
drop(chunk);
}
#[test]
#[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; no live-owner overlap"]
fn pinned_single_load_capture_two_combined_reuse_and_chunk_numeric() {
assert!(
env::var("LELEKA_STRA169_RUN_SINGLELOAD_PROOF").is_ok_and(|value| value == "yes"),
"explicit prefix GPU proof opt-in required"
);
let fd: u32 = env::var("LELEKA_STRA169_KAR_FD")
.expect("missing inherited sealed archive descriptor")
.parse()
.expect("invalid inherited sealed archive descriptor");
assert!((3..=1048576).contains(&fd));
let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0)
.expect("pinned prefix shard0 verification failed");
let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1)
.expect("pinned prefix shard1 verification failed");
let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed");
let metadata = artifact.tokenizer();
let tokenizer = Tokenizer::from_vocabulary(
&metadata.model,
&metadata.pre,
metadata.tokens.clone(),
metadata.merges.clone(),
metadata.token_types.clone(),
)
.expect("verified prefix tokenizer construction failed");
let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified prefix EOS absent");
let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE"))
.expect("pinned inherited sealed KAR admission failed");
let binding = ModelBinding::from_artifact_with_inherited_kar_mtp(
artifact,
&inherited,
&required_path("LELEKA_STRA169_MTP_PACK"),
&required_path("LELEKA_STRA169_MTP_STAGING"),
)
.expect("actual pinned KAR+MTP binding failed");
require_opt_in("LELEKA_STRA169_RUN_SINGLELOAD_PROOF");
let PinnedTokenizer { binding, inherited, tokenizer, eos } = bind_pinned_with_tokenizer(required_path);
let driver = Driver::load().expect("prefix CUDA driver load failed");
let device = driver.device(0).expect("prefix CUDA device0 unavailable");
let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable"));
let output = OutputStage::load(&binding, context.as_ref()).expect("resident prefix output head unavailable");
let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("actual KAR binding absent"))
.expect("actual KAR device cache unavailable");
let mut moe = MoeWeightCache::new(&binding, context.as_ref()).expect("actual MoE/MTP device cache unavailable");
let dense = DenseWeightCache::new(&binding, context.as_ref()).expect("actual dense device cache unavailable");
let mut owners = Owners::load(&binding, context.as_ref(), (MoeWeightCache::new, MOE_REFUSAL));
let numerical = catch_unwind(AssertUnwindSafe(|| {
let mut captured = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
let capture = crate::qwen_forward::oracle_capture::check_on_loaded(
&binding,
&mut captured,
&output,
&mut kar,
&mut moe,
&dense,
required_path("LELEKA_STRA169_CAPTURE_DIR"),
);
let disabled = crate::qwen_forward::oracle_capture::disable(&output);
capture.expect("actual two-token capture failed");
disabled.expect("capture observation cleanup failed");
// Capture's complete target state must not coexist with two full numeric
// snapshots. Drop this owner before starting reference-FIRST comparison.
drop(captured);
let mut resumed = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
let mut fresh = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
super::combined_prefix_numeric::check_on_loaded(
&binding,
&output,
&mut kar,
&mut moe,
&dense,
&tokenizer,
eos,
&mut resumed,
&mut fresh,
);
drop(resumed);
drop(fresh);
let mut chunk = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
QwenForward::test_chunk_on_loaded(&binding, &mut chunk, &output, &mut kar, &mut moe, &dense);
drop(chunk);
capture_prefix_and_chunk(&binding, &context, &mut owners, (&tokenizer, eos));
}));
// Attempt teardown even after a numerical assertion: no new device work,
// no poison reset, no current live runtime/process is involved.
let observation_disabled = crate::qwen_forward::oracle_capture::disable(&output);
let moe_closed = moe.close();
let dense_closed = dense.close();
drop(kar);
drop(output);
let synchronized = context.synchronize();
let allocated = context.allocated_bytes();
let closed = match Rc::try_unwrap(context) {
Ok(context) => Some(context.close()),
Err(context) => {
drop(context);
None
}
};
drop(binding);
drop(inherited);
let mut teardown = owners.close(true);
teardown.close_context(context);
drop((binding, inherited));
if let Err(primary) = numerical {
resume_unwind(primary);
}
assert!(observation_disabled.is_ok(), "final capture observation cleanup failed");
assert!(moe_closed.is_ok(), "prefix MoE/MTP teardown failed");
assert!(dense_closed.is_ok(), "prefix dense teardown failed");
assert!(synchronized.is_ok(), "prefix final synchronization failed");
assert_eq!(allocated, 0, "prefix proof retained owned device buffers");
assert!(matches!(closed, Some(Ok(()))), "prefix Context teardown failed");
teardown.assert_clean();
eprintln!("singleload proof teardown PASS allocated_bytes=0 context_closed=true");
}
@@ -127,68 +85,22 @@ fn pinned_single_load_capture_two_combined_reuse_and_chunk_numeric() {
#[test]
#[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; no live-owner overlap"]
fn pinned_single_load_grouped_certified_chunk_numeric() {
assert!(
env::var("LELEKA_STRA169_RUN_GROUPED_CHUNK_PROOF").is_ok_and(|value| value == "yes"),
"explicit prefix GPU proof opt-in required"
);
let fd: u32 = env::var("LELEKA_STRA169_KAR_FD")
.expect("missing inherited sealed archive descriptor")
.parse()
.expect("invalid inherited sealed archive descriptor");
assert!((3..=1048576).contains(&fd));
let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0)
.expect("pinned prefix shard0 verification failed");
let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1)
.expect("pinned prefix shard1 verification failed");
let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed");
let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE"))
.expect("pinned inherited sealed KAR admission failed");
let binding = ModelBinding::from_artifact_with_inherited_kar_mtp(
artifact,
&inherited,
&required_path("LELEKA_STRA169_MTP_PACK"),
&required_path("LELEKA_STRA169_MTP_STAGING"),
)
.expect("actual pinned KAR+MTP binding failed");
require_opt_in("LELEKA_STRA169_RUN_GROUPED_CHUNK_PROOF");
let (binding, inherited) = bind_pinned(required_path);
let driver = Driver::load().expect("prefix CUDA driver load failed");
let device = driver.device(0).expect("prefix CUDA device0 unavailable");
let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable"));
let output = OutputStage::load(&binding, context.as_ref()).expect("resident prefix output head unavailable");
let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("actual KAR binding absent"))
.expect("actual KAR device cache unavailable");
let mut moe = MoeWeightCache::new(&binding, context.as_ref()).expect("actual MoE/MTP device cache unavailable");
let dense = DenseWeightCache::new(&binding, context.as_ref()).expect("actual dense device cache unavailable");
let numerical = catch_unwind(AssertUnwindSafe(|| {
let mut chunk = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
QwenForward::test_chunk_on_loaded(&binding, &mut chunk, &output, &mut kar, &mut moe, &dense);
drop(chunk);
}));
// Attempt teardown even after a numerical assertion: no new device work,
// no poison reset, no current live runtime/process is involved.
let observation_disabled = crate::qwen_forward::oracle_capture::disable(&output);
let moe_closed = moe.close();
let dense_closed = dense.close();
drop(kar);
drop(output);
let synchronized = context.synchronize();
let allocated = context.allocated_bytes();
let closed = match Rc::try_unwrap(context) {
Ok(context) => Some(context.close()),
Err(context) => {
drop(context);
None
}
};
drop(binding);
drop(inherited);
let mut owners = Owners::load(&binding, context.as_ref(), (MoeWeightCache::new, MOE_REFUSAL));
let numerical = fresh_owner_phase(&binding, &context, |chunk| {
let o = &mut owners;
QwenForward::test_chunk_on_loaded(&binding, chunk, &o.output, &mut o.kar, &mut o.moe, &o.dense);
});
let mut teardown = owners.close(true);
teardown.close_context(context);
drop((binding, inherited));
if let Err(primary) = numerical {
resume_unwind(primary);
}
assert!(observation_disabled.is_ok(), "final capture observation cleanup failed");
assert!(moe_closed.is_ok(), "prefix MoE/MTP teardown failed");
assert!(dense_closed.is_ok(), "prefix dense teardown failed");
assert!(synchronized.is_ok(), "prefix final synchronization failed");
assert_eq!(allocated, 0, "prefix proof retained owned device buffers");
assert!(matches!(closed, Some(Ok(()))), "prefix Context teardown failed");
teardown.assert_clean();
eprintln!("grouped certified chunk proof teardown PASS allocated_bytes=0 context_closed=true");
}