STRA-338 size: split native_down_candidate_only into shared pair io, arm, owner, run and proof modules

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 13:37:11 +01:00
parent ad87e5b57d
commit 6a6433cbe3
7 changed files with 1300 additions and 1455 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,257 @@
//! One actual owner generation on a fresh target/draft state: bounded stream consumer, failure artifact and the
//! measurement record of a completed arm.
use super::*;
const WALL_BOUNDARY: &str = "immediately before generate_mtp_resume through terminal, actual channel EOF and \
consumer join; excludes session teardown and helpers";
pub(super) struct Arm {
pub(super) measurement: EvaluationMeasurement,
pub(super) text: String,
pub(super) usage: Usage,
pub(super) reason: FinishReason,
pub(super) request_wall: Duration,
pub(super) first_text: Option<Duration>,
}
fn window_json(w: &WindowWitness) -> Value {
json!({"draft_steps":w.draft_steps,"verified_ids":w.verified_ids,"verified_count":w.verified_count,
"authoritative_eos":w.authoritative_eos,"accepted_non_eos_drafts":w.accepted_non_eos_drafts})
}
fn usage_json(u: &Usage) -> Value {
json!({"input_tokens":u.input_tokens,"output_tokens":u.output_tokens,"reused_input_tokens":u.reused_input_tokens})
}
fn ns(duration: Duration) -> u64 {
u64::try_from(duration.as_nanos()).unwrap()
}
impl Arm {
pub(super) fn json(&self, phase: &str, policy: &str) -> Value {
let m = &self.measurement;
let windows: Vec<_> = m.windows.iter().map(window_json).collect();
json!({"phase":phase,"execution_policy":policy,"input_token_ids":m.input_token_ids,
"output_token_ids":m.output_token_ids,"retained_prefix_tokens":m.retained_prefix_tokens,
"prefill_ns":ns(m.prefill),"decode_ns":ns(m.decode),"request_wall_ns":ns(self.request_wall),
"first_text_ns":self.first_text.map(ns),
"wall_boundary":WALL_BOUNDARY,
"windows":windows,"cache_before":cache_json(m.cache_before),"cache_after":cache_json(m.cache_after),
"completed":m.completed,"stopped":m.stopped,"terminal_published":m.terminal_published,
"text":self.text,"usage":usage_json(&self.usage),"finish_reason":format!("{:?}",self.reason)})
}
pub(super) fn offered(&self) -> usize {
self.measurement.windows.iter().map(|w| w.draft_steps).sum()
}
}
pub(super) struct Inputs<'a, 'ctx, 'driver> {
pub(super) binding: &'a ModelBinding,
pub(super) output: &'a OutputStage<'ctx, 'driver>,
pub(super) kar: &'a mut KarPleCache<'ctx>,
pub(super) moe: &'a mut MoeWeightCache<'ctx>,
pub(super) dense: &'a DenseWeightCache<'ctx>,
pub(super) tokenizer: &'a Tokenizer,
pub(super) context: &'a Rc<leleka_cuda_driver::Context<'ctx>>,
pub(super) eos: u32,
pub(super) shared: Shared,
}
type Drained = (String, Option<Usage>, Option<GenerationTerminal>, Option<Instant>);
fn drain_stream(mut stream: GenerationStream) -> Drained {
let mut text = String::new();
let mut usage = None;
let mut terminal = None;
let mut first_text_at = None;
while let Some(event) = stream.recv().expect("pair stream missing terminal") {
match event {
GenerationEvent::TextDelta { text: delta } => {
if !delta.is_empty() && first_text_at.is_none() {
first_text_at = Some(Instant::now());
}
assert!(text.len() + delta.len() <= FRAME_LIMIT);
text.push_str(&delta);
}
GenerationEvent::Usage(value) => {
assert!(usage.replace(value).is_none());
}
GenerationEvent::Terminal(value) => {
assert!(terminal.replace(value).is_none());
}
GenerationEvent::ToolCallDelta { .. } => {
panic!("text-only public pair emitted unexpected typed tool")
}
}
}
(text, usage, terminal, first_text_at)
}
/// The channel, its consumer thread, the measurement recorder and the request clock of one arm.
struct Running {
sink: GenerationSink,
drain: thread::JoinHandle<Drained>,
recorder: std::cell::RefCell<measurement::Recorder>,
cancel: AtomicBool,
started: Instant,
}
impl Running {
fn open(ids: &[u32], max_output_tokens: u32) -> Self {
let cancel = AtomicBool::new(false);
let (sink, stream) = GenerationSink::bounded_channel(QUEUE).expect("actual pair channel refused");
let drain = thread::spawn(move || drain_stream(stream));
let recorder = std::cell::RefCell::new(measurement::Recorder::new(ids, max_output_tokens));
Running { sink, drain, recorder, cancel, started: Instant::now() }
}
}
/// What the failure artifact records besides the progress of the recorder.
struct FailureFacts<'a> {
terminal: &'a GenerationTerminal,
published: bool,
consumer_failed: bool,
drained: &'a Drained,
request_wall: Duration,
started: Instant,
/// Allocated bytes, budget bytes and whether this was the Native control arm.
device: (usize, usize, bool),
}
fn failure_json(facts: &FailureFacts<'_>, progress: (&[u32], usize, bool), phase: &str) -> Value {
let (text, seen_usage, seen_terminal, first_text_at) = facts.drained;
json!({"terminal":format!("{:?}", facts.terminal),"terminal_published":facts.published,
"terminal_seen_matches":seen_terminal.as_ref()==Some(facts.terminal),
"consumer_failed":facts.consumer_failed,"usage_seen":seen_usage.as_ref().map(usage_json),
"public_text":text,"text_bytes":text.len(),"actual_observed_output_ids":progress.0,
"window_count":progress.1,"prefill_completed":progress.2,"phase":phase,
"request_wall_ns":ns(facts.request_wall),
"first_text_ns":first_text_at.map(|at|ns(at.duration_since(facts.started))),
"allocated_at_failure":facts.device.0,"device_budget_bytes":facts.device.1,
"is_native_control":facts.device.2})
}
fn terminal_of(failure: GenerationFailure) -> GenerationTerminal {
match failure {
GenerationFailure::Cancelled => GenerationTerminal::Cancelled,
GenerationFailure::Backend(error) => {
GenerationTerminal::Failed { code: error.code, message: error.message, retryable: false }
}
}
}
impl<'ctx, 'driver> Inputs<'_, 'ctx, 'driver> {
fn announce(&self, phase: &str, execution: EvaluationExecution) {
eprintln!(
"PUBLIC arm-start phase={phase} is_native_control={} allocated={} budget={}",
execution == EvaluationExecution::Native,
self.context.allocated_bytes(),
self.context.budget_bytes()
);
}
/// Publishes the terminal, joins the consumer and keeps a bounded artifact; never returns.
fn fail(&self, run: Running, failure: GenerationFailure, phase: &str, execution: EvaluationExecution) -> ! {
let terminal = terminal_of(failure);
let diagnostic = format!("{terminal:?}");
let published = emit_terminal(&run.sink, terminal.clone(), &SystemClock).is_ok();
drop(run.sink);
let joined = run.drain.join();
let consumer_failed = joined.is_err();
let drained = joined.unwrap_or_default();
let request_wall = run.started.elapsed();
let progress = run.recorder.borrow();
let device =
(self.context.allocated_bytes(), self.context.budget_bytes(), execution == EvaluationExecution::Native);
let facts = FailureFacts {
terminal: &terminal,
published,
consumer_failed,
drained: &drained,
request_wall,
started: run.started,
device,
};
let artifact = failure_json(&facts, progress.diagnostic_progress(), phase);
save(&path("LELEKA_STRA169_PAIR_OUTPUT"), "GENERATION-FAILURE.json", &artifact);
eprintln!("PUBLIC generation terminal={diagnostic}");
panic!("actual public pair generation failed; bounded failure artifact retained");
}
fn generation<'a>(
&'a mut self,
run: &'a Running,
session: &'a mut QwenSession<'ctx>,
execution: EvaluationExecution,
) -> Generation<'a, 'ctx, 'driver, SystemClock> {
Generation {
measurement: Some(&run.recorder),
execution,
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: &run.sink,
cancel: &run.cancel,
shared: &self.shared,
context_tokens: 262144,
eos: self.eos,
mtp: true,
clock: SystemClock,
}
}
pub(super) fn arm(
&mut self,
req: &GenerationRequest,
ids: &[u32],
execution: EvaluationExecution,
phase: &'static str,
) -> Arm {
self.announce(phase, execution);
// Fresh genuine target state and fresh actual decoder. No position reset,
// invented prefix, checkpoint reuse or cached-token count substitution.
let mut session = QwenSession::for_binding_on_shared_device(self.binding, Rc::clone(self.context));
let before = cache(self.moe.counters(), self.dense.counters());
let run = Running::open(ids, req.max_output_tokens);
let mut pending = None;
let generation = self.generation(&run, &mut session, execution);
let result = generate_mtp_resume(generation, ids, req.max_output_tokens, None, &mut pending);
let (reason, usage) = match result {
Ok(value) => value,
Err(failure) => self.fail(run, failure, phase, execution),
};
self.finish(run, (reason, usage), (pending, session), before, ids)
}
fn assert_ready(&self, cancel: &AtomicBool) {
assert!(!cancel.load(Ordering::Acquire));
assert!(self.shared.ready.load(Ordering::Acquire));
assert!(!self.shared.shutdown.load(Ordering::Acquire));
}
fn measure(
&self,
recorder: std::cell::RefCell<measurement::Recorder>,
before: CacheCounts,
(reason, usage): (&FinishReason, &Usage),
published: bool,
) -> EvaluationMeasurement {
let stopped = matches!(reason, FinishReason::Stop);
let usage_ids = Some((usage.input_tokens, usage.output_tokens, usage.reused_input_tokens));
let after = cache(self.moe.counters(), self.dense.counters());
recorder
.into_inner()
.finish(before, after, true, stopped, published, usage_ids)
.expect("actual owner measurement refused")
}
fn finish(
&self,
run: Running,
(reason, usage): (FinishReason, Usage),
(pending, session): (Option<MtpContinuation>, QwenSession<'ctx>),
before: CacheCounts,
ids: &[u32],
) -> Arm {
let terminal = GenerationTerminal::Completed { reason: reason.clone(), usage: usage.clone() };
let published = emit_terminal(&run.sink, terminal.clone(), &SystemClock).is_ok();
drop(run.sink);
let (text, seen_usage, seen_terminal, first_text_at) = run.drain.join().expect("actual pair consumer failed");
let request_wall = run.started.elapsed();
let first_text = first_text_at.map(|at| at.duration_since(run.started));
assert!(published && seen_terminal.as_ref() == Some(&terminal));
assert!(seen_usage.as_ref() == Some(&usage));
self.assert_ready(&run.cancel);
drop(pending);
drop(session);
let measured = self.measure(run.recorder, before, (&reason, &usage), published);
assert_eq!(measured.input_token_ids, ids);
assert_eq!(measured.retained_prefix_tokens, 0);
Arm { measurement: measured, text, usage, reason, request_wall, first_text }
}
}
@@ -0,0 +1,111 @@
//! The retained completed Native arm and the checks of the MTP window witnesses of a candidate arm.
use super::*;
pub(super) const BASELINE_SHA: &str = "4d61ee949d37a738500c889f23f07310b6d75c7c8dfe5f50173eceafe1882fbe";
pub(super) struct Baseline {
pub(super) input_ids: Vec<u32>,
pub(super) output_ids: Vec<u32>,
pub(super) text: String,
}
pub(super) fn token_ids(value: &Value) -> Vec<u32> {
value
.as_array()
.expect("actual baseline token array missing")
.iter()
.map(|v| u32::try_from(v.as_u64().expect("baseline token is not u32")).unwrap())
.collect()
}
fn assert_baseline_header(v: &Value) {
assert_eq!(v["phase"], json!("warm"));
assert_eq!(v["execution_policy"], json!("native64-same-dual-cache-retained-mtp-kv"));
assert_eq!(v["completed"], json!(true));
assert_eq!(v["terminal_published"], json!(true));
assert_eq!(v["stopped"], json!(false));
assert_eq!(v["finish_reason"], json!("Length"));
assert_eq!(v["retained_prefix_tokens"], json!(0));
assert_eq!(v["usage"], json!({"input_tokens":202,"output_tokens":32,"reused_input_tokens":0}));
}
/// Checks one window witness of the baseline and appends its active ids; returns (offered, accepted).
fn baseline_window(w: &Value, active: &mut Vec<u32>) -> (u64, u64) {
let steps = w["draft_steps"].as_u64().unwrap();
let count = usize::try_from(w["verified_count"].as_u64().unwrap()).unwrap();
let ids = token_ids(&w["verified_ids"]);
assert_eq!(ids.len(), 4);
assert!((1..=4).contains(&steps) && (1..=4).contains(&count));
assert!(u64::try_from(count).unwrap() <= steps);
assert_eq!(w["authoritative_eos"], json!(false));
let matched = w["accepted_non_eos_drafts"].as_u64().unwrap();
assert_eq!(matched, u64::try_from(count - 1).unwrap());
active.extend_from_slice(&ids[..count]);
(steps, matched)
}
/// Validates the actual active window witnesses, excluding unused padding IDs.
fn assert_baseline_windows(windows: &Value, output_ids: &[u32]) {
let mut active = Vec::new();
let mut offered = 0u64;
let mut accepted = 0u64;
for w in windows.as_array().unwrap() {
let (steps, matched) = baseline_window(w, &mut active);
offered += steps;
accepted += matched;
}
assert_eq!(active.len(), 31);
assert_eq!(active, output_ids[..31]);
assert_eq!(offered, 31);
assert_eq!(accepted, 23);
}
pub(super) fn baseline() -> Baseline {
// This is the retained completed Native arm, not the failed whole campaign.
// Root separately retains its source/model/request transfer provenance.
let bytes = sealed_bytes("LELEKA_STRA169_NATIVE_BASELINE", 65536, "sealed retained Native baseline required");
assert_eq!(sha(&bytes), BASELINE_SHA);
let v: Value = serde_json::from_slice(&bytes).unwrap();
assert_baseline_header(&v);
let input_ids = token_ids(&v["input_token_ids"]);
let output_ids = token_ids(&v["output_token_ids"]);
assert_eq!(input_ids.len(), 202);
assert_eq!(output_ids.len(), 32);
let text = v["text"].as_str().unwrap().to_owned();
assert!(text.len() <= FRAME_LIMIT);
assert_baseline_windows(&v["windows"], &output_ids);
Baseline { input_ids, output_ids, text }
}
/// A window with no draft capacity is only the single anchor before the reserved final public token.
fn assert_zero_draft_anchor(w: &WindowWitness, index: usize, count: usize, active: usize, outputs: usize) {
// generate_mtp_resume reserves one final public authoritative token
// outside the windows. Only its preceding single anchor can have
// no available draft capacity. Padding is never an output token.
assert_eq!(index + 1, count);
assert_eq!(w.verified_count, 1);
assert_eq!(w.accepted_non_eos_drafts, 0);
assert_eq!(active + 1, outputs - 1);
}
pub(super) fn checked_candidate_window_prefix(windows: &[WindowWitness], output_ids: &[u32]) -> (usize, usize) {
assert!(!output_ids.is_empty());
let mut active = Vec::new();
let mut offered = 0usize;
let mut accepted = 0usize;
for (index, w) in windows.iter().enumerate() {
assert!((1..=4).contains(&w.verified_count));
assert!(!w.authoritative_eos);
assert_eq!(w.accepted_non_eos_drafts, w.verified_count - 1);
if w.draft_steps == 0 {
assert_zero_draft_anchor(w, index, windows.len(), active.len(), output_ids.len());
} else {
assert!((1..=4).contains(&w.draft_steps));
assert!(w.verified_count - 1 <= w.draft_steps);
}
active.extend_from_slice(&w.verified_ids[..w.verified_count]);
offered += w.draft_steps;
accepted += w.accepted_non_eos_drafts;
}
assert_eq!(active.len(), output_ids.len() - 1);
assert_eq!(active, output_ids[..active.len()]);
(offered, accepted)
}
pub(super) fn candidate_windows(candidate: &Arm) -> (usize, usize) {
let counts =
checked_candidate_window_prefix(&candidate.measurement.windows, &candidate.measurement.output_token_ids);
assert_eq!(counts.0, candidate.offered());
counts
}
@@ -0,0 +1,141 @@
//! Files, environment, request framing and counters shared by the PUBLIC pair proofs.
//! Included by `native_down_candidate_only.rs` and `native_down_public_pair.rs` (each owns its copy of the state).
use super::*;
pub(super) const ARTIFACT_CAP: usize = 16 * 1024 * 1024;
pub(super) static ARTIFACT_BYTES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
pub(super) const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024;
pub(super) const CAP: u32 = 32;
const INSTRUCTIONS: &str = "Use only the public document. Preserve the requested word order.";
const SEQUENCE: &str = "Return this public sequence once, without explanation: amber birch cedar delta elm fern \
grove hazel iris jade kelp lake moss north oak pine quartz reed sage thyme umber vale willow xenon yew zinc \
amber birch cedar delta elm fern.";
const METADATA_KEYS: [&str; 8] = [
"engine_source_sha256",
"evaluation_binary_sha256",
"gpu",
"driver",
"cuda",
"power_limit_w",
"clocks",
"context_tokens",
];
pub(super) fn reserve_artifacts(bytes: usize) -> std::io::Result<()> {
ARTIFACT_BYTES
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| {
current.checked_add(bytes).filter(|next| *next <= ARTIFACT_CAP)
})
.map(|_| ())
.map_err(|_| std::io::Error::other("whole public pair artifact cap exceeded"))
}
pub(super) fn path(name: &str) -> PathBuf {
env::var_os(name).map(PathBuf::from).expect("missing ROOT-owned public pair path")
}
pub(super) fn sha(bytes: &[u8]) -> String {
Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect()
}
pub(super) fn save(root: &std::path::Path, name: &str, value: &Value) {
let bytes = serde_json::to_vec(value).expect("public pair JSON encoding failed");
assert!(bytes.len() <= 1024 * 1024);
reserve_artifacts(bytes.len().checked_add(1).expect("JSON newline extent overflow"))
.expect("whole public pair serialized budget exceeded");
let mut f = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(root.join(name))
.expect("fresh public pair output required");
f.write_all(&bytes).unwrap();
f.write_all(b"\n").unwrap();
f.sync_data().unwrap();
}
/// Reads a sealed regular file of at most `limit` bytes; `what` is the refusal message of the open.
pub(super) fn sealed_bytes(env_name: &str, limit: usize, what: &str) -> Vec<u8> {
let mut f = OpenOptions::new().read(true).custom_flags(0x20000 | 0x800).open(path(env_name)).expect(what);
assert!(f.metadata().unwrap().is_file());
let mut bytes = Vec::new();
std::io::Read::by_ref(&mut f).take(limit as u64 + 1).read_to_end(&mut bytes).unwrap();
assert!(bytes.len() <= limit);
bytes
}
pub(super) fn cache(
m: crate::qwen_forward::moe_weight_cache::WeightCacheCounters,
d: crate::qwen_forward::dense_weight_cache::DenseCacheCounters,
) -> CacheCounts {
CacheCounts {
expert_hits: m.hits,
expert_misses: m.misses,
expert_source_bytes: m.read_bytes,
expert_upload_bytes: m.upload_bytes,
expert_eviction_bytes: m.eviction_bytes,
dense_hits: d.hits,
dense_source_bytes: d.read_bytes,
dense_upload_bytes: d.upload_bytes,
}
}
pub(super) fn cache_json(c: CacheCounts) -> Value {
json!({
"expert_hits":c.expert_hits,"expert_misses":c.expert_misses,"expert_source_bytes":c.expert_source_bytes,
"expert_upload_bytes":c.expert_upload_bytes,"expert_eviction_bytes":c.expert_eviction_bytes,
"dense_hits":c.dense_hits,"dense_source_bytes":c.dense_source_bytes,"dense_upload_bytes":c.dense_upload_bytes
})
}
fn document(lines: usize) -> String {
let mut document =
String::from("PUBLIC deterministic evaluation document; no private agent content.\nTicket LV-17 is READY.\n");
for index in 0..lines {
document.push_str(&format!("Record {index}: LV-17 has priority 3; status READY; owner PUBLIC.\n"));
}
document.push_str(SEQUENCE);
document
}
fn render(document: &str) -> String {
let message = |role, content| public_renderer::Message { role, content, reasoning: None, parts: None };
public_renderer::render(
&[message(public_renderer::Role::System, INSTRUCTIONS), message(public_renderer::Role::User, document)],
public_renderer::Effort::None,
)
.expect("actual daemon public renderer refused")
}
fn canonical(document: &str) -> Value {
json!({"model":"pinned-native-model","instructions":INSTRUCTIONS,"input":document,"tools":[],
"max_output_tokens":CAP,"temperature":0,"stream":true,"store":false})
}
pub(super) fn request(tokenizer: &Tokenizer) -> (GenerationRequest, Vec<u32>, Value) {
for lines in 1..=64 {
let document = document(lines);
let prompt = render(&document);
let req = GenerationRequest {
request_id: "public-paired-owner-generation".into(),
prompt,
max_output_tokens: CAP,
temperature_milli: 0,
sampling: Default::default(),
};
let ids = prepare_prompt(tokenizer, &req, 262144).expect("actual pinned tokenizer refused public frame");
if (193..=256).contains(&ids.len()) {
return (req, ids, canonical(&document));
}
assert!(
ids.len() <= 256,
"public framing jumped past the predeclared193..256 intake; do not fit a token surrogate"
);
}
panic!("public framed193..256 token request unavailable");
}
pub(super) fn metadata() -> Value {
let b = sealed_bytes("LELEKA_STRA169_PAIR_METADATA", 16384, "ROOT public measurement metadata required");
assert_eq!(
sha(&b),
env::var("LELEKA_STRA169_PAIR_METADATA_SHA").expect("ROOT exact public metadata digest required")
);
let value: Value = serde_json::from_slice(&b).unwrap();
let o = value.as_object().expect("public metadata object required");
for key in METADATA_KEYS {
assert!(o.get(key).is_some_and(|v| !v.is_null()), "actual hardware/profile metadata required");
}
assert!(o.keys().all(|k| METADATA_KEYS.contains(&k.as_str())));
assert_eq!(o["context_tokens"], json!(262144));
value
}
@@ -0,0 +1,310 @@
//! The one loaded owner of the PUBLIC candidate proofs: admission of the sealed inputs, the load, the ordered
//! teardown and the artifacts of it. The proofs differ only in the `Proof` hooks (`native_down_pair_proofs.rs`).
use super::*;
use crate::qwen_forward::owner_wall_profile::{self, Sample};
use leleka_model_format::qwen4exp::{ProvisionalExpertSource, ResidentExpertSourceReport};
use std::os::unix::fs::PermissionsExt;
const PROFILE_LEN: usize = 196_632;
/// One failed or passed assertion that is decided at teardown and asserted afterwards.
pub(super) type Check = (bool, &'static str);
pub(super) struct Case {
pub(super) req: GenerationRequest,
pub(super) ids: Vec<u32>,
}
/// What a proof reports of its cache owners: the profile JSON and the assertions on the witnesses.
pub(super) struct MoeFacts {
pub(super) json: Option<Value>,
pub(super) checks: Vec<Check>,
}
/// Borrowed state a generation needs besides the loaded owner.
pub(super) struct RunCtx<'a, 'ctx> {
pub(super) binding: &'a ModelBinding,
pub(super) tokenizer: &'a Tokenizer,
pub(super) context: &'a Rc<leleka_cuda_driver::Context<'ctx>>,
pub(super) eos: u32,
pub(super) case: &'a Case,
}
/// What the finished proof is judged on, after every attempted teardown.
pub(super) struct Finish<R> {
pub(super) root: PathBuf,
pub(super) hardware: Value,
pub(super) baseline: Baseline,
pub(super) case: Case,
pub(super) driver_version: Value,
pub(super) report: R,
pub(super) recorded: Value,
pub(super) td: Teardown,
}
pub(super) trait Proof {
type Report;
/// Opens shard 0 with the incremental expert capture.
fn incremental_capture(&self) -> bool {
false
}
fn dense<'c>(&self, binding: &ModelBinding, context: &'c leleka_cuda_driver::Context<'_>) -> DenseWeightCache<'c>;
fn moe<'c>(
&self,
binding: &ModelBinding,
context: &'c leleka_cuda_driver::Context<'_>,
profile: &[u8],
) -> MoeWeightCache<'c>;
fn generate<'ctx>(&self, owner: &mut Owner<'ctx, '_>, run: &RunCtx<'_, 'ctx>) -> Self::Report;
fn moe_facts(&self, moe: &MoeWeightCache<'_>, binding: &ModelBinding, preload_ns: u128) -> MoeFacts;
fn dense_check(&self, _dense: &DenseWeightCache<'_>) -> Option<Check> {
None
}
/// The cache counters before the first and after the last request of the report.
fn cache_bounds(report: &Self::Report) -> (Value, Value);
/// Saves the report artifact; returns the JSON saved.
fn record(&self, root: &std::path::Path, report: &Self::Report) -> Value;
fn after_teardown(&self, _report: &mut Self::Report) {}
fn conclude(&self, finish: Finish<Self::Report>);
}
fn prepare_root() -> PathBuf {
let root = path("LELEKA_STRA169_PAIR_OUTPUT");
assert!(root.is_absolute() && !root.exists());
assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap());
std::fs::create_dir(&root).unwrap();
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap();
root
}
fn inherited_fd() -> u32 {
// Existing identical GDN recurrence was qualified in cdb5ec8a and current15b3.
// Root runs only the new GDN full-products entry in this component cohort.
let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").unwrap().parse().unwrap();
assert!((3..=1048576).contains(&fd));
fd
}
fn open_artifact(fd: u32, incremental: bool) -> (Qwen4ExpArtifact, ProvisionalExpertSource, u128) {
// Observation only. Missing/invalid inherited FD defers capture refusal;
// the original later InheritedKarArchive gate remains authoritative.
let observed_kar = std::fs::File::open(format!("/proc/self/fd/{fd}")).ok();
let shard0_started = Instant::now();
let shard0_path = path("LELEKA_STRA169_IQ3S_SHARD0");
let opened = if incremental {
Qwen4ExpArtifact::open_shard0_with_expert_capture_incremental(&shard0_path, SHARD0, observed_kar.as_ref())
} else {
Qwen4ExpArtifact::open_shard0_with_expert_capture(&shard0_path, SHARD0, observed_kar.as_ref())
};
let (shard0, capture) = opened.expect("pinned shard0 failed");
let capture_ns = shard0_started.elapsed().as_nanos();
drop(observed_kar);
let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 failed");
let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact failed");
(artifact, capture, capture_ns)
}
fn pinned_tokenizer(artifact: &Qwen4ExpArtifact) -> (Tokenizer, u32) {
let m = artifact.tokenizer();
let tokenizer =
Tokenizer::from_vocabulary(&m.model, &m.pre, m.tokens.clone(), m.merges.clone(), m.token_types.clone())
.expect("actual pinned tokenizer failed");
let eos = *m.special_ids.get("tokenizer.ggml.eos_token_id").unwrap();
(tokenizer, eos)
}
fn renderer_sha() -> String {
sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs"))
}
fn baseline_admission_json() -> Value {
json!({"baseline_sha256":BASELINE_SHA,"retained_run":"24993ad2-9c7c-4a90-bfac-3e6e0b5685c1",
"retained_source_sha256":"ea8b6183c4f9bb5851054f908913d87b06c896c6408e8b737b97da77e3aba7e1",
"actual_baseline_phase":"warm","model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,
"renderer_source_sha256":renderer_sha(),"framed_ids_match":true,"context_tokens":262144,
"temperature_milli":0,"max_output_tokens":CAP,"historical_timing_used":false,
"baseline_campaign_succeeded":false})
}
fn frame_json(case: &Case) -> Value {
json!({"renderer_source_sha256":renderer_sha(),"framed_prompt":case.req.prompt,
"framed_prompt_sha256":sha(case.req.prompt.as_bytes()),"input_token_ids":case.ids,
"framed_count":case.ids.len(),"model_digest":MODEL_DIGEST,"max_output_tokens":CAP,"temperature_milli":0})
}
fn admit_request(root: &std::path::Path, tokenizer: &Tokenizer, baseline: &Baseline) -> Case {
let (req, ids, canonical) = request(tokenizer);
assert_eq!(ids, baseline.input_ids);
assert_eq!(ids.len(), 202);
let case = Case { req, ids };
save(root, "BASELINE-ADMISSION.json", &baseline_admission_json());
save(root, "PUBLIC-REQUEST.json", &canonical);
save(root, "FRAME.json", &frame_json(&case));
case
}
fn bind_model(artifact: Qwen4ExpArtifact, inherited: &InheritedKarArchive) -> ModelBinding {
ModelBinding::from_artifact_with_inherited_kar_mtp(
artifact,
inherited,
&path("LELEKA_STRA169_MTP_PACK"),
&path("LELEKA_STRA169_MTP_STAGING"),
)
.expect("actual KAR MTP binding failed")
}
pub(super) fn bank_json(r: &ResidentExpertSourceReport) -> Value {
json!({"source_bytes":r.source_bytes,"charged_bytes":r.charged_bytes,"bank_count":r.bank_count,
"source_cap_bytes":r.source_cap_bytes,"observed_mem_available_bytes":r.observed_mem_available_bytes,
"future_headroom_bytes":r.future_headroom_bytes,"shard0_sha256_bytes":r.shard0_sha256,
"completed_logical_copy_spans":r.copied_spans,"completed_logical_copy_bytes":r.copied_bytes,
"disk_io_claim":false,"raw_bytes_only_not_finite_certificate":true})
}
fn adopt_bank(root: &std::path::Path, binding: &mut ModelBinding, capture: ProvisionalExpertSource, capture_ns: u128) {
// Selected fresh binding only, before Driver/profile/session publication.
let bank_started = Instant::now();
let r = binding.adopt_resident_expert_capture(capture).expect("actual resident expert RAM bank admission failed");
let bank_load_ns = bank_started.elapsed().as_nanos();
save(
root,
"BANK-ADMISSION.json",
&json!({"load_ns":bank_load_ns,"shard0_digest_capture_ns":capture_ns,
"source_transport":"same-fd-full-sha-opaque-capture","report":bank_json(&r)}),
);
}
/// The sealed ranked expert profile: the open file stays until the caches have been built from its bytes.
pub(super) struct Profile {
file: std::fs::File,
bytes: Vec<u8>,
}
impl Profile {
fn open() -> Self {
let mut file = OpenOptions::new()
.read(true)
.custom_flags(0x20000)
.open(path("LELEKA_STRA169_EXPERT_PROFILE"))
.expect("ROOT pinned STRP profile required");
assert!(file.metadata().unwrap().is_file());
assert_eq!(file.metadata().unwrap().len(), PROFILE_LEN as u64);
let mut bytes = Vec::new();
bytes.try_reserve_exact(PROFILE_LEN).expect("bounded profile allocation failed");
Read::by_ref(&mut file).take(PROFILE_LEN as u64 + 1).read_to_end(&mut bytes).unwrap();
assert_eq!(bytes.len(), PROFILE_LEN);
crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&bytes)
.expect("pure pinned profile admission failed before Driver");
Profile { file, bytes }
}
fn release(self) {
drop(self.file);
drop(self.bytes);
}
}
/// Everything admitted on the host before the Driver is loaded.
pub(super) struct Host {
pub(super) root: PathBuf,
pub(super) hardware: Value,
pub(super) baseline: Baseline,
pub(super) tokenizer: Tokenizer,
pub(super) eos: u32,
pub(super) case: Case,
pub(super) binding: ModelBinding,
pub(super) inherited: InheritedKarArchive,
pub(super) profile: Profile,
}
impl Host {
pub(super) fn admit(proof: &impl Proof) -> Host {
assert_eq!(env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), Ok("yes"));
let baseline = baseline();
let hardware = metadata();
let root = prepare_root();
let fd = inherited_fd();
let (artifact, capture, capture_ns) = open_artifact(fd, proof.incremental_capture());
let (tokenizer, eos) = pinned_tokenizer(&artifact);
let case = admit_request(&root, &tokenizer, &baseline);
let inherited =
InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited sealed KAR failed");
let mut binding = bind_model(artifact, &inherited);
let profile = Profile::open();
adopt_bank(&root, &mut binding, capture, capture_ns);
Host { root, hardware, baseline, tokenizer, eos, case, binding, inherited, profile }
}
}
/// The loaded caches and output head of the one admitted owner.
pub(super) struct Owner<'ctx, 'driver> {
pub(super) output: OutputStage<'ctx, 'driver>,
pub(super) kar: KarPleCache<'ctx>,
pub(super) dense: DenseWeightCache<'ctx>,
pub(super) moe: MoeWeightCache<'ctx>,
preload_ns: u128,
}
/// The counters read from the caches before they are closed.
pub(super) struct OwnerCounters {
pub(super) shared_tail_rows: u64,
pub(super) lru: (u64, u64, u64),
pub(super) lru_metadata_bytes: Option<usize>,
pub(super) mtp_input: u64,
pub(super) router_rows: Option<u64>,
pub(super) gr_batch: u64,
pub(super) compact_head: u64,
}
/// What the ordered teardown of the owner established.
pub(super) struct Witnessed {
pub(super) oracle_disabled: bool,
pub(super) moe_closed: bool,
pub(super) dense_closed: bool,
pub(super) counters: OwnerCounters,
pub(super) facts: MoeFacts,
pub(super) dense_check: Option<Check>,
}
pub(super) struct Teardown {
pub(super) head: Witnessed,
pub(super) synchronized: bool,
pub(super) allocated: usize,
pub(super) context_closed: bool,
pub(super) bank_after: Option<ResidentExpertSourceReport>,
pub(super) owner_wall: Result<[Sample; 6], &'static str>,
}
impl<'ctx, 'driver> Owner<'ctx, 'driver> {
pub(super) fn load<P: Proof>(
proof: &P,
binding: &ModelBinding,
context: &'ctx leleka_cuda_driver::Context<'driver>,
profile: Profile,
) -> Self {
let output = OutputStage::load_compact(binding, context).unwrap();
let kar = KarPleCache::new(context, binding.kar_ple_binding().unwrap()).unwrap();
// Profile admission observes all eager Dense/QSA/router and MTP owners.
let dense = proof.dense(binding, context);
let preload_started = Instant::now();
let moe = proof.moe(binding, context, &profile.bytes);
let preload_ns = preload_started.elapsed().as_nanos();
profile.release();
Owner { output, kar, dense, moe, preload_ns }
}
/// The borrowed inputs of the actual generation, with the owner wall profile armed.
pub(super) fn armed_inputs<'a>(&'a mut self, run: &RunCtx<'a, 'ctx>) -> Inputs<'a, 'ctx, 'driver> {
let inputs = Inputs {
binding: run.binding,
output: &self.output,
kar: &mut self.kar,
moe: &mut self.moe,
dense: &self.dense,
tokenizer: run.tokenizer,
context: run.context,
eos: run.eos,
shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) },
};
owner_wall_profile::arm().expect("actual owner wall profile admission failed");
inputs
}
/// Witnesses, then closes the caches and the output head, in the order of the original proofs.
pub(super) fn teardown<P: Proof>(self, proof: &P, binding: &ModelBinding) -> Witnessed {
let Owner { output, kar, dense, moe, preload_ns } = self;
let oracle_disabled = crate::qwen_forward::oracle_capture::disable(&output).is_ok();
let shared_tail_rows = moe.test_shared_tail_witness();
let lru = moe.test_lru_witness();
let lru_metadata_bytes = moe.test_lru_metadata_bytes().ok();
let facts = proof.moe_facts(&moe, binding, preload_ns);
let mtp_input = moe.test_mtp_input_completions();
let moe_closed = moe.close().is_ok();
let router_rows = dense.test_router_witness().ok();
let gr_batch = dense.test_gr_batch_completions();
let dense_check = proof.dense_check(&dense);
let dense_closed = dense.close().is_ok();
drop(kar);
let compact_head = output.test_compact_completions();
drop(output);
let counters =
OwnerCounters { shared_tail_rows, lru, lru_metadata_bytes, mtp_input, router_rows, gr_batch, compact_head };
Witnessed { oracle_disabled, moe_closed, dense_closed, counters, facts, dense_check }
}
}
@@ -0,0 +1,291 @@
//! The four PUBLIC candidate proofs: they differ in the caches they load, in what they generate and in what
//! they conclude; the owner, the teardown and the artifacts are shared (`native_down_pair_run.rs`).
use super::*;
use crate::qwen_forward::moe_weight_cache::LearnedMainWitness;
use fivecase_runtime::FiveCaseReport;
const METADATA_CAP: usize = 16 * 1024 * 1024;
const CASE_STATE: &str = "no replayed helper; actual per-case before/after counters; \
same loaded owners but fresh target/draft each request";
const DIRECT_STATE: &str = "fresh target+draft sessions after original-first changed direct Down layer0 helper; \
helper-warmed kernel/module/L0 scratch/KAR row-source/MoE expert-cache; actual generation cache_before \
measured after that helper; ranked prefix/preload separately reported, not cold hardware";
const DIRECT_PHASE: &str = "candidate-only-new-slowpaths-fixed-draft-selected-QSA-queued-target-shared-tail-\
pinned-profile-spill-router-scratch";
fn pinned_facts(moe: &MoeWeightCache<'_>, preload_ns: u128) -> MoeFacts {
let witness = moe.test_profile_witness();
let json = witness.as_ref().ok().map(|w| {
json!({
"profile_sha256":"8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf",
"complete_pinned_experts":w.prefix,"pinned_bytes":w.pinned_bytes,"spill_bytes":w.spill_bytes,
"post_preload_source_read_bytes_including_shared":w.post_preload_read_bytes,
"post_preload_upload_bytes_including_shared":w.post_preload_upload_bytes,
"spill_reserve":w.spill_reserve,"largest_triplet":w.largest_triplet,
"metadata_bytes":w.metadata_bytes,"main_slot_limit":w.main_slot_limit,
"fixed_resident_upload_bytes_before_profile":w.fixed_resident_upload_bytes,
"pinned_hits":w.pinned_hits,"spill_hits":w.spill_hits,
"spill_misses":w.spill_misses,"preload_read_bytes":w.preload_read_bytes,
"preload_upload_bytes":w.preload_upload_bytes,"preload_ns":preload_ns,
"preload_in_generation_timing":false,"normal_defaults_changed":false
})
});
let ok = witness.is_ok_and(|w| w.prefix > 0 && w.pinned_hits > 0 && w.metadata_bytes <= METADATA_CAP);
MoeFacts { json, checks: vec![(ok, "actual bounded pinned profile owner/hit witness missing")] }
}
fn learned_json(w: &LearnedMainWitness, shared_valid: bool, preload_ns: u128) -> Value {
json!({
"policy":"learned-main-lru-shared192", "routed_matrices":w.routed_matrices,
"routed_bytes":w.routed_bytes,"shared_matrices":w.shared_matrices,"shared_bytes":w.shared_bytes,
"main_bytes":w.main_bytes,"main_slot_limit":w.main_slot_limit,"metadata_bytes":w.metadata_bytes,
"historical_prefix":w.historical_prefix,"historical_routed_preload_bytes":w.historical_routed_preload_bytes,
"age":w.age,"preload_ns":preload_ns,"normal_defaults_changed":false,
"shared_witness_valid":shared_valid
})
}
fn learned_facts(moe: &MoeWeightCache<'_>, binding: &ModelBinding, preload_ns: u128) -> MoeFacts {
let witness = moe.learned_main_witness(binding);
let shared = moe.shared_permanent_witness();
let json = witness.as_ref().ok().map(|w| learned_json(w, shared.is_ok(), preload_ns));
let ok =
witness.is_ok_and(|w| w.routed_matrices > 0 && w.shared_matrices == 192 && w.metadata_bytes <= METADATA_CAP);
let checks = vec![
(ok, "actual learned main owner witness missing"),
(shared.is_ok(), "actual shared owner role witness missing"),
];
MoeFacts { json, checks }
}
/// The candidate-only proof: the changed direct Down packet proof, then one candidate arm
/// against the retained Native arm.
pub(super) struct DirectDown;
pub(super) struct Direct {
arm: Arm,
/// The teardown assertion of the loaded direct Down report.
down: Option<Box<dyn FnOnce()>>,
}
fn direct_parity(arm: &Arm, baseline: &Baseline) -> bool {
arm.measurement.output_token_ids == baseline.output_ids
&& arm.text == baseline.text
&& matches!(arm.reason, FinishReason::Length)
&& arm.usage.input_tokens == 202
&& arm.usage.output_tokens == 32
&& arm.usage.reused_input_tokens == 0
}
fn direct_head_json(f: &Finish<Direct>, parity: bool, ids_len: usize) -> Value {
json!({"scope":"one fresh candidate owner generation compared with retained completed actual Native arm; \
excludes historical paired timing","baseline_sha256":BASELINE_SHA,"model_digest":MODEL_DIGEST,
"profile":KAR_MTP_PROFILE,"hardware":f.hardware,"actual_cuda_driver_version":f.driver_version,
"context_tokens":262144,"framed_tokens":ids_len,"output_cap":CAP,"same_request_token_ids":true,
"greedy_output_ids_text_finish_usage_equal":parity,"actual_pinned_profile":f.td.head.facts.json})
}
fn direct_tail_json(f: &Finish<Direct>, offered: usize, accepted: usize) -> Value {
let m = &f.report.arm.measurement;
json!({"actual_mtp_offered":offered,"actual_non_eos_drafts_accepted":accepted,"completed":m.completed,
"terminal_published":m.terminal_published,"retained_prefix_tokens":m.retained_prefix_tokens,
"cache_state":DIRECT_STATE,"historical_speed_ratio":null,"GateC":false,"GateD":false,
"HTTP_endagent_speed_claim":false,"longcontext_170K":false,"allocated":f.td.allocated,
"cleanup_complete":true})
}
impl Proof for DirectDown {
type Report = Direct;
fn dense<'c>(&self, binding: &ModelBinding, context: &'c leleka_cuda_driver::Context<'_>) -> DenseWeightCache<'c> {
DenseWeightCache::new_qsa_selected_router_gr_batch(binding, context).unwrap()
}
fn moe<'c>(
&self,
binding: &ModelBinding,
context: &'c leleka_cuda_driver::Context<'_>,
profile: &[u8],
) -> MoeWeightCache<'c> {
MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input(
binding, context, profile,
)
.unwrap()
}
fn generate<'ctx>(&self, owner: &mut Owner<'ctx, '_>, run: &RunCtx<'_, 'ctx>) -> Direct {
// Only the changed direct Down proof shares this model load.
// The unchanged, previously qualified GDN helper is not repeated.
let mut session = QwenSession::for_binding_on_shared_device(run.binding, Rc::clone(run.context));
let down = QwenForward::test_direct_down_on_loaded(
run.binding,
run.context,
&mut session,
&mut owner.kar,
&mut owner.moe,
&owner.dense,
)
.expect("actual original-first direct Down packet proof failed");
drop(session);
let execution = EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr;
let arm = owner.armed_inputs(run).arm(&run.case.req, &run.case.ids, execution, DIRECT_PHASE);
Direct { arm, down: Some(Box::new(move || down.assert_after_teardown())) }
}
fn moe_facts(&self, moe: &MoeWeightCache<'_>, _binding: &ModelBinding, preload_ns: u128) -> MoeFacts {
pinned_facts(moe, preload_ns)
}
fn cache_bounds(report: &Direct) -> (Value, Value) {
(cache_json(report.arm.measurement.cache_before), cache_json(report.arm.measurement.cache_after))
}
fn record(&self, root: &std::path::Path, report: &Direct) -> Value {
let json = report.arm.json("candidate-only", "integer-gu-native-down-retained-gr256-kv-only");
save(root, "CANDIDATE.json", &json);
json
}
fn after_teardown(&self, report: &mut Direct) {
(report.down.take().expect("loaded direct Down report missing"))();
}
fn conclude(&self, f: Finish<Direct>) {
let arm = &f.report.arm;
let (offered, accepted) = candidate_windows(arm);
let parity = direct_parity(arm, &f.baseline);
let head = direct_head_json(&f, parity, f.case.ids.len());
let quality = with_counters(merged(head, direct_tail_json(&f, offered, accepted)), &f.td);
save(&f.root, "QUALITY.json", &quality);
assert!(arm.measurement.completed && arm.measurement.terminal_published);
assert_eq!(arm.measurement.retained_prefix_tokens, 0);
assert!(offered > 0 && accepted > 0, "actual candidate must offer and accept MTP drafts");
assert!(parity, "candidate differs from retained actual Native output/finish/Usage");
eprintln!(
"PUBLIC candidate-only framed={} output={} offered={offered} accepted={accepted} parity=true allocated=0 \
historical_speed_ratio=null",
f.case.ids.len(),
arm.measurement.output_token_ids.len()
);
}
}
/// The constructor name is 118 characters: it only fits a line of the limit when it starts at column 0.
#[rustfmt::skip]
fn resident_moe<'c>(
binding: &ModelBinding,
context: &'c leleka_cuda_driver::Context<'_>,
profile: &[u8],
) -> MoeWeightCache<'c> {
MoeWeightCache::
new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor_shared_permanent_learned_main_lru(
binding, context, profile,
)
.unwrap()
}
/// Which owner policy the five public requests run on.
#[derive(Clone, Copy)]
pub(super) enum Kind {
OneLoadedOwner,
RetainedQkQsa,
ResidentOwners,
}
pub(super) struct FiveCase(pub(super) Kind);
impl FiveCase {
/// The policy the owner reports; `None` is the default of `fivecase_runtime`.
fn run_policy(&self) -> Option<&'static str> {
match self.0 {
Kind::OneLoadedOwner => None,
Kind::RetainedQkQsa => Some("integer-gr256-streamed-spill-retained-qk40960-qsa108544"),
Kind::ResidentOwners => {
Some("integer-gr256-resident-owners-learned-main-shared192-gdn-journal-incremental-capture")
}
}
}
fn changed_owner_policy(&self) -> &'static str {
match self.0 {
Kind::OneLoadedOwner => "digest-capture-queued-input-compact-head-GR-batch-1GiB-reusable-spill-floor",
Kind::RetainedQkQsa => {
"digest-capture-queued-input-compact-head-GR-batch-1GiB-spill-retained-qk40960-qsa108544"
}
Kind::ResidentOwners => "incremental-capture-learned-main-shared192-gdn-journal-qk40960-qsa108544",
}
}
fn quality_json(&self, f: &Finish<FiveCaseReport>, parity: bool) -> Value {
json!({"case1_retained_native_parity":parity,
"quality_against_original17":null,"requires_matching_original_five":true,
"changed_owner_policy":self.changed_owner_policy(),
"spill_floor_bytes":1073741824u64,"actual_cuda_driver_version":f.driver_version,
"model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"hardware":f.hardware,
"allocated":f.td.allocated,"cleanup_complete":true,"same_request_case1":true,
"cache_state":CASE_STATE,
"GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false,
"longcontext_170K":false})
}
}
fn case1_parity(first: &Value, baseline: &Baseline) -> bool {
token_ids(&first["output_token_ids"]) == baseline.output_ids
&& first["text"].as_str() == Some(baseline.text.as_str())
&& first["finish_reason"] == json!("Length")
&& first["usage"] == json!({"input_tokens":202,"output_tokens":32,"reused_input_tokens":0})
}
impl Proof for FiveCase {
type Report = FiveCaseReport;
fn incremental_capture(&self) -> bool {
matches!(self.0, Kind::ResidentOwners)
}
fn dense<'c>(&self, binding: &ModelBinding, context: &'c leleka_cuda_driver::Context<'_>) -> DenseWeightCache<'c> {
match self.0 {
Kind::OneLoadedOwner => DenseWeightCache::new_qsa_selected_router_gr_batch(binding, context),
Kind::RetainedQkQsa => DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention(binding, context),
Kind::ResidentOwners => {
DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention_mtp_journal(binding, context)
}
}
.unwrap()
}
fn moe<'c>(
&self,
binding: &ModelBinding,
context: &'c leleka_cuda_driver::Context<'_>,
profile: &[u8],
) -> MoeWeightCache<'c> {
match self.0 {
Kind::ResidentOwners => resident_moe(binding, context, profile),
_ => MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor(
binding, context, profile,
)
.unwrap(),
}
}
fn generate<'ctx>(&self, owner: &mut Owner<'ctx, '_>, run: &RunCtx<'_, 'ctx>) -> FiveCaseReport {
// Already qualified DirectDown/components are not replayed. Every case
// gets a fresh target/draft; one genuine weight/cache owner load is shared.
let mut inputs = owner.armed_inputs(run);
let (manifest, manifest_sha) = inputs.prepare_five_public_frames();
match self.run_policy() {
None => inputs.arm_five_public_cases(&manifest, &manifest_sha),
Some(policy) => fivecase_runtime::run_on_loaded_with_policy(&mut inputs, &manifest, &manifest_sha, policy),
}
}
fn moe_facts(&self, moe: &MoeWeightCache<'_>, binding: &ModelBinding, preload_ns: u128) -> MoeFacts {
match self.0 {
Kind::ResidentOwners => learned_facts(moe, binding, preload_ns),
_ => pinned_facts(moe, preload_ns),
}
}
fn dense_check(&self, dense: &DenseWeightCache<'_>) -> Option<Check> {
let scratch = matches!(self.0, Kind::RetainedQkQsa).then(|| dense.test_retained_scratch_witness());
scratch.map(|witness| {
(
witness.is_ok_and(|(bytes, rows)| bytes == 149504 && rows > 1),
"actual retained scratch owner rows absent",
)
})
}
fn cache_bounds(report: &FiveCaseReport) -> (Value, Value) {
let json = report.json_after_teardown();
let last = json["cases"].as_array().unwrap().last().unwrap();
(json["cases"][0]["cache_before"].clone(), last["cache_after"].clone())
}
fn record(&self, root: &std::path::Path, report: &FiveCaseReport) -> Value {
let json = report.json_after_teardown();
save(root, "FIVE-CASE.json", &json);
json
}
fn conclude(&self, f: Finish<FiveCaseReport>) {
f.report.assert_after_teardown();
let first = &f.recorded["cases"][0];
assert_eq!(token_ids(&first["input_token_ids"]), f.baseline.input_ids);
let parity = case1_parity(first, &f.baseline);
save(&f.root, "QUALITY.json", &self.quality_json(&f, parity));
assert!(parity, "case1 differs from retained actual Native IDs/text/Length/Usage");
eprintln!("PUBLIC five cases completed allocated=0 case1_native_parity=true paired_original_pending=true");
}
}
@@ -0,0 +1,148 @@
//! Runs a `Proof` on the one loaded owner: generation, ordered teardown, the cleanup artifacts that survive a
//! failed generation, and the assertions that follow every attempted teardown.
use super::*;
use crate::qwen_forward::owner_wall_profile::{self, Sample};
const SCOPE: &str =
"six fixed producer categories during actual owner generation; excludes loading, preload and helper";
const WALL_COUNTS: &str =
"attempted mixed scalar/group/role/drain invocations, including errors; not products or tokens";
const WALL_OVERHEAD: &str = "one Instant pair and bounded TLS accounting per armed invocation; \
diagnostic run has instrumentation overhead";
fn counters_json(c: &OwnerCounters) -> Value {
json!({"actual_queued_shared_tail_rows":c.shared_tail_rows,"actual_mtp_input_completions":c.mtp_input,
"actual_compact_head_completions":c.compact_head,"actual_gr_batch_inject_completions":c.gr_batch,
"actual_lru_index":{"victim_lookups":c.lru.0,"metadata_updates":c.lru.1,"removals":c.lru.2,
"metadata_bytes":c.lru_metadata_bytes},
"actual_router_scratch_rows":c.router_rows,
"actual_router_scratch_reuses":c.router_rows.map(|rows| rows.saturating_sub(1))})
}
/// The keys of `extra` added to the object `base`.
pub(super) fn merged(mut base: Value, extra: Value) -> Value {
let (Some(target), Some(source)) = (base.as_object_mut(), extra.as_object()) else {
panic!("JSON objects required")
};
target.extend(source.iter().map(|(key, value)| (key.clone(), value.clone())));
base
}
/// The witness keys of the teardown added to the object `base`.
pub(super) fn with_counters(base: Value, td: &Teardown) -> Value {
merged(base, counters_json(&td.head.counters))
}
fn sample_json(sample: &Sample) -> Value {
json!({"label":sample.label,"attempted_scope_count":sample.count,
"inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns})
}
fn owner_wall_json(root: &std::path::Path, hardware: &Value, td: &Teardown, bounds: Option<(Value, Value)>) -> Value {
let wall = &td.owner_wall;
let rows = wall.as_ref().ok().map(|samples| samples.iter().map(sample_json).collect::<Vec<_>>());
let (before, after) = bounds.unzip();
json!({"schema":1,"valid":wall.is_ok(),"error":wall.as_ref().err(),"rows":rows,
"metadata":hardware,"owner_output_directory":root,"cache_before":before,"cache_after":after,
"scope":SCOPE,"drained_after_all_attempted_teardown":true,"counts":WALL_COUNTS,
"clock":"inclusive CPU owner wall with existing completion waits; not GPU service time",
"nested_totals_not_additive":true,"complete_request_accounting":false,"overhead":WALL_OVERHEAD,
"additional_cuda_calls":0,"additional_tensor_reads":0,"performance_acceptance":false})
}
fn cleanup_json(td: &Teardown, generation_succeeded: bool) -> Value {
let h = &td.head;
let base = json!({"oracle_disabled":h.oracle_disabled,"moe_closed":h.moe_closed,
"dense_closed":h.dense_closed,"synchronized":td.synchronized,"allocated":td.allocated,
"context_closed":td.context_closed,"generation_succeeded":generation_succeeded,
"actual_pinned_profile":h.facts.json});
with_counters(base, td)
}
/// The artifacts that are written even when the generation failed.
fn save_cleanup<P: Proof>(root: &std::path::Path, hardware: &Value, td: &Teardown, report: Option<&P::Report>) {
let bounds = report.map(P::cache_bounds);
save(root, "OWNER-WALL.json", &owner_wall_json(root, hardware, td, bounds));
if let Some(r) = &td.bank_after {
save(root, "BANK-COPIES.json", &bank_json(r));
}
save(root, "CLEANUP.json", &cleanup_json(td, report.is_some()));
}
/// Synchronizes and closes the Context, then releases the binding and drains the owner wall profile.
fn seal(
head: Witnessed,
context: Rc<leleka_cuda_driver::Context<'_>>,
binding: ModelBinding,
inherited: InheritedKarArchive,
) -> Teardown {
let synchronized = context.synchronize().is_ok();
let allocated = context.allocated_bytes();
let closed = match Rc::try_unwrap(context) {
Ok(c) => Some(c.close()),
Err(c) => {
drop(c);
None
}
};
let bank_after = binding.resident_expert_source_report().ok().flatten();
drop(binding);
drop(inherited);
let owner_wall = owner_wall_profile::drain();
let context_closed = matches!(&closed, Some(Ok(())));
Teardown { head, synchronized, allocated, context_closed, bank_after, owner_wall }
}
fn assert_torn(td: &Teardown) {
let h = &td.head;
assert!(h.oracle_disabled && h.moe_closed && h.dense_closed && td.synchronized);
assert_eq!(td.allocated, 0);
assert!(td.context_closed);
assert!(td.owner_wall.is_ok(), "actual owner wall profile drain failed");
}
/// Quality assertions follow every attempted teardown and preserve a primary
/// generation panic/error. There is no Native call or historical timing ratio.
fn assert_witnesses(h: &Witnessed) {
for (ok, message) in &h.facts.checks {
assert!(*ok, "{message}");
}
let c = &h.counters;
assert!(c.gr_batch > 0, "actual retained GR batch injection did not complete");
assert!(c.compact_head > 0, "actual compact full-vocabulary head did not complete");
assert!(c.mtp_input > 0, "actual completed MTP input queue was not executed");
assert!(c.shared_tail_rows > 0, "actual queued target shared tail was not executed");
assert!(c.router_rows.is_some_and(|rows| rows > 1), "actual router scratch was not reused");
assert!(c.lru.0 > 0 && c.lru.1 > 0 && c.lru.2 > 0, "actual indexed lookup/update/removal path was not exercised");
assert!(
c.lru_metadata_bytes.is_some_and(|bytes| bytes > 0 && bytes <= 16 * 1024 * 1024),
"bounded actual index metadata charge missing"
);
if let Some((ok, message)) = &h.dense_check {
assert!(*ok, "{message}");
}
}
/// Rethrows a generation panic first, then a cleanup panic, once the cleanup artifacts are written.
fn unwind_after_cleanup<R>(candidate: std::thread::Result<R>, cleanup: std::thread::Result<()>) -> R {
let report = match candidate {
Ok(value) => value,
Err(primary) => resume_unwind(primary),
};
if let Err(secondary) = cleanup {
resume_unwind(secondary);
}
report
}
pub(super) fn run<P: Proof>(proof: &P) {
let Host { root, hardware, baseline, tokenizer, eos, case, binding, inherited, profile } = Host::admit(proof);
// Reuse the already verified bound tokenizer; no long request or Native inference.
let driver = Driver::load().expect("actual CUDA driver failed");
let driver_version = json!(driver.version());
let device = driver.device(0).unwrap();
let context = Rc::new(device.create_context(DEVICE_BUDGET).unwrap());
let mut owner = Owner::load(proof, &binding, context.as_ref(), profile);
let ctx = RunCtx { binding: &binding, tokenizer: &tokenizer, context: &context, eos, case: &case };
let candidate = catch_unwind(AssertUnwindSafe(|| proof.generate(&mut owner, &ctx)));
let head = owner.teardown(proof, &binding);
let td = seal(head, context, binding, inherited);
let cleanup = catch_unwind(AssertUnwindSafe(|| {
save_cleanup::<P>(&root, &hardware, &td, candidate.as_ref().ok());
}));
let mut report = unwind_after_cleanup(candidate, cleanup);
let recorded = proof.record(&root, &report);
assert_torn(&td);
proof.after_teardown(&mut report);
assert_witnesses(&td.head);
proof.conclude(Finish { root, hardware, baseline, case, driver_version, report, recorded, td });
}