STRA-338 size2: merge of the 14 function-size slices; seven files over 400 lines split again, baselines regenerated (dyn-trait ratchet raised by helper parameters that repeat an existing &dyn seam, allowlist gets the legacy functions the splitter moved)

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 23:36:21 +01:00
parent 1c3bcdf290
commit 2d25958e42
40 changed files with 4035 additions and 3511 deletions
+5 -5
View File
@@ -8,11 +8,11 @@
"source": {
"dyn-trait:leleka-backend-api": 1,
"dyn-trait:leleka-cpu-worker": 4,
"dyn-trait:leleka-cuda-driver": 48,
"dyn-trait:leleka-cuda-driver": 56,
"dyn-trait:leleka-deploy": 17,
"dyn-trait:leleka-engine-core": 18,
"dyn-trait:leleka-engine-fake": 1,
"dyn-trait:leleka-engine-qwen35-cuda": 50,
"dyn-trait:leleka-engine-qwen35-cuda": 53,
"dyn-trait:leleka-experimental-ref": 3,
"dyn-trait:leleka-gateway-domain": 4,
"dyn-trait:leleka-gptoss": 10,
@@ -26,7 +26,7 @@
"dyn-trait:strata-desktop-core": 2,
"env-read:leleka-cpu-kernels": 1,
"env-read:leleka-cpu-worker": 2,
"env-read:leleka-cuda-driver": 73,
"env-read:leleka-cuda-driver": 72,
"env-read:leleka-deploy": 41,
"env-read:leleka-engine-qwen35-cuda": 1,
"env-read:leleka-gateway-text": 2,
@@ -47,9 +47,9 @@
"env-read:strata-desktop-core": 15,
"instant-now:leleka-backend-api": 2,
"instant-now:leleka-cpu-worker": 9,
"instant-now:leleka-cuda-driver": 31,
"instant-now:leleka-cuda-driver": 25,
"instant-now:leleka-deploy": 28,
"instant-now:leleka-engine-qwen35-cuda": 17,
"instant-now:leleka-engine-qwen35-cuda": 16,
"instant-now:leleka-gptoss": 4,
"instant-now:leleka-gptoss-igpu": 5,
"instant-now:leleka-gptoss-npu": 12,
+48 -375
View File
@@ -10,73 +10,6 @@ const ENABLE: &str = "LELEKA_QSA_LATE_GPU";
const CAP: usize = 2051;
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
}
fn upload<'c>(context: &'c Context<'c>, bytes: &[u8]) -> DeviceBuffer<'c> {
let mut b = context.allocate(bytes.len().max(16).next_multiple_of(16)).expect("alloc");
let mut padded = bytes.to_vec();
padded.resize(b.len(), 0);
b.copy_from(&padded).expect("upload");
b
}
fn download(b: &DeviceBuffer<'_>, n: usize) -> Vec<u8> {
b.copy_to_owned(b.len()).expect("download")[..n].to_vec()
}
/// Opens the device with a 6 GiB budget and runs `body(context, stream, max_blocks)` on the workspace stream.
fn with_gpu(body: impl FnOnce(&Context<'_>, usize, usize)) {
assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes"));
let driver = Driver::load().expect("driver");
let device = driver.device(0).expect("device");
let context = device.create_context(6usize << 30).expect("context");
let workspace = context.native_batch_workspace().expect("workspace");
let stream = workspace.blas().expect("blas").stream();
let max_blocks = crate::serving_context::geometry().max_blocks();
body(&context, stream, max_blocks);
}
fn handle(b: &DeviceBuffer<'_>) -> crate::ffi::BufferHandle {
b.handle.expect("handle")
}
/// The per-row step words: position, position + 1, the block count and the clamped selection width.
fn step_bytes(p0: usize, rows: usize) -> Vec<u8> {
let mut steps = Vec::new();
for r in 0..rows {
let pos = p0 + r;
for x in [pos, pos + 1, (pos + 1) / 4, (pos + 1).min(CAP)] {
steps.extend_from_slice(&(x as i32).to_le_bytes());
}
}
steps
}
fn f32_raw(values: &[f32]) -> Vec<u8> {
let mut raw = Vec::with_capacity(values.len() * 4);
values.iter().for_each(|v| raw.extend_from_slice(&v.to_le_bytes()));
raw
}
/// The top-k arguments over `scores`/`steps` writing `ids`.
fn topk_args(
max_blocks: usize,
(scores, steps): (&DeviceBuffer<'_>, &DeviceBuffer<'_>),
ids: &DeviceBuffer<'_>,
) -> KernelArguments {
KernelArguments::new(vec![
A::Address(handle(scores)),
A::Address(handle(steps)),
A::I64(max_blocks as i64),
A::I64(CAP as i64),
A::Address(handle(ids)),
])
}
// ---------------------------------------------------------------------------------------------- selection kernels
@@ -121,126 +54,6 @@ fn selection_kernels_equal_the_originals_at_long_positions() {
});
}
/// Block scores of `rows` rows from position `p0` in `style` (0 continuous, 1 sixteen tied levels, 2 all equal).
fn selection_scores(rng: &mut Rng, max_blocks: usize, (p0, rows, style): (usize, usize, u8)) -> Vec<f32> {
let mut scores = vec![0f32; rows * max_blocks];
for r in 0..rows {
let n_bid = (p0 + r + 1) / 4;
for b in 0..=n_bid.min(max_blocks - 1) {
let v = match style {
0 => (rng.next() % 1_000_003) as f32 / 1000.0,
1 => ((rng.next() % 16) as f32) * 0.5 * ((rng.next() % 3 != 0) as u32 as f32),
_ => 0.0,
};
scores[r * max_blocks + b] = v;
}
if style == 1 || style == 0 {
// the tail block of the real scorer: +1e9 when it is partly filled
if (p0 + r + 1) % 4 != 0 {
scores[r * max_blocks + n_bid] += 1e9;
}
}
}
scores
}
fn selection_case(rig: &SelectionRig<'_>, rng: &mut Rng, case: usize, c @ (p0, rows, _): (usize, usize, u8)) {
let steps = step_bytes(p0, rows);
let scores = selection_scores(rng, rig.max_blocks, c);
let scores_d = upload(rig.context, &f32_raw(&scores));
let steps_d = upload(rig.context, &steps);
topk_matches_original(rig, (&scores_d, &steps_d), (case, c));
scan_flags_match_original(rig, (&scores, &steps_d), (case, p0, rows));
}
/// `leleka_qsa_topk_fast` writes the same ids as `qsa_topk_ref`.
fn topk_matches_original(
rig: &SelectionRig<'_>,
inputs: (&DeviceBuffer<'_>, &DeviceBuffer<'_>),
(case, (p0, rows, style)): (usize, (usize, usize, u8)),
) {
let (context, stream) = (rig.context, rig.stream);
let out_len = rows * CAP * 4;
let ids_o = upload(context, &vec![0xffu8; out_len]);
let ids_n = upload(context, &vec![0xffu8; out_len]);
let guard = context.enter().expect("enter");
let mut a_old = topk_args(rig.max_blocks, inputs, &ids_o);
let mut a_new = topk_args(rig.max_blocks, inputs, &ids_n);
let t0 = std::time::Instant::now();
rig.select.launch(0, rows as u32, 256, stream, &mut a_old).expect("old topk");
context.driver.api.synchronize().expect("sync");
let old_ms = t0.elapsed().as_secs_f64() * 1e3;
let t1 = std::time::Instant::now();
rig.late.launch(TOPK_FAST, rows as u32, 256, stream, &mut a_new).expect("new topk");
context.driver.api.synchronize().expect("sync");
let new_ms = t1.elapsed().as_secs_f64() * 1e3;
guard.finish().expect("finish");
let (o, n) = (download(&ids_o, out_len), download(&ids_n, out_len));
assert!(o == n, "case {case} (p0 {p0}, rows {rows}, style {style}): ids differ");
eprintln!(
"QSA-LATE topk case {case} p0={p0} rows={rows} style={style}: ids equal ({} bytes); original {old_ms:.3} ms, fast {new_ms:.3} ms",
out_len
);
}
/// The score scan: a clean tile, then a NaN inside a row's blocks, then a NaN beyond its last block.
fn scan_flags_match_original(
rig: &SelectionRig<'_>,
(scores, steps_d): (&[f32], &DeviceBuffer<'_>),
(case, p0, rows): (usize, usize, usize),
) {
for variant in 0..3 {
let bad = scores_with_variant(scores, rig.max_blocks, (p0, rows), variant);
let (st_o, st_n) = scan_both(rig, (&bad, steps_d), (p0, rows));
assert_eq!(download(&st_o, 8), download(&st_n, 8), "case {case} variant {variant}: scan flags");
if variant == 1 {
assert_ne!(download(&st_n, 8)[4..8], [0, 0, 0, 0], "a NaN inside the blocks must raise the flag");
}
}
}
/// `scores` with a NaN inside a row's blocks (variant 1) or an infinity beyond a row's last block (variant 2).
fn scores_with_variant(scores: &[f32], max_blocks: usize, (p0, rows): (usize, usize), variant: usize) -> Vec<f32> {
let mut bad = scores.to_vec();
match variant {
1 => bad[(rows / 2) * max_blocks + ((p0 + rows / 2 + 1) / 4) / 2] = f32::NAN,
2 => {
let row = rows - 1;
let n_bid = (p0 + row + 1) / 4;
if n_bid + 1 < max_blocks {
bad[row * max_blocks + n_bid + 1] = f32::INFINITY;
}
}
_ => {}
}
bad
}
/// The Original's score scan and the late fast scan over the same scores; returns both status buffers.
fn scan_both<'c>(
rig: &SelectionRig<'c>,
(bad, steps_d): (&[f32], &DeviceBuffer<'_>),
(p0, rows): (usize, usize),
) -> (DeviceBuffer<'c>, DeviceBuffer<'c>) {
let (context, stream, max_blocks) = (rig.context, rig.stream, rig.max_blocks);
let reach = (p0 + rows) / 4 + 1;
let ad = |b: &DeviceBuffer<'_>| A::Address(handle(b));
let bad_d = upload(context, &f32_raw(bad));
let (st_o, st_n) = (upload(context, &[0u8; 16]), upload(context, &[0u8; 16]));
let guard = context.enter().expect("enter");
let old = vec![ad(&bad_d), ad(steps_d), A::I32(rows as i32), A::I64(max_blocks as i64), ad(&st_o), A::U32(1)];
let mut so = KernelArguments::new(old);
rig.index.launch(0, (rows * max_blocks).div_ceil(256) as u32, 256, stream, &mut so).expect("old scan");
let mut new = vec![ad(&bad_d), ad(steps_d), A::I32(rows as i32), A::I64(max_blocks as i64)];
new.extend([A::I64(reach as i64), ad(&st_n), A::U32(1)]);
let mut sn = KernelArguments::new(new);
let grid = (rows * reach).div_ceil(256) as u32;
rig.late.launch(SCORE_SCAN_FAST, grid, 256, stream, &mut sn).expect("new scan");
context.driver.api.synchronize().expect("sync");
guard.finish().expect("finish");
(st_o, st_n)
}
// ---------------------------------------------------------------------------------------------- top-k variants
/// The Original's top-k, the late variants and the decode cluster kernel.
@@ -278,136 +91,6 @@ fn topk_variants_equal_the_original_and_are_timed() {
});
}
/// (first position, rows, style, label): style 0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy tail (relu-sum
/// like).
fn bench_cases() -> [(usize, usize, u8, &'static str); 24] {
[
(100, 4, 3, "decode"),
(2_040, 4, 3, "decode"),
(2_049, 5, 1, "decode"),
(3_000, 4, 3, "decode"),
(9_999, 3, 2, "decode"),
(2_040, 256, 3, "prompt"),
(8_000, 256, 3, "prompt"),
(24_000, 256, 3, "prompt"),
(48_000, 256, 3, "prompt"),
(70_000, 256, 3, "prompt"),
(100_003, 256, 0, "prompt"),
(100_003, 256, 3, "prompt"),
(180_000, 256, 0, "prompt"),
(180_000, 256, 3, "prompt"),
(180_000, 256, 1, "prompt"),
(245_000, 256, 3, "prompt"),
(245_000, 256, 2, "prompt"),
(131_072, 1, 3, "decode"),
(131_072, 4, 3, "decode"),
(245_000, 1, 3, "decode"),
(245_000, 4, 3, "decode"),
(245_000, 5, 0, "decode"),
(245_000, 4, 1, "decode"),
(261_500, 4, 2, "decode"),
]
}
/// Block scores of `rows` rows from position `p0` in `style` (0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy
/// tail).
fn bench_scores(rng: &mut Rng, max_blocks: usize, (p0, rows, style): (usize, usize, u8)) -> Vec<f32> {
let mut scores = vec![0f32; rows * max_blocks];
for r in 0..rows {
let n_bid = (p0 + r + 1) / 4;
for b in 0..=n_bid.min(max_blocks - 1) {
let u = (rng.next() % 1_000_003) as f32 / 1_000_003.0;
scores[r * max_blocks + b] = match style {
0 => u * 1000.0,
1 => ((rng.next() % 16) as f32) * 0.5 * ((rng.next() % 3 != 0) as u32 as f32),
2 => 0.0,
_ => (-(u.max(1e-6)).ln()) * 40.0 * ((rng.next() % 4 != 0) as u32 as f32) + ((b % 977) as f32) * 0.01,
};
}
if style != 2 && (p0 + r + 1) % 4 != 0 {
scores[r * max_blocks + n_bid] += 1e9;
}
}
scores
}
/// One runner per variant: (name, closure launching it once).
fn topk_variants<'a>(rig: &'a BenchRig<'a>, n: u32) -> Vec<(&'static str, Run<'a>)> {
let (select, late, cluster, stream) = (&rig.select, &rig.late, &rig.cluster, rig.stream);
let smem = crate::qsa_cluster::dynamic_smem(rig.max_blocks);
vec![
("ref", Box::new(move |a| select.launch(0, n, 256, stream, a).expect("ref"))),
("fast", Box::new(move |a| late.launch(TOPK_FAST, n, 256, stream, a).expect("fast"))),
("wide", Box::new(move |a| late.launch(TOPK_WIDE, n, 1024, stream, a).expect("wide"))),
(
"sample+failed",
Box::new(move |a| {
late.launch(TOPK_SAMPLE, n, 1024, stream, a).expect("sample");
late.launch(TOPK_WIDE_FAILED, n, 1024, stream, a).expect("failed");
}),
),
(
"cluster",
Box::new(move |a| {
cluster
.launch_cluster(crate::qsa_cluster::TOPK_CLUSTER, [8, n], 1024, 8, smem, stream, a)
.expect("cluster")
}),
),
]
}
fn bench_case(rig: &BenchRig<'_>, rng: &mut Rng, case: usize, (p0, rows, style, label): (usize, usize, u8, &str)) {
let context = rig.context;
let steps = step_bytes(p0, rows);
let scores = bench_scores(rng, rig.max_blocks, (p0, rows, style));
let scores_d = upload(context, &f32_raw(&scores));
let steps_d = upload(context, &steps);
let out_len = rows * CAP * 4;
let variants = topk_variants(rig, rows as u32);
let mut reference: Option<Vec<u8>> = None;
let mut line = format!("QSA-TOPK-BENCH case {case} {label} p0={p0} rows={rows} style={style}:");
for (name, run) in &variants {
if *name == "cluster" && rows > 16 {
continue; // the decode kernel (the upstream dispatch uses it for at most 16 queries)
}
let (got, us) = time_variant(rig, run, (&scores_d, &steps_d), out_len);
match &reference {
None => reference = Some(got),
Some(r) => assert!(
*r == got,
"case {case} (p0 {p0}, rows {rows}, style {style}): {name} ids differ from the original"
),
}
line.push_str(&format!(" {name} {us:.1} us;"));
}
eprintln!("{line} ids equal");
}
/// Runs one variant warm, then 20 launches drained once; returns the ids it wrote and the per-launch microseconds.
fn time_variant(
rig: &BenchRig<'_>,
run: &Run<'_>,
inputs: (&DeviceBuffer<'_>, &DeviceBuffer<'_>),
out_len: usize,
) -> (Vec<u8>, f64) {
let (context, reps) = (rig.context, 20);
let ids = upload(context, &vec![0xffu8; out_len]);
let mut a = topk_args(rig.max_blocks, inputs, &ids);
let guard = context.enter().expect("enter");
// the sample kernel flags its failures in a module global that persists: clear by running sample first inside run
run(&mut a);
context.driver.api.synchronize().expect("sync");
let t0 = std::time::Instant::now();
for _ in 0..reps {
run(&mut a);
}
context.driver.api.synchronize().expect("sync");
let us = t0.elapsed().as_secs_f64() * 1e6 / reps as f64;
guard.finish().expect("finish");
(download(&ids, out_len), us)
}
// ---------------------------------------------------------------------------------------------- decode scores
/// Timing only (row 2.5 follow-up): the decode window's block scores (`qsa_decode_scores`, the Original's multi-query kernel, 256 CTAs) next to its
@@ -428,61 +111,51 @@ fn decode_scores_are_timed_next_to_the_topk() {
});
}
/// Random pooled, dead and query vectors and the steps of one `(pos, nq)` shape, uploaded in that order.
fn decode_inputs<'c>(
context: &'c Context<'c>,
rng: &mut Rng,
max_blocks: usize,
(pos, nq): (usize, usize),
) -> [DeviceBuffer<'c>; 4] {
let mut random =
|n: usize| -> Vec<f32> { (0..n).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect() };
let pooled = random((max_blocks + 1) * 128);
let dead = random(128);
let qidx = random(nq * 4 * 128);
let steps = step_bytes(pos, nq);
[
upload(context, &f32_raw(&pooled)),
upload(context, &f32_raw(&dead)),
upload(context, &f32_raw(&qidx)),
upload(context, &steps),
]
}
/// Times the decode scores kernel and the top-k at one `(pos, nq)` shape, 20 warm launches each.
fn time_scores_and_topk(
context: &Context<'_>,
(select, stream, max_blocks): (&KernelModule, usize, usize),
rng: &mut Rng,
(pos, nq): (usize, usize),
) {
let n_bid_max = (pos + nq) / 4;
let [pooled_d, dead_d, qidx_d, steps_d] = decode_inputs(context, rng, max_blocks, (pos, nq));
let scores_d = upload(context, &vec![0u8; nq * max_blocks * 4]);
let ids_d = upload(context, &vec![0xffu8; nq * CAP * 4]);
let guard = context.enter().expect("enter");
let ad = |b: &DeviceBuffer<'_>| A::Address(handle(b));
let (nq_arg, blocks_arg) = (A::I32(nq as i32), A::I64(max_blocks as i64));
let mut sa: Vec<A> = [&pooled_d, &dead_d, &qidx_d, &steps_d].into_iter().map(|b| ad(b)).collect();
sa.extend([nq_arg, blocks_arg, ad(&scores_d)]);
let mut sa = KernelArguments::new(sa);
let scores_us = time_warm(context, &mut || select.launch(0, 256, 256, stream, &mut sa).expect("scores"));
let mut ta = topk_args(max_blocks, (&scores_d, &steps_d), &ids_d);
let topk_us = time_warm(context, &mut || select.launch(1, nq as u32, 256, stream, &mut ta).expect("topk"));
guard.finish().expect("finish");
eprintln!(
"QSA-DECODE-SCORES pos={pos} nq={nq} n_bid={n_bid_max}: qsa_decode_scores {scores_us:.1} us, qsa_topk_ref {topk_us:.1} us (per layer, warm)"
);
}
/// One warm-up run, then 20 timed runs drained once; microseconds per run.
fn time_warm(context: &Context<'_>, run: &mut dyn FnMut()) -> f64 {
run();
context.driver.api.synchronize().expect("sync");
let t0 = std::time::Instant::now();
for _ in 0..20 {
run();
}
context.driver.api.synchronize().expect("sync");
t0.elapsed().as_secs_f64() * 1e6 / 20.0
}
#[path = "qsa_late_gpu/impl_rng.rs"]
mod impl_rng;
#[allow(unused_imports)]
use impl_rng::download;
#[allow(unused_imports)]
use impl_rng::f32_raw;
#[allow(unused_imports)]
use impl_rng::handle;
#[allow(unused_imports)]
use impl_rng::scan_flags_match_original;
#[allow(unused_imports)]
use impl_rng::scores_with_variant;
#[allow(unused_imports)]
use impl_rng::selection_case;
#[allow(unused_imports)]
use impl_rng::selection_scores;
#[allow(unused_imports)]
use impl_rng::step_bytes;
#[allow(unused_imports)]
use impl_rng::topk_args;
#[allow(unused_imports)]
use impl_rng::topk_matches_original;
#[allow(unused_imports)]
use impl_rng::upload;
#[allow(unused_imports)]
use impl_rng::with_gpu;
#[path = "qsa_late_gpu/scan_both_fn.rs"]
mod scan_both_fn;
#[allow(unused_imports)]
use scan_both_fn::bench_case;
#[allow(unused_imports)]
use scan_both_fn::bench_cases;
#[allow(unused_imports)]
use scan_both_fn::bench_scores;
#[allow(unused_imports)]
use scan_both_fn::decode_inputs;
#[allow(unused_imports)]
use scan_both_fn::scan_both;
#[allow(unused_imports)]
use scan_both_fn::time_variant;
#[allow(unused_imports)]
use scan_both_fn::topk_variants;
#[path = "qsa_late_gpu/time_scores_and_topk_fn.rs"]
mod time_scores_and_topk_fn;
#[allow(unused_imports)]
use time_scores_and_topk_fn::time_scores_and_topk;
#[allow(unused_imports)]
use time_scores_and_topk_fn::time_warm;
@@ -0,0 +1,177 @@
//! Moved out of the parent module by STRA-338.
#[allow(unused_imports)]
use super::*;
impl Rng {
pub(super) fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
}
pub(super) fn upload<'c>(context: &'c Context<'c>, bytes: &[u8]) -> DeviceBuffer<'c> {
let mut b = context.allocate(bytes.len().max(16).next_multiple_of(16)).expect("alloc");
let mut padded = bytes.to_vec();
padded.resize(b.len(), 0);
b.copy_from(&padded).expect("upload");
b
}
pub(super) fn download(b: &DeviceBuffer<'_>, n: usize) -> Vec<u8> {
b.copy_to_owned(b.len()).expect("download")[..n].to_vec()
}
/// Opens the device with a 6 GiB budget and runs `body(context, stream, max_blocks)` on the workspace stream.
pub(super) fn with_gpu(body: impl FnOnce(&Context<'_>, usize, usize)) {
assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes"));
let driver = Driver::load().expect("driver");
let device = driver.device(0).expect("device");
let context = device.create_context(6usize << 30).expect("context");
let workspace = context.native_batch_workspace().expect("workspace");
let stream = workspace.blas().expect("blas").stream();
let max_blocks = crate::serving_context::geometry().max_blocks();
body(&context, stream, max_blocks);
}
pub(super) fn handle(b: &DeviceBuffer<'_>) -> crate::ffi::BufferHandle {
b.handle.expect("handle")
}
/// The per-row step words: position, position + 1, the block count and the clamped selection width.
pub(super) fn step_bytes(p0: usize, rows: usize) -> Vec<u8> {
let mut steps = Vec::new();
for r in 0..rows {
let pos = p0 + r;
for x in [pos, pos + 1, (pos + 1) / 4, (pos + 1).min(CAP)] {
steps.extend_from_slice(&(x as i32).to_le_bytes());
}
}
steps
}
pub(super) fn f32_raw(values: &[f32]) -> Vec<u8> {
let mut raw = Vec::with_capacity(values.len() * 4);
values.iter().for_each(|v| raw.extend_from_slice(&v.to_le_bytes()));
raw
}
/// The top-k arguments over `scores`/`steps` writing `ids`.
pub(super) fn topk_args(
max_blocks: usize,
(scores, steps): (&DeviceBuffer<'_>, &DeviceBuffer<'_>),
ids: &DeviceBuffer<'_>,
) -> KernelArguments {
KernelArguments::new(vec![
A::Address(handle(scores)),
A::Address(handle(steps)),
A::I64(max_blocks as i64),
A::I64(CAP as i64),
A::Address(handle(ids)),
])
}
/// Block scores of `rows` rows from position `p0` in `style` (0 continuous, 1 sixteen tied levels, 2 all equal).
pub(super) fn selection_scores(rng: &mut Rng, max_blocks: usize, (p0, rows, style): (usize, usize, u8)) -> Vec<f32> {
let mut scores = vec![0f32; rows * max_blocks];
for r in 0..rows {
let n_bid = (p0 + r + 1) / 4;
for b in 0..=n_bid.min(max_blocks - 1) {
let v = match style {
0 => (rng.next() % 1_000_003) as f32 / 1000.0,
1 => ((rng.next() % 16) as f32) * 0.5 * ((rng.next() % 3 != 0) as u32 as f32),
_ => 0.0,
};
scores[r * max_blocks + b] = v;
}
if style == 1 || style == 0 {
// the tail block of the real scorer: +1e9 when it is partly filled
if (p0 + r + 1) % 4 != 0 {
scores[r * max_blocks + n_bid] += 1e9;
}
}
}
scores
}
pub(super) fn selection_case(
rig: &SelectionRig<'_>,
rng: &mut Rng,
case: usize,
c @ (p0, rows, _): (usize, usize, u8),
) {
let steps = step_bytes(p0, rows);
let scores = selection_scores(rng, rig.max_blocks, c);
let scores_d = upload(rig.context, &f32_raw(&scores));
let steps_d = upload(rig.context, &steps);
topk_matches_original(rig, (&scores_d, &steps_d), (case, c));
scan_flags_match_original(rig, (&scores, &steps_d), (case, p0, rows));
}
/// `leleka_qsa_topk_fast` writes the same ids as `qsa_topk_ref`.
pub(super) fn topk_matches_original(
rig: &SelectionRig<'_>,
inputs: (&DeviceBuffer<'_>, &DeviceBuffer<'_>),
(case, (p0, rows, style)): (usize, (usize, usize, u8)),
) {
let (context, stream) = (rig.context, rig.stream);
let out_len = rows * CAP * 4;
let ids_o = upload(context, &vec![0xffu8; out_len]);
let ids_n = upload(context, &vec![0xffu8; out_len]);
let guard = context.enter().expect("enter");
let mut a_old = topk_args(rig.max_blocks, inputs, &ids_o);
let mut a_new = topk_args(rig.max_blocks, inputs, &ids_n);
let t0 = std::time::Instant::now();
rig.select.launch(0, rows as u32, 256, stream, &mut a_old).expect("old topk");
context.driver.api.synchronize().expect("sync");
let old_ms = t0.elapsed().as_secs_f64() * 1e3;
let t1 = std::time::Instant::now();
rig.late.launch(TOPK_FAST, rows as u32, 256, stream, &mut a_new).expect("new topk");
context.driver.api.synchronize().expect("sync");
let new_ms = t1.elapsed().as_secs_f64() * 1e3;
guard.finish().expect("finish");
let (o, n) = (download(&ids_o, out_len), download(&ids_n, out_len));
assert!(o == n, "case {case} (p0 {p0}, rows {rows}, style {style}): ids differ");
eprintln!(
"QSA-LATE topk case {case} p0={p0} rows={rows} style={style}: ids equal ({} bytes); original {old_ms:.3} ms, fast {new_ms:.3} ms",
out_len
);
}
/// The score scan: a clean tile, then a NaN inside a row's blocks, then a NaN beyond its last block.
pub(super) fn scan_flags_match_original(
rig: &SelectionRig<'_>,
(scores, steps_d): (&[f32], &DeviceBuffer<'_>),
(case, p0, rows): (usize, usize, usize),
) {
for variant in 0..3 {
let bad = scores_with_variant(scores, rig.max_blocks, (p0, rows), variant);
let (st_o, st_n) = scan_both(rig, (&bad, steps_d), (p0, rows));
assert_eq!(download(&st_o, 8), download(&st_n, 8), "case {case} variant {variant}: scan flags");
if variant == 1 {
assert_ne!(download(&st_n, 8)[4..8], [0, 0, 0, 0], "a NaN inside the blocks must raise the flag");
}
}
}
/// `scores` with a NaN inside a row's blocks (variant 1) or an infinity beyond a row's last block (variant 2).
pub(super) fn scores_with_variant(
scores: &[f32],
max_blocks: usize,
(p0, rows): (usize, usize),
variant: usize,
) -> Vec<f32> {
let mut bad = scores.to_vec();
match variant {
1 => bad[(rows / 2) * max_blocks + ((p0 + rows / 2 + 1) / 4) / 2] = f32::NAN,
2 => {
let row = rows - 1;
let n_bid = (p0 + row + 1) / 4;
if n_bid + 1 < max_blocks {
bad[row * max_blocks + n_bid + 1] = f32::INFINITY;
}
}
_ => {}
}
bad
}
@@ -0,0 +1,185 @@
//! Moved out of the parent module by STRA-338.
#[allow(unused_imports)]
use super::*;
/// The Original's score scan and the late fast scan over the same scores; returns both status buffers.
pub(super) fn scan_both<'c>(
rig: &SelectionRig<'c>,
(bad, steps_d): (&[f32], &DeviceBuffer<'_>),
(p0, rows): (usize, usize),
) -> (DeviceBuffer<'c>, DeviceBuffer<'c>) {
let (context, stream, max_blocks) = (rig.context, rig.stream, rig.max_blocks);
let reach = (p0 + rows) / 4 + 1;
let ad = |b: &DeviceBuffer<'_>| A::Address(handle(b));
let bad_d = upload(context, &f32_raw(bad));
let (st_o, st_n) = (upload(context, &[0u8; 16]), upload(context, &[0u8; 16]));
let guard = context.enter().expect("enter");
let old = vec![ad(&bad_d), ad(steps_d), A::I32(rows as i32), A::I64(max_blocks as i64), ad(&st_o), A::U32(1)];
let mut so = KernelArguments::new(old);
rig.index.launch(0, (rows * max_blocks).div_ceil(256) as u32, 256, stream, &mut so).expect("old scan");
let mut new = vec![ad(&bad_d), ad(steps_d), A::I32(rows as i32), A::I64(max_blocks as i64)];
new.extend([A::I64(reach as i64), ad(&st_n), A::U32(1)]);
let mut sn = KernelArguments::new(new);
let grid = (rows * reach).div_ceil(256) as u32;
rig.late.launch(SCORE_SCAN_FAST, grid, 256, stream, &mut sn).expect("new scan");
context.driver.api.synchronize().expect("sync");
guard.finish().expect("finish");
(st_o, st_n)
}
/// (first position, rows, style, label): style 0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy tail (relu-sum
/// like).
pub(super) fn bench_cases() -> [(usize, usize, u8, &'static str); 24] {
[
(100, 4, 3, "decode"),
(2_040, 4, 3, "decode"),
(2_049, 5, 1, "decode"),
(3_000, 4, 3, "decode"),
(9_999, 3, 2, "decode"),
(2_040, 256, 3, "prompt"),
(8_000, 256, 3, "prompt"),
(24_000, 256, 3, "prompt"),
(48_000, 256, 3, "prompt"),
(70_000, 256, 3, "prompt"),
(100_003, 256, 0, "prompt"),
(100_003, 256, 3, "prompt"),
(180_000, 256, 0, "prompt"),
(180_000, 256, 3, "prompt"),
(180_000, 256, 1, "prompt"),
(245_000, 256, 3, "prompt"),
(245_000, 256, 2, "prompt"),
(131_072, 1, 3, "decode"),
(131_072, 4, 3, "decode"),
(245_000, 1, 3, "decode"),
(245_000, 4, 3, "decode"),
(245_000, 5, 0, "decode"),
(245_000, 4, 1, "decode"),
(261_500, 4, 2, "decode"),
]
}
/// Block scores of `rows` rows from position `p0` in `style` (0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy
/// tail).
pub(super) fn bench_scores(rng: &mut Rng, max_blocks: usize, (p0, rows, style): (usize, usize, u8)) -> Vec<f32> {
let mut scores = vec![0f32; rows * max_blocks];
for r in 0..rows {
let n_bid = (p0 + r + 1) / 4;
for b in 0..=n_bid.min(max_blocks - 1) {
let u = (rng.next() % 1_000_003) as f32 / 1_000_003.0;
scores[r * max_blocks + b] = match style {
0 => u * 1000.0,
1 => ((rng.next() % 16) as f32) * 0.5 * ((rng.next() % 3 != 0) as u32 as f32),
2 => 0.0,
_ => (-(u.max(1e-6)).ln()) * 40.0 * ((rng.next() % 4 != 0) as u32 as f32) + ((b % 977) as f32) * 0.01,
};
}
if style != 2 && (p0 + r + 1) % 4 != 0 {
scores[r * max_blocks + n_bid] += 1e9;
}
}
scores
}
/// One runner per variant: (name, closure launching it once).
pub(super) fn topk_variants<'a>(rig: &'a BenchRig<'a>, n: u32) -> Vec<(&'static str, Run<'a>)> {
let (select, late, cluster, stream) = (&rig.select, &rig.late, &rig.cluster, rig.stream);
let smem = crate::qsa_cluster::dynamic_smem(rig.max_blocks);
vec![
("ref", Box::new(move |a| select.launch(0, n, 256, stream, a).expect("ref"))),
("fast", Box::new(move |a| late.launch(TOPK_FAST, n, 256, stream, a).expect("fast"))),
("wide", Box::new(move |a| late.launch(TOPK_WIDE, n, 1024, stream, a).expect("wide"))),
(
"sample+failed",
Box::new(move |a| {
late.launch(TOPK_SAMPLE, n, 1024, stream, a).expect("sample");
late.launch(TOPK_WIDE_FAILED, n, 1024, stream, a).expect("failed");
}),
),
(
"cluster",
Box::new(move |a| {
cluster
.launch_cluster(crate::qsa_cluster::TOPK_CLUSTER, [8, n], 1024, 8, smem, stream, a)
.expect("cluster")
}),
),
]
}
pub(super) fn bench_case(
rig: &BenchRig<'_>,
rng: &mut Rng,
case: usize,
(p0, rows, style, label): (usize, usize, u8, &str),
) {
let context = rig.context;
let steps = step_bytes(p0, rows);
let scores = bench_scores(rng, rig.max_blocks, (p0, rows, style));
let scores_d = upload(context, &f32_raw(&scores));
let steps_d = upload(context, &steps);
let out_len = rows * CAP * 4;
let variants = topk_variants(rig, rows as u32);
let mut reference: Option<Vec<u8>> = None;
let mut line = format!("QSA-TOPK-BENCH case {case} {label} p0={p0} rows={rows} style={style}:");
for (name, run) in &variants {
if *name == "cluster" && rows > 16 {
continue; // the decode kernel (the upstream dispatch uses it for at most 16 queries)
}
let (got, us) = time_variant(rig, run, (&scores_d, &steps_d), out_len);
match &reference {
None => reference = Some(got),
Some(r) => assert!(
*r == got,
"case {case} (p0 {p0}, rows {rows}, style {style}): {name} ids differ from the original"
),
}
line.push_str(&format!(" {name} {us:.1} us;"));
}
eprintln!("{line} ids equal");
}
/// Runs one variant warm, then 20 launches drained once; returns the ids it wrote and the per-launch microseconds.
pub(super) fn time_variant(
rig: &BenchRig<'_>,
run: &Run<'_>,
inputs: (&DeviceBuffer<'_>, &DeviceBuffer<'_>),
out_len: usize,
) -> (Vec<u8>, f64) {
let (context, reps) = (rig.context, 20);
let ids = upload(context, &vec![0xffu8; out_len]);
let mut a = topk_args(rig.max_blocks, inputs, &ids);
let guard = context.enter().expect("enter");
// the sample kernel flags its failures in a module global that persists: clear by running sample first inside run
run(&mut a);
context.driver.api.synchronize().expect("sync");
let t0 = std::time::Instant::now();
for _ in 0..reps {
run(&mut a);
}
context.driver.api.synchronize().expect("sync");
let us = t0.elapsed().as_secs_f64() * 1e6 / reps as f64;
guard.finish().expect("finish");
(download(&ids, out_len), us)
}
/// Random pooled, dead and query vectors and the steps of one `(pos, nq)` shape, uploaded in that order.
pub(super) fn decode_inputs<'c>(
context: &'c Context<'c>,
rng: &mut Rng,
max_blocks: usize,
(pos, nq): (usize, usize),
) -> [DeviceBuffer<'c>; 4] {
let mut random =
|n: usize| -> Vec<f32> { (0..n).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect() };
let pooled = random((max_blocks + 1) * 128);
let dead = random(128);
let qidx = random(nq * 4 * 128);
let steps = step_bytes(pos, nq);
[
upload(context, &f32_raw(&pooled)),
upload(context, &f32_raw(&dead)),
upload(context, &f32_raw(&qidx)),
upload(context, &steps),
]
}
@@ -0,0 +1,42 @@
//! Moved out of the parent module by STRA-338: fn time_scores_and_topk, fn time_warm.
#[allow(unused_imports)]
use super::*;
/// Times the decode scores kernel and the top-k at one `(pos, nq)` shape, 20 warm launches each.
pub(super) fn time_scores_and_topk(
context: &Context<'_>,
(select, stream, max_blocks): (&KernelModule, usize, usize),
rng: &mut Rng,
(pos, nq): (usize, usize),
) {
let n_bid_max = (pos + nq) / 4;
let [pooled_d, dead_d, qidx_d, steps_d] = decode_inputs(context, rng, max_blocks, (pos, nq));
let scores_d = upload(context, &vec![0u8; nq * max_blocks * 4]);
let ids_d = upload(context, &vec![0xffu8; nq * CAP * 4]);
let guard = context.enter().expect("enter");
let ad = |b: &DeviceBuffer<'_>| A::Address(handle(b));
let (nq_arg, blocks_arg) = (A::I32(nq as i32), A::I64(max_blocks as i64));
let mut sa: Vec<A> = [&pooled_d, &dead_d, &qidx_d, &steps_d].into_iter().map(|b| ad(b)).collect();
sa.extend([nq_arg, blocks_arg, ad(&scores_d)]);
let mut sa = KernelArguments::new(sa);
let scores_us = time_warm(context, &mut || select.launch(0, 256, 256, stream, &mut sa).expect("scores"));
let mut ta = topk_args(max_blocks, (&scores_d, &steps_d), &ids_d);
let topk_us = time_warm(context, &mut || select.launch(1, nq as u32, 256, stream, &mut ta).expect("topk"));
guard.finish().expect("finish");
eprintln!(
"QSA-DECODE-SCORES pos={pos} nq={nq} n_bid={n_bid_max}: qsa_decode_scores {scores_us:.1} us, qsa_topk_ref {topk_us:.1} us (per layer, warm)"
);
}
/// One warm-up run, then 20 timed runs drained once; microseconds per run.
pub(super) fn time_warm(context: &Context<'_>, run: &mut dyn FnMut()) -> f64 {
run();
context.driver.api.synchronize().expect("sync");
let t0 = std::time::Instant::now();
for _ in 0..20 {
run();
}
context.driver.api.synchronize().expect("sync");
t0.elapsed().as_secs_f64() * 1e6 / 20.0
}
@@ -3,362 +3,6 @@
#[allow(unused_imports)]
use super::*;
impl<'ctx> QsaPromptAttention<'ctx> {
pub(super) fn new(c: &'ctx Context<'ctx>) -> Result<Self> {
Self::new_capacity(c, 64)
}
pub(super) fn new_capacity(c: &'ctx Context<'ctx>, capacity: usize) -> Result<Self> {
if !(1..=8192).contains(&capacity) {
return Err(Error::InvalidQwenShape);
}
if c.is_poisoned() {
return Err(Error::ContextPoisoned);
}
let output_bytes = capacity.checked_mul(6144 * 4).ok_or(Error::BudgetExceeded)?;
admit_budget(c, output_bytes)?;
let ptx = include_bytes!("../qsa_prompt_attention.ptx");
let m = crate::qsa_prompt_attention_ffi::load_in_context(
c,
ptx,
&[c"leleka_qsa_prompt_guard", c"leleka_qsa_prompt_attn", c"leleka_qsa_prompt_output_guard"],
)?;
let mut o = Self::with_module(c, capacity, m);
if let Err(e) = o.allocate_buffers(Some(output_bytes)) {
return combine(Err(e), o.close());
}
Ok(o)
}
pub(super) fn with_module(c: &'ctx Context<'ctx>, capacity: usize, module: Module) -> Self {
Self {
capacity,
context: c,
output: None,
status: None,
module: Some(module),
variants: None,
switches: SelectSwitches::default(),
failed: false,
}
}
/// The status word and, when the owner keeps one, the output bank; 128 MiB of device memory must stay free.
pub(super) fn allocate_buffers(&mut self, output_bytes: Option<usize>) -> Result<()> {
let c = self.context;
if let Some(bytes) = output_bytes {
self.output = Some(c.allocate(bytes)?);
}
self.status = Some(c.allocate(4)?);
if c.memory_info()?.0 < 128 * 1024 * 1024 {
return Err(Error::BudgetExceeded);
}
Ok(())
}
pub fn prompt_device_bytes(capacity: usize) -> Result<usize> {
if !(1..=8192).contains(&capacity) {
return Err(Error::InvalidQwenShape);
}
Ok(capacity * 6144 * 4 + 4)
}
pub fn capacity(&self) -> usize {
self.capacity
}
pub fn allocated_bytes(&self) -> usize {
self.output.as_ref().map_or(0, DeviceBuffer::len) + self.status.as_ref().map_or(0, DeviceBuffer::len)
}
pub fn is_failed(&self) -> bool {
self.failed || self.context.is_poisoned()
}
pub(super) fn validate(&self) -> Result<()> {
if self.is_failed() || self.module.is_none() {
return Err(Error::ContextPoisoned);
}
checked(self.context, self.output.as_ref().ok_or(Error::ContextPoisoned)?, self.capacity * 6144 * 4)?;
checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?;
Ok(())
}
pub(super) fn flags(&self) -> Result<u32> {
let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(4)?;
Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::InvalidSize)?))
}
/// Launches one entry of the default module, or of the variants module, on the workspace's stream.
pub(super) fn launch_variant(
&self,
variants: bool,
w: &NativeBatchWorkspace<'ctx>,
(index, grid, block, shared): (usize, [u32; 3], u32, u32),
a: &mut Arguments,
) -> Result<()> {
(if variants { self.variants.as_ref() } else { self.module.as_ref() }).ok_or(Error::ContextPoisoned)?.launch(
index,
grid,
block,
shared,
w.blas()?.stream(),
a,
)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn run_in(
&mut self,
variants: bool,
w: &mut NativeBatchWorkspace<'ctx>,
index: usize,
grid: [u32; 3],
block: u32,
shared: u32,
mut a: Arguments,
) -> Result<()> {
self.validate()?;
w.validate_context(self.context)?;
let g = self.context.enter()?;
let dependency = self.context.driver.api.synchronize();
let op = dependency.and_then(|()| self.launch_variant(variants, w, (index, grid, block, shared), &mut a));
let sync = w.blas()?.synchronize();
let pop = g.finish();
if sync.is_err() || pop.is_err() {
std::mem::forget(a);
}
if op.is_err() || sync.is_err() || pop.is_err() {
self.failed = true;
self.context.poisoned.set(true);
w.mark_failed();
}
combine(combine(op, sync), pop)
}
/// Q/IDs/steps must be genuine completed full producer buffers. Width is steps[3].
/// Driver admission is whole shape/Context/alias and exact bounds; Root authenticates
/// selected provenance/current origin before calling, and consumes only current rows.
pub fn attend<'loan>(
&'loan mut self,
w: &mut NativeBatchWorkspace<'ctx>,
stage: &'loan QsaPromptStage<'ctx>,
kv: &QsaPromptKv<'ctx>,
snapshot: &'loan QsaKvSnapshot,
inputs: &QsaAttentionInputs<'_, '_>,
) -> Result<QsaPromptAttentionCompletion<'loan, 'ctx>> {
self.attend_kernel(PromptAttnKernel::Int8V2, w, stage, kv, snapshot, inputs)
}
/// The Original's `qsa_prompt_attn_batch` kernel choice over these INT8 pools (v2 cp.async by default; the v1
/// kernel on a pre-sm_80 card or with `STRATA_PROMPT_ATTN_V1`), decided by [`select`] from the actual device.
/// A `None` selection (an unsupported card) is a refusal here: the decode-kernel fallback is a different owner.
pub fn attend_selected<'loan>(
&'loan mut self,
w: &mut NativeBatchWorkspace<'ctx>,
stage: &'loan QsaPromptStage<'ctx>,
kv: &QsaPromptKv<'ctx>,
snapshot: &'loan QsaKvSnapshot,
inputs: &QsaAttentionInputs<'_, '_>,
switches: SelectSwitches,
) -> Result<QsaPromptAttentionCompletion<'loan, 'ctx>> {
let caps = self.module.as_ref().ok_or(Error::ContextPoisoned)?.caps();
let device = DeviceCaps { cc_major: caps[0], cc_minor: caps[1], max_shared_optin: caps[2] };
let kernel = select(PoolPresence::int8(), Shapes::QWEN, 2051, true, device, switches)
.ok_or(Error::UnsupportedQwenOperation)?;
self.attend_kernel(kernel, w, stage, kv, snapshot, inputs)
}
/// Explicit replacement of the Original's `STRATA_QSA_WARP` / `STRATA_PROMPT_ATTN_V1` environment reads; the
/// library never reads the environment on its own. The default keeps the v2 kernel on every admitted card.
pub fn set_switches(&mut self, switches: SelectSwitches) {
self.switches = switches;
}
pub(crate) fn selected_kernel(&self) -> Result<PromptAttnKernel> {
let caps = self.module.as_ref().ok_or(Error::ContextPoisoned)?.caps();
let device = DeviceCaps { cc_major: caps[0], cc_minor: caps[1], max_shared_optin: caps[2] };
select(PoolPresence::int8(), Shapes::QWEN, 2051, true, device, self.switches)
.ok_or(Error::UnsupportedQwenOperation)
}
pub(super) fn ensure_variants(&mut self) -> Result<()> {
if self.variants.is_some() {
return Ok(());
}
let g = self.context.enter()?;
let load = Module::load(include_bytes!("../qsa_prompt_attention_variants.ptx"), &VARIANT_ENTRIES);
let pop = g.finish();
match load {
Ok(m) => {
if let Err(e) = pop {
self.context.poisoned.set(true);
std::mem::forget(m);
return Err(e);
}
self.variants = Some(m);
Ok(())
}
Err(e) => combine(Err(e), pop),
}
}
pub(super) fn attend_kernel<'loan>(
&'loan mut self,
kernel: PromptAttnKernel,
w: &mut NativeBatchWorkspace<'ctx>,
stage: &'loan QsaPromptStage<'ctx>,
kv: &QsaPromptKv<'ctx>,
snapshot: &'loan QsaKvSnapshot,
inputs: &QsaAttentionInputs<'_, '_>,
) -> Result<QsaPromptAttentionCompletion<'loan, 'ctx>> {
let plan = KernelPlan::of(kernel)?;
if plan.variants {
self.ensure_variants()?;
}
let t = inputs.t;
self.validate()?;
w.validate_context(self.context)?;
stage.validate(self.context)?;
let [qh, ih, sh] = self.admit_inputs(w, inputs, |b| stage.reject_alias(b))?;
let (pools, table, end) = stage.completed_addresses(kv, snapshot)?;
let status = self.zero_status()?;
let out =
self.output.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?.qwen_address();
let passes = AttnPasses { addrs: [qh, ih, sh, out, status], pools, table, end, t };
self.run_passes(w, &plan, &passes, Self::run_in)?;
Ok(QsaPromptAttentionCompletion { owner: self, _stage: stage, _snapshot: snapshot, t })
}
/// The 1..=capacity query rows and the Q/IDs/steps owners: exact sizes, no alias with the stage, the workspace,
/// this attention's own buffers or each other. Returns the three device addresses.
pub(super) fn admit_inputs(
&self,
w: &NativeBatchWorkspace<'ctx>,
inputs: &QsaAttentionInputs<'_, '_>,
reject_stage: impl Fn(&DeviceBuffer<'_>) -> Result<()>,
) -> Result<[u64; 3]> {
let (q, ids, steps, t) = (inputs.q, inputs.ids, inputs.steps, inputs.t);
if !(1..=self.capacity).contains(&t) {
return Err(Error::InvalidQwenShape);
}
let qh = checked(self.context, q, t * 6144 * 4)?;
let ih = checked(self.context, ids, t * 2051 * 4)?;
let sh = checked(self.context, steps, t * 4 * 4)?;
for b in [q, ids, steps] {
reject_stage(b)?;
w.reject_alias(b.handle.ok_or(Error::ContextPoisoned)?, b.bytes)?;
for own in self.output.iter().chain(self.status.iter()) {
if own.handle.ok_or(Error::ContextPoisoned)?.overlaps(
own.bytes,
b.handle.ok_or(Error::ContextPoisoned)?,
b.bytes,
) {
return Err(Error::OutputAliasesInput);
}
}
}
reject_mutual_alias([q, ids, steps])?;
Ok([qh, ih, sh])
}
/// The query, IDs, steps and attention spans of the arena do not overlap the stage, the workspace or this
/// attention's own buffers.
pub(super) fn reject_span_aliases(
&self,
w: &NativeBatchWorkspace<'ctx>,
t: usize,
spans: [crate::ffi::BufferHandle; 4],
reject_stage: impl Fn(crate::ffi::BufferHandle, usize) -> Result<()>,
) -> Result<()> {
let [hq, hi, hs, out_h] = spans;
for (h, n) in [(hq, t * 6144 * 4), (hi, t * 2051 * 4), (hs, t * 16), (out_h, t * 6144 * 4)] {
reject_stage(h, n)?;
w.reject_alias(h, n)?;
for b in self.output.iter().chain(self.status.iter()) {
if h.overlaps(n, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) {
return Err(Error::OutputAliasesInput);
}
}
}
Ok(())
}
/// Zeroes the status word and returns its address.
pub(super) fn zero_status(&mut self) -> Result<u64> {
self.status.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0; 4])?;
checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)
}
/// The guard scan and fence, the attention kernel and the output finiteness scan, on `run` (`run_in` or
/// `run_resident`).
pub(super) fn run_passes(
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
plan: &KernelPlan,
p: &AttnPasses,
run: Runner<'ctx>,
) -> Result<()> {
let [qh, ih, sh, out, status] = p.addrs;
let (v, t) = (plan.variants, p.t);
self.guard_pass(w, plan, p, run)?;
let mut args = vec![Arg::U64(qh)];
args.extend(p.pools.map(Arg::U64));
args.extend([Arg::U64(p.table), Arg::U64(ih), Arg::U64(sh), Arg::I32(2), Arg::I32(4)]);
args.extend([Arg::F32(1.442_695_0_f32 / 16.0), Arg::U64(out), Arg::I32(2051)]);
run(self, v, w, plan.attn_ix, [t as u32, 2, 1], 128, plan.shared, Arguments::new(args)?)?;
let scan = Arguments::new(vec![Arg::U64(out), Arg::I32((t * 6144) as i32), Arg::U64(status)])?;
run(self, v, w, plan.scan_ix, [guard_grid(t), 1, 1], 256, 0, scan)?;
if self.flags()? != 0 {
return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention"));
}
Ok(())
}
/// Pre-admission scan and fence are mandatory before selected IDs can address pools.
fn guard_pass(
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
plan: &KernelPlan,
p: &AttnPasses,
run: Runner<'ctx>,
) -> Result<()> {
let [qh, ih, sh, _, status] = p.addrs;
let t = p.t;
let end = Arg::I32(p.end as i32);
let guard = Arguments::new(vec![
Arg::U64(qh),
Arg::U64(ih),
Arg::U64(sh),
Arg::I32(t as i32),
Arg::I32(2051),
end,
Arg::U64(status),
])?;
run(self, plan.variants, w, plan.guard_ix, [guard_grid(t), 1, 1], 256, 0, guard)?;
let flags = self.flags()?;
if flags & 2 != 0 {
return Err(Error::InvalidQwenShape);
}
if flags & 1 != 0 {
return Err(Error::InvalidQ8Activation);
}
Ok(())
}
pub fn close(mut self) -> Result<()> {
self.close_inner()
}
/// Unloads a module inside the context; a poisoned context keeps it (and reports the poison) instead.
fn close_module(&self, m: Module) -> Result<()> {
if self.context.is_poisoned() {
std::mem::forget(m);
return Err(Error::ContextPoisoned);
}
match self.context.enter() {
Ok(g) => combine(m.close(), g.finish()),
Err(e) => {
std::mem::forget(m);
Err(e)
}
}
}
pub(super) fn close_inner(&mut self) -> Result<()> {
self.failed = true;
let mut r = Ok(());
if let Some(m) = self.module.take() {
r = self.close_module(m);
}
if let Some(m) = self.variants.take() {
r = combine(r, self.close_module(m));
}
if let Some(b) = self.status.take() {
r = combine(r, b.release());
}
if let Some(b) = self.output.take() {
r = combine(r, b.release());
}
r
}
}
/// `kernel` as the module, the entries (guard, attention, output guard) and the dynamic shared bytes it launches.
pub(super) struct KernelPlan {
pub(super) variants: bool,
@@ -368,21 +12,6 @@ pub(super) struct KernelPlan {
pub(super) shared: u32,
}
impl KernelPlan {
pub(super) fn of(kernel: PromptAttnKernel) -> Result<Self> {
match kernel {
PromptAttnKernel::Int8V2 => {
Ok(Self { variants: false, guard_ix: 0, attn_ix: 1, scan_ix: 2, shared: kernel.smem_bytes() })
}
PromptAttnKernel::Int8V1 => {
Ok(Self { variants: true, guard_ix: 0, attn_ix: 1, scan_ix: 4, shared: kernel.smem_bytes() })
}
// the FP16 / hybrid pools have no Rust owner on this resident INT8 stage
PromptAttnKernel::Fp16 | PromptAttnKernel::HybridK8V4 => Err(Error::UnsupportedQwenOperation),
}
}
}
/// What the three passes address: `addrs` = Q, IDs, steps, output, status; the pools, their table and the cache end.
pub(super) struct AttnPasses {
pub(super) addrs: [u64; 5],
@@ -404,29 +33,10 @@ pub(super) type Runner<'ctx> = fn(
Arguments,
) -> Result<()>;
/// No two of the inputs overlap.
fn reject_mutual_alias(inputs: [&DeviceBuffer<'_>; 3]) -> Result<()> {
for a in inputs {
for b in inputs {
if !std::ptr::eq(a, b)
&& a.handle.ok_or(Error::ContextPoisoned)?.overlaps(
a.bytes,
b.handle.ok_or(Error::ContextPoisoned)?,
b.bytes,
)
{
return Err(Error::OutputAliasesInput);
}
}
}
Ok(())
}
/// The output bank, the status word and the 128 MiB reserve must fit the budget and the free device memory.
pub(super) fn admit_budget(c: &Context<'_>, output_bytes: usize) -> Result<()> {
let n = output_bytes.checked_add(4 + 128 * 1024 * 1024).ok_or(Error::BudgetExceeded)?;
if c.allocated_bytes().checked_add(n).is_none_or(|x| x > c.budget) || c.memory_info()?.0 < n {
return Err(Error::BudgetExceeded);
}
Ok(())
}
mod impl_qsapromptattention_2;
mod impl_qsapromptattention_2_2;
mod reject_mutual_alias_fn;
#[allow(unused_imports)]
pub(super) use reject_mutual_alias_fn::admit_budget;
#[allow(unused_imports)]
use reject_mutual_alias_fn::reject_mutual_alias;
@@ -0,0 +1,189 @@
//! Moved out of the parent module by STRA-338: impl QsaPromptAttention.
#[allow(unused_imports)]
use super::*;
impl<'ctx> QsaPromptAttention<'ctx> {
pub(in super::super) fn new(c: &'ctx Context<'ctx>) -> Result<Self> {
Self::new_capacity(c, 64)
}
pub(in super::super) fn new_capacity(c: &'ctx Context<'ctx>, capacity: usize) -> Result<Self> {
if !(1..=8192).contains(&capacity) {
return Err(Error::InvalidQwenShape);
}
if c.is_poisoned() {
return Err(Error::ContextPoisoned);
}
let output_bytes = capacity.checked_mul(6144 * 4).ok_or(Error::BudgetExceeded)?;
admit_budget(c, output_bytes)?;
let ptx = include_bytes!("../../qsa_prompt_attention.ptx");
let m = crate::qsa_prompt_attention_ffi::load_in_context(
c,
ptx,
&[c"leleka_qsa_prompt_guard", c"leleka_qsa_prompt_attn", c"leleka_qsa_prompt_output_guard"],
)?;
let mut o = Self::with_module(c, capacity, m);
if let Err(e) = o.allocate_buffers(Some(output_bytes)) {
return combine(Err(e), o.close());
}
Ok(o)
}
pub(in super::super) fn with_module(c: &'ctx Context<'ctx>, capacity: usize, module: Module) -> Self {
Self {
capacity,
context: c,
output: None,
status: None,
module: Some(module),
variants: None,
switches: SelectSwitches::default(),
failed: false,
}
}
/// The status word and, when the owner keeps one, the output bank; 128 MiB of device memory must stay free.
pub(in super::super) fn allocate_buffers(&mut self, output_bytes: Option<usize>) -> Result<()> {
let c = self.context;
if let Some(bytes) = output_bytes {
self.output = Some(c.allocate(bytes)?);
}
self.status = Some(c.allocate(4)?);
if c.memory_info()?.0 < 128 * 1024 * 1024 {
return Err(Error::BudgetExceeded);
}
Ok(())
}
pub fn prompt_device_bytes(capacity: usize) -> Result<usize> {
if !(1..=8192).contains(&capacity) {
return Err(Error::InvalidQwenShape);
}
Ok(capacity * 6144 * 4 + 4)
}
pub fn capacity(&self) -> usize {
self.capacity
}
pub fn allocated_bytes(&self) -> usize {
self.output.as_ref().map_or(0, DeviceBuffer::len) + self.status.as_ref().map_or(0, DeviceBuffer::len)
}
pub fn is_failed(&self) -> bool {
self.failed || self.context.is_poisoned()
}
pub(in super::super) fn validate(&self) -> Result<()> {
if self.is_failed() || self.module.is_none() {
return Err(Error::ContextPoisoned);
}
checked(self.context, self.output.as_ref().ok_or(Error::ContextPoisoned)?, self.capacity * 6144 * 4)?;
checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?;
Ok(())
}
pub(in super::super) fn flags(&self) -> Result<u32> {
let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(4)?;
Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::InvalidSize)?))
}
/// Launches one entry of the default module, or of the variants module, on the workspace's stream.
pub(in super::super) fn launch_variant(
&self,
variants: bool,
w: &NativeBatchWorkspace<'ctx>,
(index, grid, block, shared): (usize, [u32; 3], u32, u32),
a: &mut Arguments,
) -> Result<()> {
(if variants { self.variants.as_ref() } else { self.module.as_ref() }).ok_or(Error::ContextPoisoned)?.launch(
index,
grid,
block,
shared,
w.blas()?.stream(),
a,
)
}
#[allow(clippy::too_many_arguments)]
pub(in super::super) fn run_in(
&mut self,
variants: bool,
w: &mut NativeBatchWorkspace<'ctx>,
index: usize,
grid: [u32; 3],
block: u32,
shared: u32,
mut a: Arguments,
) -> Result<()> {
self.validate()?;
w.validate_context(self.context)?;
let g = self.context.enter()?;
let dependency = self.context.driver.api.synchronize();
let op = dependency.and_then(|()| self.launch_variant(variants, w, (index, grid, block, shared), &mut a));
let sync = w.blas()?.synchronize();
let pop = g.finish();
if sync.is_err() || pop.is_err() {
std::mem::forget(a);
}
if op.is_err() || sync.is_err() || pop.is_err() {
self.failed = true;
self.context.poisoned.set(true);
w.mark_failed();
}
combine(combine(op, sync), pop)
}
/// Q/IDs/steps must be genuine completed full producer buffers. Width is steps[3].
/// Driver admission is whole shape/Context/alias and exact bounds; Root authenticates
/// selected provenance/current origin before calling, and consumes only current rows.
pub fn attend<'loan>(
&'loan mut self,
w: &mut NativeBatchWorkspace<'ctx>,
stage: &'loan QsaPromptStage<'ctx>,
kv: &QsaPromptKv<'ctx>,
snapshot: &'loan QsaKvSnapshot,
inputs: &QsaAttentionInputs<'_, '_>,
) -> Result<QsaPromptAttentionCompletion<'loan, 'ctx>> {
self.attend_kernel(PromptAttnKernel::Int8V2, w, stage, kv, snapshot, inputs)
}
/// The Original's `qsa_prompt_attn_batch` kernel choice over these INT8 pools (v2 cp.async by default; the v1
/// kernel on a pre-sm_80 card or with `STRATA_PROMPT_ATTN_V1`), decided by [`select`] from the actual device.
/// A `None` selection (an unsupported card) is a refusal here: the decode-kernel fallback is a different owner.
pub fn attend_selected<'loan>(
&'loan mut self,
w: &mut NativeBatchWorkspace<'ctx>,
stage: &'loan QsaPromptStage<'ctx>,
kv: &QsaPromptKv<'ctx>,
snapshot: &'loan QsaKvSnapshot,
inputs: &QsaAttentionInputs<'_, '_>,
switches: SelectSwitches,
) -> Result<QsaPromptAttentionCompletion<'loan, 'ctx>> {
let caps = self.module.as_ref().ok_or(Error::ContextPoisoned)?.caps();
let device = DeviceCaps { cc_major: caps[0], cc_minor: caps[1], max_shared_optin: caps[2] };
let kernel = select(PoolPresence::int8(), Shapes::QWEN, 2051, true, device, switches)
.ok_or(Error::UnsupportedQwenOperation)?;
self.attend_kernel(kernel, w, stage, kv, snapshot, inputs)
}
/// Explicit replacement of the Original's `STRATA_QSA_WARP` / `STRATA_PROMPT_ATTN_V1` environment reads; the
/// library never reads the environment on its own. The default keeps the v2 kernel on every admitted card.
pub fn set_switches(&mut self, switches: SelectSwitches) {
self.switches = switches;
}
pub(crate) fn selected_kernel(&self) -> Result<PromptAttnKernel> {
let caps = self.module.as_ref().ok_or(Error::ContextPoisoned)?.caps();
let device = DeviceCaps { cc_major: caps[0], cc_minor: caps[1], max_shared_optin: caps[2] };
select(PoolPresence::int8(), Shapes::QWEN, 2051, true, device, self.switches)
.ok_or(Error::UnsupportedQwenOperation)
}
pub(in super::super) fn ensure_variants(&mut self) -> Result<()> {
if self.variants.is_some() {
return Ok(());
}
let g = self.context.enter()?;
let load = Module::load(include_bytes!("../../qsa_prompt_attention_variants.ptx"), &VARIANT_ENTRIES);
let pop = g.finish();
match load {
Ok(m) => {
if let Err(e) = pop {
self.context.poisoned.set(true);
std::mem::forget(m);
return Err(e);
}
self.variants = Some(m);
Ok(())
}
Err(e) => combine(Err(e), pop),
}
}
}
@@ -0,0 +1,193 @@
//! Moved out of the parent module by STRA-338: impl QsaPromptAttention (2), impl KernelPlan.
#[allow(unused_imports)]
use super::*;
impl<'ctx> QsaPromptAttention<'ctx> {
pub(in super::super) fn attend_kernel<'loan>(
&'loan mut self,
kernel: PromptAttnKernel,
w: &mut NativeBatchWorkspace<'ctx>,
stage: &'loan QsaPromptStage<'ctx>,
kv: &QsaPromptKv<'ctx>,
snapshot: &'loan QsaKvSnapshot,
inputs: &QsaAttentionInputs<'_, '_>,
) -> Result<QsaPromptAttentionCompletion<'loan, 'ctx>> {
let plan = KernelPlan::of(kernel)?;
if plan.variants {
self.ensure_variants()?;
}
let t = inputs.t;
self.validate()?;
w.validate_context(self.context)?;
stage.validate(self.context)?;
let [qh, ih, sh] = self.admit_inputs(w, inputs, |b| stage.reject_alias(b))?;
let (pools, table, end) = stage.completed_addresses(kv, snapshot)?;
let status = self.zero_status()?;
let out =
self.output.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?.qwen_address();
let passes = AttnPasses { addrs: [qh, ih, sh, out, status], pools, table, end, t };
self.run_passes(w, &plan, &passes, Self::run_in)?;
Ok(QsaPromptAttentionCompletion { owner: self, _stage: stage, _snapshot: snapshot, t })
}
/// The 1..=capacity query rows and the Q/IDs/steps owners: exact sizes, no alias with the stage, the workspace,
/// this attention's own buffers or each other. Returns the three device addresses.
pub(in super::super) fn admit_inputs(
&self,
w: &NativeBatchWorkspace<'ctx>,
inputs: &QsaAttentionInputs<'_, '_>,
reject_stage: impl Fn(&DeviceBuffer<'_>) -> Result<()>,
) -> Result<[u64; 3]> {
let (q, ids, steps, t) = (inputs.q, inputs.ids, inputs.steps, inputs.t);
if !(1..=self.capacity).contains(&t) {
return Err(Error::InvalidQwenShape);
}
let qh = checked(self.context, q, t * 6144 * 4)?;
let ih = checked(self.context, ids, t * 2051 * 4)?;
let sh = checked(self.context, steps, t * 4 * 4)?;
for b in [q, ids, steps] {
reject_stage(b)?;
w.reject_alias(b.handle.ok_or(Error::ContextPoisoned)?, b.bytes)?;
for own in self.output.iter().chain(self.status.iter()) {
if own.handle.ok_or(Error::ContextPoisoned)?.overlaps(
own.bytes,
b.handle.ok_or(Error::ContextPoisoned)?,
b.bytes,
) {
return Err(Error::OutputAliasesInput);
}
}
}
reject_mutual_alias([q, ids, steps])?;
Ok([qh, ih, sh])
}
/// The query, IDs, steps and attention spans of the arena do not overlap the stage, the workspace or this
/// attention's own buffers.
pub(in super::super) fn reject_span_aliases(
&self,
w: &NativeBatchWorkspace<'ctx>,
t: usize,
spans: [crate::ffi::BufferHandle; 4],
reject_stage: impl Fn(crate::ffi::BufferHandle, usize) -> Result<()>,
) -> Result<()> {
let [hq, hi, hs, out_h] = spans;
for (h, n) in [(hq, t * 6144 * 4), (hi, t * 2051 * 4), (hs, t * 16), (out_h, t * 6144 * 4)] {
reject_stage(h, n)?;
w.reject_alias(h, n)?;
for b in self.output.iter().chain(self.status.iter()) {
if h.overlaps(n, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) {
return Err(Error::OutputAliasesInput);
}
}
}
Ok(())
}
/// Zeroes the status word and returns its address.
pub(in super::super) fn zero_status(&mut self) -> Result<u64> {
self.status.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0; 4])?;
checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)
}
/// The guard scan and fence, the attention kernel and the output finiteness scan, on `run` (`run_in` or
/// `run_resident`).
pub(in super::super) fn run_passes(
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
plan: &KernelPlan,
p: &AttnPasses,
run: Runner<'ctx>,
) -> Result<()> {
let [qh, ih, sh, out, status] = p.addrs;
let (v, t) = (plan.variants, p.t);
self.guard_pass(w, plan, p, run)?;
let mut args = vec![Arg::U64(qh)];
args.extend(p.pools.map(Arg::U64));
args.extend([Arg::U64(p.table), Arg::U64(ih), Arg::U64(sh), Arg::I32(2), Arg::I32(4)]);
args.extend([Arg::F32(1.442_695_0_f32 / 16.0), Arg::U64(out), Arg::I32(2051)]);
run(self, v, w, plan.attn_ix, [t as u32, 2, 1], 128, plan.shared, Arguments::new(args)?)?;
let scan = Arguments::new(vec![Arg::U64(out), Arg::I32((t * 6144) as i32), Arg::U64(status)])?;
run(self, v, w, plan.scan_ix, [guard_grid(t), 1, 1], 256, 0, scan)?;
if self.flags()? != 0 {
return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention"));
}
Ok(())
}
/// Pre-admission scan and fence are mandatory before selected IDs can address pools.
pub(super) fn guard_pass(
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
plan: &KernelPlan,
p: &AttnPasses,
run: Runner<'ctx>,
) -> Result<()> {
let [qh, ih, sh, _, status] = p.addrs;
let t = p.t;
let end = Arg::I32(p.end as i32);
let guard = Arguments::new(vec![
Arg::U64(qh),
Arg::U64(ih),
Arg::U64(sh),
Arg::I32(t as i32),
Arg::I32(2051),
end,
Arg::U64(status),
])?;
run(self, plan.variants, w, plan.guard_ix, [guard_grid(t), 1, 1], 256, 0, guard)?;
let flags = self.flags()?;
if flags & 2 != 0 {
return Err(Error::InvalidQwenShape);
}
if flags & 1 != 0 {
return Err(Error::InvalidQ8Activation);
}
Ok(())
}
pub fn close(mut self) -> Result<()> {
self.close_inner()
}
/// Unloads a module inside the context; a poisoned context keeps it (and reports the poison) instead.
pub(super) fn close_module(&self, m: Module) -> Result<()> {
if self.context.is_poisoned() {
std::mem::forget(m);
return Err(Error::ContextPoisoned);
}
match self.context.enter() {
Ok(g) => combine(m.close(), g.finish()),
Err(e) => {
std::mem::forget(m);
Err(e)
}
}
}
pub(in super::super) fn close_inner(&mut self) -> Result<()> {
self.failed = true;
let mut r = Ok(());
if let Some(m) = self.module.take() {
r = self.close_module(m);
}
if let Some(m) = self.variants.take() {
r = combine(r, self.close_module(m));
}
if let Some(b) = self.status.take() {
r = combine(r, b.release());
}
if let Some(b) = self.output.take() {
r = combine(r, b.release());
}
r
}
}
impl KernelPlan {
pub(in super::super) fn of(kernel: PromptAttnKernel) -> Result<Self> {
match kernel {
PromptAttnKernel::Int8V2 => {
Ok(Self { variants: false, guard_ix: 0, attn_ix: 1, scan_ix: 2, shared: kernel.smem_bytes() })
}
PromptAttnKernel::Int8V1 => {
Ok(Self { variants: true, guard_ix: 0, attn_ix: 1, scan_ix: 4, shared: kernel.smem_bytes() })
}
// the FP16 / hybrid pools have no Rust owner on this resident INT8 stage
PromptAttnKernel::Fp16 | PromptAttnKernel::HybridK8V4 => Err(Error::UnsupportedQwenOperation),
}
}
}
@@ -0,0 +1,31 @@
//! Moved out of the parent module by STRA-338: fn reject_mutual_alias, fn admit_budget.
#[allow(unused_imports)]
use super::*;
/// No two of the inputs overlap.
pub(super) fn reject_mutual_alias(inputs: [&DeviceBuffer<'_>; 3]) -> Result<()> {
for a in inputs {
for b in inputs {
if !std::ptr::eq(a, b)
&& a.handle.ok_or(Error::ContextPoisoned)?.overlaps(
a.bytes,
b.handle.ok_or(Error::ContextPoisoned)?,
b.bytes,
)
{
return Err(Error::OutputAliasesInput);
}
}
}
Ok(())
}
/// The output bank, the status word and the 128 MiB reserve must fit the budget and the free device memory.
pub(in super::super) fn admit_budget(c: &Context<'_>, output_bytes: usize) -> Result<()> {
let n = output_bytes.checked_add(4 + 128 * 1024 * 1024).ok_or(Error::BudgetExceeded)?;
if c.allocated_bytes().checked_add(n).is_none_or(|x| x > c.budget) || c.memory_info()?.0 < n {
return Err(Error::BudgetExceeded);
}
Ok(())
}
@@ -20,55 +20,7 @@ thread_local! {
static CANCELLED_ON_COPY: Cell<bool> = const { Cell::new(false) };
static PACKETS: RefCell<Option<Vec<Box<[f32]>>>> = const { RefCell::new(None) };
}
pub(super) fn policy(actual: bool) -> bool {
actual && !OLD.get()
}
pub(super) fn copy_completed() {
COPIED.set(true);
}
pub(super) fn observe_packet(packet: &DeviceBuffer<'_>) -> Result<()> {
PACKETS.with(|slot| {
let mut slot = slot.borrow_mut();
let Some(packets) = slot.as_mut() else {
return Ok(());
};
if packets.len() >= 3 {
return Err(Error::InvalidDimension);
}
packets.push(download_f32(packet, K * N)?);
Ok(())
})
}
struct Observation;
impl Observation {
fn begin(old: bool) -> Result<Self> {
let mut rows = Vec::new();
rows.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
PACKETS.with(|slot| -> Result<()> {
if slot.borrow().is_some() {
return Err(Error::IdentityMismatch);
}
*slot.borrow_mut() = Some(rows);
Ok(())
})?;
OLD.set(old);
COPIED.set(false);
CANCELLED_ON_COPY.set(false);
Ok(Self)
}
fn take(&self) -> Result<Vec<Box<[f32]>>> {
PACKETS.with(|slot| slot.borrow_mut().take().ok_or(Error::IdentityMismatch))
}
}
impl Drop for Observation {
fn drop(&mut self) {
OLD.set(false);
COPIED.set(false);
PACKETS.with(|slot| {
slot.borrow_mut().take();
});
}
}
pub(crate) struct DirectDownReport {
differences: usize,
words: usize,
@@ -77,199 +29,8 @@ pub(crate) struct DirectDownReport {
reset_exact: bool,
guards: bool,
}
impl DirectDownReport {
/// The loaded caller retains this report, then closes every cache/session
/// and Context before asserting. This is not an all48/target commit proof.
pub(crate) fn assert_after_teardown(self) {
assert_eq!(self.differences, 0);
assert!(self.cancelled_after_copy && self.allocated_unchanged && self.reset_exact && self.guards);
eprintln!(
"direct native Down PASS exact_words={} original_copy_first=true real_rows=true \
packet_mapping=true signedzero=true \
postcopy_cancel=true cleanup_checked=true full_model=false speed_claim=false",
self.words
);
}
}
fn compare(a: &[Box<[f32]>], b: &[Box<[f32]>]) -> Result<(usize, usize)> {
if a.len() != b.len() {
return Err(Error::IdentityMismatch);
}
let mut differences = 0;
let mut words = 0;
for (a, b) in a.iter().zip(b) {
if a.len() != b.len() {
return Err(Error::InvalidDimension);
}
validate_values(a, a.len())?;
validate_values(b, b.len())?;
differences += a.iter().zip(b.iter()).filter(|(a, b)| a.to_bits() != b.to_bits()).count();
words += a.len();
}
Ok((differences, words))
}
type ObservedArm = (Vec<ExpertReady>, Vec<Box<[f32]>>);
fn arm_consume_inputs<'ctx>(
binding: &ModelBinding,
kar: &mut KarPleCache<'_>,
chunk: &mut QwenChunkTxn<'_, 'ctx>,
) -> Result<()> {
for index in 0..3 {
let (token, position) = chunk.row_ids(index)?;
chunk.input(index, |txn| InputStage::consume_kar(binding, kar, token, position, txn))?;
}
Ok(())
}
fn arm_attention_reads<'ctx>(
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
layer: LayerId,
chunk: &mut QwenChunkTxn<'_, 'ctx>,
) -> Result<Vec<ChunkAttentionRow>> {
let mut reads = Vec::new();
reads.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
for index in 0..3 {
reads.push(chunk.read_attention_column(index, layer, |txn| {
let read = GrStage::apply(binding, layer, txn, Some(dense))?;
GrStage::detach_attention(binding, read, txn)
})?);
}
Ok(reads)
}
fn arm_ffn_rows<'ctx>(
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
layer: LayerId,
chunk: &mut QwenChunkTxn<'_, 'ctx>,
reads: &[ChunkAttentionRow],
) -> Result<Vec<ChunkFfnRow>> {
let mut rows = Vec::new();
rows.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
for (index, read) in reads.iter().enumerate() {
rows.push(chunk.prepare_attention_ffn(index, layer, read, |txn, residual| {
arm_prepare_row(binding, dense, layer, txn, residual)
})?);
}
Ok(rows)
}
fn arm_prepare_row<'ctx>(
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
layer: LayerId,
txn: &mut QwenStepTxn<'_, 'ctx>,
residual: &DetachedGrRead,
) -> Result<PreparedMoeRow> {
let prior = txn.gdn_prior(layer)?;
let mut attention = GdnStage::step(binding, layer, residual.ready(), &prior, txn, Some(dense))?;
attention.validate_origin(&binding.identity())?;
let pending = attention.take_pending()?;
txn.stage_gdn(&prior, pending)?;
let retained = GrStage::inject_retained(binding, residual, attention.output(), attention.identity(), txn, dense)?;
let ffn = GrStage::read_retained_ffn(binding, retained, txn, dense)?;
let route = MoeRouteStage::route_from_ffn(binding, layer, ffn.ready(), txn, Some(dense))?;
MoeExpertStage::prepare_chunk_row(binding, layer, ffn, route, txn)
}
fn arm_tokens() -> Result<(LayerId, [TokenId; 3])> {
let layer = LayerId::new(0, Dimension::new(48)?)?;
let vocab = Dimension::new(248320)?;
Ok((layer, [TokenId::new(0, vocab)?, TokenId::new(1, vocab)?, TokenId::new(0, vocab)?]))
}
fn arm_chunk_rows<'ctx>(
binding: &ModelBinding,
kar: &mut KarPleCache<'_>,
dense: &DenseWeightCache<'ctx>,
layer: LayerId,
chunk: &mut QwenChunkTxn<'_, 'ctx>,
) -> Result<Vec<ChunkFfnRow>> {
arm_consume_inputs(binding, kar, chunk)?;
let reads = arm_attention_reads(binding, dense, layer, chunk)?;
arm_ffn_rows(binding, dense, layer, chunk, &reads)
}
fn cancel_probe(cancel_after_copy: bool) -> bool {
let cancel = cancel_after_copy && COPIED.get();
if cancel {
CANCELLED_ON_COPY.set(true);
}
cancel
}
#[allow(clippy::too_many_arguments)]
fn arm<'ctx>(
binding: &ModelBinding,
context: &Rc<Context<'ctx>>,
session: &mut QwenSession<'ctx>,
kar: &mut KarPleCache<'_>,
cache: &mut MoeWeightCache<'ctx>,
dense: &DenseWeightCache<'ctx>,
old: bool,
cancel_after_copy: bool,
) -> Result<ObservedArm> {
let observation = Observation::begin(old)?;
let (layer, tokens) = arm_tokens()?;
let transient = 3 * (K * N * 4 + 10240 + 2884 + 3 * FF * 4 + N * 4 + 720) + DEVICE_PEAK;
cache.reserve_mmq_transient(binding, context, transient)?;
let mut chunk = QwenChunkTxn::begin(session, binding, &tokens, None, 512 * 1024 * 1024)?;
let rows = arm_chunk_rows(binding, kar, dense, layer, &mut chunk)?;
let values = MoeExpertStage::execute_chunk(binding, layer, &rows, &mut chunk, cache, &mut || {
cancel_probe(cancel_after_copy)
})?;
let packets = observation.take()?;
// Completed layer0 FFN products remain private: no injection/head/all48 or
// joint target publication. A canceled real chunk is dropped, not repaired.
drop(chunk);
Ok((values, packets))
}
const SLOTS: [usize; 3] = [9, 0, 4];
fn probe_payload() -> Result<Vec<f32>> {
let mut payload = Vec::new();
payload.try_reserve_exact(3 * N).map_err(|_| Error::InputAllocation)?;
for c in 0..3 {
for i in 0..N {
payload.push(if i % 11 == 0 {
-0.0
} else if i % 13 == 0 {
0.0
} else {
(c as f32 + 1.0) * (i as f32 - 1279.0) / 1024.0
});
}
}
Ok(payload)
}
/// Column and slot of copy `c` in the all-copy preflight: the last copy is made invalid in column or in slot.
fn preflight_copy(bad_column: bool, c: usize) -> (u32, u32) {
(if bad_column && c == 2 { 3 } else { c as u32 }, if !bad_column && c == 2 { 10 } else { SLOTS[c] as u32 })
}
fn corrupted_bytes(payload: &[f32], invalid: f32) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
bytes.try_reserve_exact(payload.len() * 4).map_err(|_| Error::InputAllocation)?;
for (i, v) in payload.iter().copied().enumerate() {
bytes.extend_from_slice(&(if i == 2 * N + 17 { invalid } else { v }).to_le_bytes());
}
Ok(bytes)
}
fn refuse_alien_scope<'ctx>(
scope: &DownScope<'ctx>,
alien_scope: &DownScope<'ctx>,
packet: &mut super::super::moe_down::ResidentPackedDown<'ctx>,
) -> Result<()> {
if packet.complete(scope).is_ok() {
return Err(Error::IdentityMismatch);
}
let called = Cell::new(false);
let refusal =
super::super::moe_down::ResidentPackedDown::copy_group_with(alien_scope, &mut [(&mut *packet, 0)], |_| {
called.set(true);
Ok(())
});
if !matches!(refusal, Err(Error::IdentityMismatch)) || called.get() {
return Err(Error::IdentityMismatch);
}
// A refused packet cannot be completed/reused within the old scope.
if packet.complete(scope).is_ok() {
return Err(Error::IdentityMismatch);
}
Ok(())
}
/// Genuine selected rows supply scope/origin; both packet sets and the source stay owned for the final close.
struct Probe<'a, 'ctx> {
context: &'ctx Context<'ctx>,
@@ -279,165 +40,6 @@ struct Probe<'a, 'ctx> {
old_parts: Vec<TransportBuffer<'ctx>>,
direct_parts: Vec<TransportBuffer<'ctx>>,
}
impl<'ctx> Probe<'_, 'ctx> {
fn run(&mut self) -> Result<bool> {
self.fill_sentinels()?;
self.split_and_pack_old()?;
self.copy_direct()?;
self.require_old_equals_direct()?;
let before = self.download_direct()?;
self.refuse_invalid_preflight()?;
self.require_direct_unchanged(before)?;
self.refuse_alien_packet_scope()?;
self.refuse_nonfinite_source()?;
Ok(true)
}
/// Both whole packets are sentinel initialized, so every untouched slot
/// is compared too. Original scalar copies establish the reference.
fn fill_sentinels(&mut self) -> Result<()> {
let mut sentinel = Vec::new();
sentinel.try_reserve_exact(K * N).map_err(|_| Error::InputAllocation)?;
sentinel.resize(K * N, 17.0);
for _ in 0..3 {
self.old_parts.push(self.scope.upload(&sentinel)?);
self.direct_parts.push(self.scope.upload(&sentinel)?);
}
Ok(())
}
fn split_and_pack_old(&mut self) -> Result<()> {
for (c, slot) in SLOTS.iter().enumerate() {
let mut split = self.scope.allocate(N * 4)?;
let op = self
.context
.copy_routed_down_column(self.source.buffer()?, 3, c, split.buffer_mut()?)
.map_err(driver_error)
.and_then(|()| {
self.context
.pack_moe_down_f32(split.buffer()?, self.old_parts[c].buffer_mut()?, *slot as u32)
.map_err(driver_error)
});
let close = split.close();
op?;
close?;
}
Ok(())
}
fn copy_direct(&mut self) -> Result<()> {
let mut copies = Vec::new();
copies.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
for (c, part) in self.direct_parts.iter_mut().enumerate() {
copies.push((c as u32, part.buffer_mut()?, SLOTS[c] as u32));
}
self.context.copy_routed_down_columns_to_slots(self.source.buffer()?, 3, &mut copies).map_err(driver_error)
}
fn require_old_equals_direct(&self) -> Result<()> {
for (old, new) in self.old_parts.iter().zip(&self.direct_parts) {
let a = download_f32(old.buffer()?, K * N)?;
let b = download_f32(new.buffer()?, K * N)?;
if a.iter().zip(b.iter()).any(|(a, b)| a.to_bits() != b.to_bits()) {
return Err(Error::IdentityMismatch);
}
}
Ok(())
}
fn download_direct(&self) -> Result<Vec<Box<[f32]>>> {
let mut before = Vec::new();
before.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
for part in &self.direct_parts {
before.push(download_f32(part.buffer()?, K * N)?);
}
Ok(before)
}
/// All-copy preflight: last slot/column invalid cannot mutate earlier
/// valid destinations. Exact full-size genuine buffers, not fake aliases.
fn refuse_invalid_preflight(&mut self) -> Result<()> {
for bad_column in [false, true] {
let mut copies = Vec::new();
copies.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
for (c, part) in self.direct_parts.iter_mut().enumerate() {
let (column, slot) = preflight_copy(bad_column, c);
copies.push((column, part.buffer_mut()?, slot));
}
let refused = self.context.copy_routed_down_columns_to_slots(self.source.buffer()?, 3, &mut copies);
if !matches!(refused, Err(DriverError::InvalidProjectionShape)) {
return Err(Error::IdentityMismatch);
}
}
Ok(())
}
fn require_direct_unchanged(&self, before: Vec<Box<[f32]>>) -> Result<()> {
for (part, before) in self.direct_parts.iter().zip(before) {
let after = download_f32(part.buffer()?, K * N)?;
if before.iter().zip(after.iter()).any(|(a, b)| a.to_bits() != b.to_bits()) {
return Err(Error::IdentityMismatch);
}
}
Ok(())
}
fn refuse_alien_packet_scope(&self) -> Result<()> {
let alien_scope = DownScope::new(self.context, Rc::new(Cell::new(false)));
let mut packet = super::super::moe_down::ResidentPackedDown::new(self.scope)?;
let scope_guard = refuse_alien_scope(self.scope, &alien_scope, &mut packet);
let close = packet.close();
scope_guard?;
close?;
Ok(())
}
/// Full finite source refusal precedes any copy callback, including an
/// interior NaN; the old producer is evaluated first on exact bytes.
fn refuse_nonfinite_source(&self) -> Result<()> {
let selections = SLOTS.map(DownSelection::Routed);
for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
let bytes = corrupted_bytes(self.payload, invalid)?;
let old = self.scope.project_columns(
&selections,
|out, _| out.copy_from(&bytes).map_err(driver_error),
&mut || false,
);
let called = Cell::new(false);
let new = self.scope.project_columns_direct(
&selections,
|out, _| out.copy_from(&bytes).map_err(driver_error),
|_, _| {
called.set(true);
Ok(())
},
&mut || false,
);
if !matches!(old, Err(Error::NonFinite)) || !matches!(new, Err(Error::NonFinite)) || called.get() {
return Err(Error::IdentityMismatch);
}
}
Ok(())
}
fn close_all(self) -> Result<()> {
let mut cleanup = Ok(());
for owner in self.old_parts.into_iter().chain(self.direct_parts).chain(std::iter::once(self.source)) {
let next = owner.close();
if cleanup.is_ok() {
cleanup = next;
}
}
cleanup
}
}
// Independent byte-only old split+pack FIRST, then direct whole-group copy.
// Genuine selected rows supply scope/origin. The finite payload deliberately
// contains both signed zeros and different columns/slots; no model state is faked.
fn transport_probe(context: &Context<'_>) -> Result<bool> {
let failed = Rc::new(Cell::new(false));
let scope = DownScope::new(context, failed.clone());
let payload = probe_payload()?;
let source = scope.upload(&payload)?;
let mut probe =
Probe { context, scope: &scope, payload: &payload, source, old_parts: Vec::new(), direct_parts: Vec::new() };
probe.old_parts.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
probe.direct_parts.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
let operation = probe.run();
scope.record(&operation);
let cleanup = probe.close_all();
operation.and_then(|value| cleanup.map(|()| value))
}
/// What the first two arms and the cancelled arm established; the reference outputs and packets stay for recovery.
struct DirectRun {
reference: Vec<ExpertReady>,
@@ -447,21 +49,6 @@ struct DirectRun {
differences: usize,
words: usize,
}
fn output_differences(reference: &[ExpertReady], candidate: &[ExpertReady]) -> Result<usize> {
let mut differences = 0;
for (a, b) in reference.iter().zip(candidate) {
validate_values(a.output(), N)?;
validate_values(b.output(), N)?;
differences += a.output().iter().zip(b.output()).filter(|(a, b)| a.to_bits() != b.to_bits()).count();
}
Ok(differences)
}
fn same_outputs(reference: &[ExpertReady], recovery: &[ExpertReady]) -> bool {
reference
.iter()
.zip(recovery)
.all(|(a, b)| a.output().iter().zip(b.output()).all(|(a, b)| a.to_bits() == b.to_bits()))
}
/// The loaded direct-Down inputs of one fresh session; every arm is run against the same snapshot.
struct LoadedArms<'a, 'k, 'ctx> {
binding: &'a ModelBinding,
@@ -471,86 +58,50 @@ struct LoadedArms<'a, 'k, 'ctx> {
cache: &'a mut MoeWeightCache<'ctx>,
dense: &'a DenseWeightCache<'ctx>,
}
impl LoadedArms<'_, '_, '_> {
fn arm(&mut self, old: bool, cancel_after_copy: bool) -> Result<ObservedArm> {
arm(self.binding, self.context, self.session, self.kar, self.cache, self.dense, old, cancel_after_copy)
}
fn matches_snapshot(&self, initial: &ResetReplaySnapshot) -> Result<bool> {
Ok(initial.numeric_eq(&self.session.test_reset_replay_snapshot(self.binding)?))
}
fn precheck(&self) -> Result<ResetReplaySnapshot> {
self.cache.validate(self.binding, self.context)?;
self.dense.retained_context(self.binding, self.context)?;
if !self.cache.uses_direct_native_down_packets() {
return Err(Error::IdentityMismatch);
}
let initial = self.session.test_reset_replay_snapshot(self.binding)?;
if !initial.has_prefix(0, [-1, -1]) {
return Err(Error::IdentityMismatch);
}
Ok(initial)
}
fn reference_and_candidate(&mut self, initial: &ResetReplaySnapshot) -> Result<DirectRun> {
let (reference, old_packets) = self.arm(true, false)?;
let original_unchanged = self.matches_snapshot(initial)?;
let allocated = self.context.allocated_bytes();
let (candidate, new_packets) = self.arm(false, false)?;
if [reference.len(), candidate.len(), old_packets.len(), new_packets.len()].iter().any(|n| *n != 3) {
return Err(Error::IdentityMismatch);
}
let (mut differences, mut words) = compare(&old_packets, &new_packets)?;
differences += output_differences(&reference, &candidate)?;
words += reference.len() * N;
Ok(DirectRun { reference, old_packets, original_unchanged, allocated, differences, words })
}
/// A cancelled arm is refused after the original copy and leaves the session snapshot untouched.
fn cancelled_arm(&mut self, initial: &ResetReplaySnapshot) -> Result<bool> {
Ok(matches!(self.arm(false, true), Err(Error::Unsupported(Stage::Executor)))
&& CANCELLED_ON_COPY.get()
&& self.matches_snapshot(initial)?)
}
/// After a reset the recovery arm reproduces the reference outputs and the old packets.
fn cancel_and_recover(&mut self, initial: &ResetReplaySnapshot, run: &mut DirectRun) -> Result<(bool, bool)> {
let cancelled_after_copy = self.cancelled_arm(initial)?;
self.session.reset()?;
let reset_prefix = self.matches_snapshot(initial)?;
let (recovery, recovered_packets) = self.arm(false, false)?;
if recovery.len() != 3 || recovered_packets.len() != 3 {
return Err(Error::IdentityMismatch);
}
let (d, n) = compare(&run.old_packets, &recovered_packets)?;
run.differences += d;
run.words += n;
let reset_exact = run.original_unchanged && reset_prefix && same_outputs(&run.reference, &recovery);
Ok((cancelled_after_copy, reset_exact))
}
}
impl QwenForward {
/// ONE genuine loaded binding/fresh session. Every arm independently mints
/// real three-row chunk/FFN proofs; canceled chunks are dropped unchanged.
pub(crate) fn test_direct_down_on_loaded<'ctx>(
binding: &ModelBinding,
context: &Rc<Context<'ctx>>,
session: &mut QwenSession<'ctx>,
kar: &mut KarPleCache<'_>,
cache: &mut MoeWeightCache<'ctx>,
dense: &DenseWeightCache<'ctx>,
) -> Result<DirectDownReport> {
let mut arms = LoadedArms { binding, context, session, kar, cache, dense };
let initial = arms.precheck()?;
let mut run = arms.reference_and_candidate(&initial)?;
let (cancelled_after_copy, reset_exact) = arms.cancel_and_recover(&initial, &mut run)?;
let guards = transport_probe(context)?;
if run.words != 3 * (2 * K * N + N) {
return Err(Error::IdentityMismatch);
}
Ok(DirectDownReport {
differences: run.differences,
words: run.words,
cancelled_after_copy,
reset_exact,
guards,
allocated_unchanged: run.allocated == context.allocated_bytes(),
})
}
}
#[path = "moe_group_down_direct_gpu/policy_fn.rs"]
mod policy_fn;
#[allow(unused_imports)]
use policy_fn::arm_attention_reads;
#[allow(unused_imports)]
use policy_fn::arm_chunk_rows;
#[allow(unused_imports)]
use policy_fn::arm_consume_inputs;
#[allow(unused_imports)]
use policy_fn::arm_ffn_rows;
#[allow(unused_imports)]
use policy_fn::arm_prepare_row;
#[allow(unused_imports)]
use policy_fn::arm_tokens;
#[allow(unused_imports)]
use policy_fn::cancel_probe;
#[allow(unused_imports)]
use policy_fn::compare;
#[allow(unused_imports)]
pub(super) use policy_fn::copy_completed;
#[allow(unused_imports)]
pub(super) use policy_fn::observe_packet;
#[allow(unused_imports)]
pub(super) use policy_fn::policy;
#[path = "moe_group_down_direct_gpu/arm_fn.rs"]
mod arm_fn;
#[allow(unused_imports)]
use arm_fn::arm;
#[allow(unused_imports)]
use arm_fn::corrupted_bytes;
#[allow(unused_imports)]
use arm_fn::preflight_copy;
#[allow(unused_imports)]
use arm_fn::probe_payload;
#[allow(unused_imports)]
use arm_fn::refuse_alien_scope;
#[path = "moe_group_down_direct_gpu/impl_probe.rs"]
mod impl_probe;
#[allow(unused_imports)]
use impl_probe::output_differences;
#[allow(unused_imports)]
use impl_probe::same_outputs;
#[allow(unused_imports)]
use impl_probe::transport_probe;
#[path = "moe_group_down_direct_gpu/impl_loadedarms.rs"]
mod impl_loadedarms;
@@ -0,0 +1,85 @@
//! Moved out of the parent module by STRA-338.
#[allow(unused_imports)]
use super::*;
#[allow(clippy::too_many_arguments)]
pub(super) fn arm<'ctx>(
binding: &ModelBinding,
context: &Rc<Context<'ctx>>,
session: &mut QwenSession<'ctx>,
kar: &mut KarPleCache<'_>,
cache: &mut MoeWeightCache<'ctx>,
dense: &DenseWeightCache<'ctx>,
old: bool,
cancel_after_copy: bool,
) -> Result<ObservedArm> {
let observation = Observation::begin(old)?;
let (layer, tokens) = arm_tokens()?;
let transient = 3 * (K * N * 4 + 10240 + 2884 + 3 * FF * 4 + N * 4 + 720) + DEVICE_PEAK;
cache.reserve_mmq_transient(binding, context, transient)?;
let mut chunk = QwenChunkTxn::begin(session, binding, &tokens, None, 512 * 1024 * 1024)?;
let rows = arm_chunk_rows(binding, kar, dense, layer, &mut chunk)?;
let values = MoeExpertStage::execute_chunk(binding, layer, &rows, &mut chunk, cache, &mut || {
cancel_probe(cancel_after_copy)
})?;
let packets = observation.take()?;
// Completed layer0 FFN products remain private: no injection/head/all48 or
// joint target publication. A canceled real chunk is dropped, not repaired.
drop(chunk);
Ok((values, packets))
}
pub(super) fn probe_payload() -> Result<Vec<f32>> {
let mut payload = Vec::new();
payload.try_reserve_exact(3 * N).map_err(|_| Error::InputAllocation)?;
for c in 0..3 {
for i in 0..N {
payload.push(if i % 11 == 0 {
-0.0
} else if i % 13 == 0 {
0.0
} else {
(c as f32 + 1.0) * (i as f32 - 1279.0) / 1024.0
});
}
}
Ok(payload)
}
/// Column and slot of copy `c` in the all-copy preflight: the last copy is made invalid in column or in slot.
pub(super) fn preflight_copy(bad_column: bool, c: usize) -> (u32, u32) {
(if bad_column && c == 2 { 3 } else { c as u32 }, if !bad_column && c == 2 { 10 } else { SLOTS[c] as u32 })
}
pub(super) fn corrupted_bytes(payload: &[f32], invalid: f32) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
bytes.try_reserve_exact(payload.len() * 4).map_err(|_| Error::InputAllocation)?;
for (i, v) in payload.iter().copied().enumerate() {
bytes.extend_from_slice(&(if i == 2 * N + 17 { invalid } else { v }).to_le_bytes());
}
Ok(bytes)
}
pub(super) fn refuse_alien_scope<'ctx>(
scope: &DownScope<'ctx>,
alien_scope: &DownScope<'ctx>,
packet: &mut super::super::super::moe_down::ResidentPackedDown<'ctx>,
) -> Result<()> {
if packet.complete(scope).is_ok() {
return Err(Error::IdentityMismatch);
}
let called = Cell::new(false);
let refusal = super::super::super::moe_down::ResidentPackedDown::copy_group_with(
alien_scope,
&mut [(&mut *packet, 0)],
|_| {
called.set(true);
Ok(())
},
);
if !matches!(refusal, Err(Error::IdentityMismatch)) || called.get() {
return Err(Error::IdentityMismatch);
}
// A refused packet cannot be completed/reused within the old scope.
if packet.complete(scope).is_ok() {
return Err(Error::IdentityMismatch);
}
Ok(())
}
@@ -0,0 +1,92 @@
//! Moved out of the parent module by STRA-338: impl LoadedArms, impl QwenForward.
#[allow(unused_imports)]
use super::*;
impl LoadedArms<'_, '_, '_> {
pub(super) fn arm(&mut self, old: bool, cancel_after_copy: bool) -> Result<ObservedArm> {
arm(self.binding, self.context, self.session, self.kar, self.cache, self.dense, old, cancel_after_copy)
}
pub(super) fn matches_snapshot(&self, initial: &ResetReplaySnapshot) -> Result<bool> {
Ok(initial.numeric_eq(&self.session.test_reset_replay_snapshot(self.binding)?))
}
pub(super) fn precheck(&self) -> Result<ResetReplaySnapshot> {
self.cache.validate(self.binding, self.context)?;
self.dense.retained_context(self.binding, self.context)?;
if !self.cache.uses_direct_native_down_packets() {
return Err(Error::IdentityMismatch);
}
let initial = self.session.test_reset_replay_snapshot(self.binding)?;
if !initial.has_prefix(0, [-1, -1]) {
return Err(Error::IdentityMismatch);
}
Ok(initial)
}
pub(super) fn reference_and_candidate(&mut self, initial: &ResetReplaySnapshot) -> Result<DirectRun> {
let (reference, old_packets) = self.arm(true, false)?;
let original_unchanged = self.matches_snapshot(initial)?;
let allocated = self.context.allocated_bytes();
let (candidate, new_packets) = self.arm(false, false)?;
if [reference.len(), candidate.len(), old_packets.len(), new_packets.len()].iter().any(|n| *n != 3) {
return Err(Error::IdentityMismatch);
}
let (mut differences, mut words) = compare(&old_packets, &new_packets)?;
differences += output_differences(&reference, &candidate)?;
words += reference.len() * N;
Ok(DirectRun { reference, old_packets, original_unchanged, allocated, differences, words })
}
/// A cancelled arm is refused after the original copy and leaves the session snapshot untouched.
pub(super) fn cancelled_arm(&mut self, initial: &ResetReplaySnapshot) -> Result<bool> {
Ok(matches!(self.arm(false, true), Err(Error::Unsupported(Stage::Executor)))
&& CANCELLED_ON_COPY.get()
&& self.matches_snapshot(initial)?)
}
/// After a reset the recovery arm reproduces the reference outputs and the old packets.
pub(super) fn cancel_and_recover(
&mut self,
initial: &ResetReplaySnapshot,
run: &mut DirectRun,
) -> Result<(bool, bool)> {
let cancelled_after_copy = self.cancelled_arm(initial)?;
self.session.reset()?;
let reset_prefix = self.matches_snapshot(initial)?;
let (recovery, recovered_packets) = self.arm(false, false)?;
if recovery.len() != 3 || recovered_packets.len() != 3 {
return Err(Error::IdentityMismatch);
}
let (d, n) = compare(&run.old_packets, &recovered_packets)?;
run.differences += d;
run.words += n;
let reset_exact = run.original_unchanged && reset_prefix && same_outputs(&run.reference, &recovery);
Ok((cancelled_after_copy, reset_exact))
}
}
impl QwenForward {
/// ONE genuine loaded binding/fresh session. Every arm independently mints
/// real three-row chunk/FFN proofs; canceled chunks are dropped unchanged.
pub(crate) fn test_direct_down_on_loaded<'ctx>(
binding: &ModelBinding,
context: &Rc<Context<'ctx>>,
session: &mut QwenSession<'ctx>,
kar: &mut KarPleCache<'_>,
cache: &mut MoeWeightCache<'ctx>,
dense: &DenseWeightCache<'ctx>,
) -> Result<DirectDownReport> {
let mut arms = LoadedArms { binding, context, session, kar, cache, dense };
let initial = arms.precheck()?;
let mut run = arms.reference_and_candidate(&initial)?;
let (cancelled_after_copy, reset_exact) = arms.cancel_and_recover(&initial, &mut run)?;
let guards = transport_probe(context)?;
if run.words != 3 * (2 * K * N + N) {
return Err(Error::IdentityMismatch);
}
Ok(DirectDownReport {
differences: run.differences,
words: run.words,
cancelled_after_copy,
reset_exact,
guards,
allocated_unchanged: run.allocated == context.allocated_bytes(),
})
}
}
@@ -0,0 +1,179 @@
//! Moved out of the parent module by STRA-338: impl Probe, fn transport_probe, fn output_differences, fn same_outputs.
#[allow(unused_imports)]
use super::*;
impl<'ctx> Probe<'_, 'ctx> {
pub(super) fn run(&mut self) -> Result<bool> {
self.fill_sentinels()?;
self.split_and_pack_old()?;
self.copy_direct()?;
self.require_old_equals_direct()?;
let before = self.download_direct()?;
self.refuse_invalid_preflight()?;
self.require_direct_unchanged(before)?;
self.refuse_alien_packet_scope()?;
self.refuse_nonfinite_source()?;
Ok(true)
}
/// Both whole packets are sentinel initialized, so every untouched slot
/// is compared too. Original scalar copies establish the reference.
pub(super) fn fill_sentinels(&mut self) -> Result<()> {
let mut sentinel = Vec::new();
sentinel.try_reserve_exact(K * N).map_err(|_| Error::InputAllocation)?;
sentinel.resize(K * N, 17.0);
for _ in 0..3 {
self.old_parts.push(self.scope.upload(&sentinel)?);
self.direct_parts.push(self.scope.upload(&sentinel)?);
}
Ok(())
}
pub(super) fn split_and_pack_old(&mut self) -> Result<()> {
for (c, slot) in SLOTS.iter().enumerate() {
let mut split = self.scope.allocate(N * 4)?;
let op = self
.context
.copy_routed_down_column(self.source.buffer()?, 3, c, split.buffer_mut()?)
.map_err(driver_error)
.and_then(|()| {
self.context
.pack_moe_down_f32(split.buffer()?, self.old_parts[c].buffer_mut()?, *slot as u32)
.map_err(driver_error)
});
let close = split.close();
op?;
close?;
}
Ok(())
}
pub(super) fn copy_direct(&mut self) -> Result<()> {
let mut copies = Vec::new();
copies.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
for (c, part) in self.direct_parts.iter_mut().enumerate() {
copies.push((c as u32, part.buffer_mut()?, SLOTS[c] as u32));
}
self.context.copy_routed_down_columns_to_slots(self.source.buffer()?, 3, &mut copies).map_err(driver_error)
}
pub(super) fn require_old_equals_direct(&self) -> Result<()> {
for (old, new) in self.old_parts.iter().zip(&self.direct_parts) {
let a = download_f32(old.buffer()?, K * N)?;
let b = download_f32(new.buffer()?, K * N)?;
if a.iter().zip(b.iter()).any(|(a, b)| a.to_bits() != b.to_bits()) {
return Err(Error::IdentityMismatch);
}
}
Ok(())
}
pub(super) fn download_direct(&self) -> Result<Vec<Box<[f32]>>> {
let mut before = Vec::new();
before.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
for part in &self.direct_parts {
before.push(download_f32(part.buffer()?, K * N)?);
}
Ok(before)
}
/// All-copy preflight: last slot/column invalid cannot mutate earlier
/// valid destinations. Exact full-size genuine buffers, not fake aliases.
pub(super) fn refuse_invalid_preflight(&mut self) -> Result<()> {
for bad_column in [false, true] {
let mut copies = Vec::new();
copies.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
for (c, part) in self.direct_parts.iter_mut().enumerate() {
let (column, slot) = preflight_copy(bad_column, c);
copies.push((column, part.buffer_mut()?, slot));
}
let refused = self.context.copy_routed_down_columns_to_slots(self.source.buffer()?, 3, &mut copies);
if !matches!(refused, Err(DriverError::InvalidProjectionShape)) {
return Err(Error::IdentityMismatch);
}
}
Ok(())
}
pub(super) fn require_direct_unchanged(&self, before: Vec<Box<[f32]>>) -> Result<()> {
for (part, before) in self.direct_parts.iter().zip(before) {
let after = download_f32(part.buffer()?, K * N)?;
if before.iter().zip(after.iter()).any(|(a, b)| a.to_bits() != b.to_bits()) {
return Err(Error::IdentityMismatch);
}
}
Ok(())
}
pub(super) fn refuse_alien_packet_scope(&self) -> Result<()> {
let alien_scope = DownScope::new(self.context, Rc::new(Cell::new(false)));
let mut packet = super::super::super::moe_down::ResidentPackedDown::new(self.scope)?;
let scope_guard = refuse_alien_scope(self.scope, &alien_scope, &mut packet);
let close = packet.close();
scope_guard?;
close?;
Ok(())
}
/// Full finite source refusal precedes any copy callback, including an
/// interior NaN; the old producer is evaluated first on exact bytes.
pub(super) fn refuse_nonfinite_source(&self) -> Result<()> {
let selections = SLOTS.map(DownSelection::Routed);
for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
let bytes = corrupted_bytes(self.payload, invalid)?;
let old = self.scope.project_columns(
&selections,
|out, _| out.copy_from(&bytes).map_err(driver_error),
&mut || false,
);
let called = Cell::new(false);
let new = self.scope.project_columns_direct(
&selections,
|out, _| out.copy_from(&bytes).map_err(driver_error),
|_, _| {
called.set(true);
Ok(())
},
&mut || false,
);
if !matches!(old, Err(Error::NonFinite)) || !matches!(new, Err(Error::NonFinite)) || called.get() {
return Err(Error::IdentityMismatch);
}
}
Ok(())
}
pub(super) fn close_all(self) -> Result<()> {
let mut cleanup = Ok(());
for owner in self.old_parts.into_iter().chain(self.direct_parts).chain(std::iter::once(self.source)) {
let next = owner.close();
if cleanup.is_ok() {
cleanup = next;
}
}
cleanup
}
}
// Independent byte-only old split+pack FIRST, then direct whole-group copy.
// Genuine selected rows supply scope/origin. The finite payload deliberately
// contains both signed zeros and different columns/slots; no model state is faked.
pub(super) fn transport_probe(context: &Context<'_>) -> Result<bool> {
let failed = Rc::new(Cell::new(false));
let scope = DownScope::new(context, failed.clone());
let payload = probe_payload()?;
let source = scope.upload(&payload)?;
let mut probe =
Probe { context, scope: &scope, payload: &payload, source, old_parts: Vec::new(), direct_parts: Vec::new() };
probe.old_parts.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
probe.direct_parts.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
let operation = probe.run();
scope.record(&operation);
let cleanup = probe.close_all();
operation.and_then(|value| cleanup.map(|()| value))
}
pub(super) fn output_differences(reference: &[ExpertReady], candidate: &[ExpertReady]) -> Result<usize> {
let mut differences = 0;
for (a, b) in reference.iter().zip(candidate) {
validate_values(a.output(), N)?;
validate_values(b.output(), N)?;
differences += a.output().iter().zip(b.output()).filter(|(a, b)| a.to_bits() != b.to_bits()).count();
}
Ok(differences)
}
pub(super) fn same_outputs(reference: &[ExpertReady], recovery: &[ExpertReady]) -> bool {
reference
.iter()
.zip(recovery)
.all(|(a, b)| a.output().iter().zip(b.output()).all(|(a, b)| a.to_bits() == b.to_bits()))
}
@@ -0,0 +1,167 @@
//! Moved out of the parent module by STRA-338.
#[allow(unused_imports)]
use super::*;
pub(in super::super) fn policy(actual: bool) -> bool {
actual && !OLD.get()
}
pub(in super::super) fn copy_completed() {
COPIED.set(true);
}
pub(in super::super) fn observe_packet(packet: &DeviceBuffer<'_>) -> Result<()> {
PACKETS.with(|slot| {
let mut slot = slot.borrow_mut();
let Some(packets) = slot.as_mut() else {
return Ok(());
};
if packets.len() >= 3 {
return Err(Error::InvalidDimension);
}
packets.push(download_f32(packet, K * N)?);
Ok(())
})
}
impl Observation {
pub(super) fn begin(old: bool) -> Result<Self> {
let mut rows = Vec::new();
rows.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
PACKETS.with(|slot| -> Result<()> {
if slot.borrow().is_some() {
return Err(Error::IdentityMismatch);
}
*slot.borrow_mut() = Some(rows);
Ok(())
})?;
OLD.set(old);
COPIED.set(false);
CANCELLED_ON_COPY.set(false);
Ok(Self)
}
pub(super) fn take(&self) -> Result<Vec<Box<[f32]>>> {
PACKETS.with(|slot| slot.borrow_mut().take().ok_or(Error::IdentityMismatch))
}
}
impl Drop for Observation {
fn drop(&mut self) {
OLD.set(false);
COPIED.set(false);
PACKETS.with(|slot| {
slot.borrow_mut().take();
});
}
}
impl DirectDownReport {
/// The loaded caller retains this report, then closes every cache/session
/// and Context before asserting. This is not an all48/target commit proof.
pub(crate) fn assert_after_teardown(self) {
assert_eq!(self.differences, 0);
assert!(self.cancelled_after_copy && self.allocated_unchanged && self.reset_exact && self.guards);
eprintln!(
"direct native Down PASS exact_words={} original_copy_first=true real_rows=true \
packet_mapping=true signedzero=true \
postcopy_cancel=true cleanup_checked=true full_model=false speed_claim=false",
self.words
);
}
}
pub(super) fn compare(a: &[Box<[f32]>], b: &[Box<[f32]>]) -> Result<(usize, usize)> {
if a.len() != b.len() {
return Err(Error::IdentityMismatch);
}
let mut differences = 0;
let mut words = 0;
for (a, b) in a.iter().zip(b) {
if a.len() != b.len() {
return Err(Error::InvalidDimension);
}
validate_values(a, a.len())?;
validate_values(b, b.len())?;
differences += a.iter().zip(b.iter()).filter(|(a, b)| a.to_bits() != b.to_bits()).count();
words += a.len();
}
Ok((differences, words))
}
pub(super) fn arm_consume_inputs<'ctx>(
binding: &ModelBinding,
kar: &mut KarPleCache<'_>,
chunk: &mut QwenChunkTxn<'_, 'ctx>,
) -> Result<()> {
for index in 0..3 {
let (token, position) = chunk.row_ids(index)?;
chunk.input(index, |txn| InputStage::consume_kar(binding, kar, token, position, txn))?;
}
Ok(())
}
pub(super) fn arm_attention_reads<'ctx>(
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
layer: LayerId,
chunk: &mut QwenChunkTxn<'_, 'ctx>,
) -> Result<Vec<ChunkAttentionRow>> {
let mut reads = Vec::new();
reads.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
for index in 0..3 {
reads.push(chunk.read_attention_column(index, layer, |txn| {
let read = GrStage::apply(binding, layer, txn, Some(dense))?;
GrStage::detach_attention(binding, read, txn)
})?);
}
Ok(reads)
}
pub(super) fn arm_ffn_rows<'ctx>(
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
layer: LayerId,
chunk: &mut QwenChunkTxn<'_, 'ctx>,
reads: &[ChunkAttentionRow],
) -> Result<Vec<ChunkFfnRow>> {
let mut rows = Vec::new();
rows.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
for (index, read) in reads.iter().enumerate() {
rows.push(chunk.prepare_attention_ffn(index, layer, read, |txn, residual| {
arm_prepare_row(binding, dense, layer, txn, residual)
})?);
}
Ok(rows)
}
pub(super) fn arm_prepare_row<'ctx>(
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
layer: LayerId,
txn: &mut QwenStepTxn<'_, 'ctx>,
residual: &DetachedGrRead,
) -> Result<PreparedMoeRow> {
let prior = txn.gdn_prior(layer)?;
let mut attention = GdnStage::step(binding, layer, residual.ready(), &prior, txn, Some(dense))?;
attention.validate_origin(&binding.identity())?;
let pending = attention.take_pending()?;
txn.stage_gdn(&prior, pending)?;
let retained = GrStage::inject_retained(binding, residual, attention.output(), attention.identity(), txn, dense)?;
let ffn = GrStage::read_retained_ffn(binding, retained, txn, dense)?;
let route = MoeRouteStage::route_from_ffn(binding, layer, ffn.ready(), txn, Some(dense))?;
MoeExpertStage::prepare_chunk_row(binding, layer, ffn, route, txn)
}
pub(super) fn arm_tokens() -> Result<(LayerId, [TokenId; 3])> {
let layer = LayerId::new(0, Dimension::new(48)?)?;
let vocab = Dimension::new(248320)?;
Ok((layer, [TokenId::new(0, vocab)?, TokenId::new(1, vocab)?, TokenId::new(0, vocab)?]))
}
pub(super) fn arm_chunk_rows<'ctx>(
binding: &ModelBinding,
kar: &mut KarPleCache<'_>,
dense: &DenseWeightCache<'ctx>,
layer: LayerId,
chunk: &mut QwenChunkTxn<'_, 'ctx>,
) -> Result<Vec<ChunkFfnRow>> {
arm_consume_inputs(binding, kar, chunk)?;
let reads = arm_attention_reads(binding, dense, layer, chunk)?;
arm_ffn_rows(binding, dense, layer, chunk, &reads)
}
pub(super) fn cancel_probe(cancel_after_copy: bool) -> bool {
let cancel = cancel_after_copy && COPIED.get();
if cancel {
CANCELLED_ON_COPY.set(true);
}
cancel
}
@@ -4,10 +4,6 @@
use super::*;
use crate::qwen_forward::mtp_decode::MtpVerifiedWindow;
fn position_at(position: u64) -> Position {
Position::new(position, crate::qwen_forward::contract::position_dimension()).unwrap()
}
/// The window preparation of one flow against the candidate cache. The prepared window borrows the target session
/// alone, so the call is spelled out where the session and the report must stay separately borrowable.
macro_rules! prepare_window {
@@ -27,17 +23,6 @@ macro_rules! prepare_window {
)
};
}
/// Ten complete snapshots + transaction peak and draft copies stay below
/// this explicit host cap; production transaction remains exactly512MiB.
fn admit_binding(binding: &ModelBinding) {
assert!(ROW_CAP.checked_mul(10).unwrap() + TRANSACTION_CAP + 4 * 1024 * 1024 <= SNAPSHOT_CAP);
assert_eq!(binding.layer_count(), 48);
let disposition = binding.ordered_layers().iter().fold((0, 0), |(g, q), d| match d.kind() {
crate::model_binding::qwen4exp_input::BoundLayerKind::Gdn => (g + 1, q),
crate::model_binding::qwen4exp_input::BoundLayerKind::Qsa => (g, q + 1),
});
assert_eq!(disposition, (36, 12));
}
/// The loan of the loaded stages every scalar step, window preparation and decoder window runs against.
struct Shared<'a, 'o, 'p, 'k, 'd> {
@@ -47,45 +32,6 @@ struct Shared<'a, 'o, 'p, 'k, 'd> {
kar: &'a mut KarPleCache<'k>,
}
impl Shared<'_, '_, '_, '_, '_> {
fn step<'ctx>(
&mut self,
target: &mut QwenSession<'ctx>,
native: &mut MoeWeightCache<'ctx>,
(token, position): (TokenId, u64),
) -> Result<TargetStepProduct> {
QwenForward::step_for_mtp_cached(
self.binding,
token,
position_at(position),
target,
self.output,
Some(&mut *self.kar),
Some(native),
Some(self.dense),
)
}
fn window<'ctx>(
&mut self,
decoder: &mut MtpDecoder,
(target, cache): (&mut QwenSession<'ctx>, &mut MoeWeightCache<'ctx>),
(source, spec): (TargetStepProduct, MtpWindowSpec),
cancelled: impl FnMut() -> bool,
) -> std::result::Result<MtpVerifiedWindow, MtpWindowError> {
decoder.window(
self.binding,
source,
target,
self.output,
Some(&mut *self.kar),
cache,
self.dense,
spec,
cancelled,
)
}
}
/// The tokens and draft snapshots every later phase compares against.
struct Refs {
seed: TokenId,
@@ -126,332 +72,15 @@ struct Flow<'a, 'ctx, 'o, 'p, 'k, 'd> {
zero: TokenId,
}
impl<'a, 'ctx, 'o, 'p, 'k, 'd> Flow<'a, 'ctx, 'o, 'p, 'k, 'd> {
fn open(
shared: Shared<'a, 'o, 'p, 'k, 'd>,
context: &'ctx Rc<leleka_cuda_driver::Context<'ctx>>,
cache_slot: &'a mut Option<MoeWeightCache<'ctx>>,
) -> Self {
let binding = shared.binding;
let zero = TokenId::new(0, Dimension::new(VOCAB as u64).unwrap()).unwrap();
let target = QwenSession::for_binding_on_shared_device(binding, Rc::clone(context));
let fresh = target.test_reset_replay_snapshot(binding).unwrap();
let mut report = Report::default();
report.predicates.try_reserve_exact(40).unwrap();
shared.output.test_reset_replay_record(true).unwrap();
Self { shared, context, cache_slot, target, report, fresh, zero }
}
}
impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> {
fn step(&mut self, token: TokenId, position: u64) -> Result<TargetStepProduct> {
let native = self.cache_slot.as_mut().unwrap();
self.shared.step(&mut self.target, native, (token, position))
}
fn warm(&mut self, draft: &mut MtpDecoder, source: &TargetStepProduct, token: TokenId) -> Result<()> {
let native = self.cache_slot.as_mut().unwrap();
draft.warm_retained(self.shared.binding, &mut self.target, source, token, native)
}
fn observe(&self, source: &TargetStepProduct) -> Expected {
observe(self.shared.binding, &self.target, self.shared.output, source)
}
fn matches_state(&self, expected: &ResetReplaySnapshot) -> bool {
self.target.test_reset_replay_snapshot(self.shared.binding).unwrap().numeric_eq(expected)
}
fn reset_to_fresh(&mut self) {
QwenForward::reset(&mut self.target).unwrap();
let ok = self.matches_state(&self.fresh);
self.report.check(ok);
}
/// The scalar seed and the first two rows with the draft warmed over them.
fn reference_prefix(&mut self) -> Prefix {
let (zero, binding) = (self.zero, self.shared.binding);
let source = self.step(zero, 0).expect("scalar seed refused");
let seed_expected = self.observe(&source);
let seed = source.predicted(&self.target).unwrap();
let mut draft = MtpDecoder::new(binding).unwrap();
self.warm(&mut draft, &source, seed).expect("actual seed draft warm refused");
let row0 = self.step(seed, 1).expect("scalar row0 refused");
let expected0 = self.observe(&row0);
let next = row0.predicted(&self.target).unwrap();
self.warm(&mut draft, &row0, next).expect("actual row0 draft warm refused");
let row1 = self.step(next, 2).expect("scalar row1 refused");
let expected1 = self.observe(&row1);
let expected_draft = draft.test_chunk_snapshot();
let true_next = row1.predicted(&self.target).unwrap();
let wrong = different_token(&[seed, next, true_next]);
let tokens = (seed, next, wrong, true_next);
Prefix { source, row0, row1, draft, seed_expected, expected0, expected1, expected_draft, tokens }
}
/// The continuation and the rejected-tail reference after a restore; every scalar product is then released.
fn reference_tail(&mut self, prefix: Prefix) -> Chain {
let Prefix { source, row0, row1, mut draft, seed_expected, expected0, expected1, expected_draft, tokens } =
prefix;
let (seed, next, wrong, true_next) = tokens;
let prior = self.target.checkpoint().unwrap();
self.warm(&mut draft, &row1, true_next).expect("continuation draft warm refused");
let continued = self.step(true_next, 3).expect("scalar continuation refused");
let expected_continued = self.observe(&continued);
let continued_draft = draft.test_chunk_snapshot();
self.target.restore_checkpoint(&prior).unwrap();
let tail = self.step(wrong, 3).expect("scalar rejected-tail reference refused");
let expected_tail = self.observe(&tail);
drop(tail);
drop(continued);
drop(row1);
drop(row0);
drop(source);
drop(prior);
drop(draft);
self.shared.output.test_reset_replay_record(false).unwrap();
let refs = Refs { seed, next, wrong, true_next, expected_draft, continued_draft };
Chain { refs, seed_expected, expected0, expected1, expected_tail, expected_continued }
}
/// Closes the legacy cache, opens the explicit candidate cache and proves its seed identical to the scalar seed.
fn candidate_seed(&mut self, seed_expected: Expected) -> TargetStepProduct {
let old = self.cache_slot.take().unwrap();
self.report.check(old.close().is_ok());
*self.cache_slot = Some(
MoeWeightCache::new_native_integer_iq3_mmq(self.shared.binding, self.context.as_ref())
.expect("explicit candidate cache refused"),
);
self.reset_to_fresh();
self.shared.output.test_reset_replay_record(true).unwrap();
let zero = self.zero;
let source = self.step(zero, 0).expect("candidate seed refused");
let seed_actual = self.observe(&source);
self.report.check(
seed_actual.logits == seed_expected.logits
&& seed_actual.residual == seed_expected.residual
&& seed_actual.state.numeric_eq(&seed_expected.state),
);
self.report.words += VOCAB + 10240;
drop(seed_actual);
drop(seed_expected);
self.shared.output.test_reset_replay_record(false).unwrap();
source
}
/// Refuse T4 and actual authoritative EOS before producer mutation.
fn refuse_windows(
&mut self,
source: &TargetStepProduct,
refs: &Refs,
decoder: &MtpDecoder,
(target_before, draft_before): (&ResetReplaySnapshot, &mtp::MtpChunkNumericSnapshot),
) {
let candidate = self.cache_slot.as_mut().unwrap();
let four = [refs.seed, refs.next, refs.wrong, self.zero];
let too_many = prepare_window!(self, candidate, (source, &four, None));
self.report.check(matches!(too_many, Err(Error::InputAllocation)));
drop(too_many);
self.report.guards += 1;
let at_eos = prepare_window!(self, candidate, (source, &[refs.seed], Some(refs.seed)));
self.report.check(matches!(at_eos, Err(Error::IdentityMismatch)));
drop(at_eos);
self.report.guards += 1;
let unchanged = self.matches_state(target_before) && decoder.test_chunk_eq(draft_before);
self.report.check(unchanged);
}
/// ONE actual completed T3 transaction. Cancellation is at the private
/// draft stage boundary after one real causal warm, before joint publish.
fn cancelled_publish(
&mut self,
source: &TargetStepProduct,
(refs, expected0, expected1): (&Refs, &Expected, &Expected),
expected_tail: Expected,
decoder: &mut MtpDecoder,
(target_before, draft_before): (&ResetReplaySnapshot, &mtp::MtpChunkNumericSnapshot),
) {
let collection = Collection::begin(3).unwrap();
let candidate = self.cache_slot.as_mut().unwrap();
let proposals = [refs.seed, refs.next, refs.wrong];
let pending = prepare_window!(self, candidate, (source, &proposals, None)).expect("real T3 target refused");
self.report.check(pending.accepted_rows() == 2);
let rows = collection.finish().unwrap();
self.report.check(row_matches(&rows[0], expected0));
self.report.check(row_matches(&rows[1], expected1));
self.report.check(row_matches(&rows[2], &expected_tail));
self.report.words += 3 * (VOCAB + 10240);
drop(rows);
drop(expected_tail);
let mut phase_calls = 0;
let cancelled = pending.publish_joint(self.shared.binding, &mut decoder.draft, candidate, || {
phase_calls += 1;
phase_calls == 3
});
self.report.check(matches!(cancelled, Err(Error::Unsupported(Stage::Executor))) && phase_calls == 3);
self.report.guards += 1;
let unchanged = self.matches_state(target_before) && decoder.test_chunk_eq(draft_before);
self.report.check(unchanged);
}
/// The first decoder warmed over the seed, the T4/EOS refusals, the cancelled T3 transaction and the restore.
fn first_window(
&mut self,
source: &TargetStepProduct,
(refs, expected0, expected1): (&Refs, &Expected, &Expected),
expected_tail: Expected,
) -> (MtpDecoder, ResetReplaySnapshot, mtp::MtpChunkNumericSnapshot) {
let binding = self.shared.binding;
let mut decoder = MtpDecoder::new(binding).unwrap();
self.warm(&mut decoder, source, refs.seed).unwrap();
let target_before = self.target.test_reset_replay_snapshot(binding).unwrap();
let draft_before = decoder.test_chunk_snapshot();
let target_prior = self.target.checkpoint().unwrap();
let draft_prior = decoder.draft.checkpoint().unwrap();
self.refuse_windows(source, refs, &decoder, (&target_before, &draft_before));
let before = (&target_before, &draft_before);
self.cancelled_publish(source, (refs, expected0, expected1), expected_tail, &mut decoder, before);
self.report.check(self.target.restore_checkpoint(&target_prior).is_ok());
self.report.check(decoder.draft.restore(&draft_prior).is_ok());
drop(target_prior);
drop(draft_prior);
(decoder, target_before, draft_before)
}
/// The old product was invalidated by real rollback. Reset and recompute
/// the seed; never relabel that product as a fresh origin. Existing caller publishes a real prefix, then its
/// existing cancellation check fires from this exact event. No guessed global callback ordinal.
fn automatic_cancel(
&mut self,
source: TargetStepProduct,
expected0: &Expected,
target_before: &ResetReplaySnapshot,
) {
drop(source);
self.reset_to_fresh();
let zero = self.zero;
let source = self.step(zero, 0).expect("recovery seed refused");
let mut decoder = MtpDecoder::new(self.shared.binding).unwrap();
let automatic_draft_before = decoder.test_chunk_snapshot();
let event = PostcommitCancellation::arm().unwrap();
let collection = Collection::begin(1).unwrap();
let spec = MtpWindowSpec::new(4, 1, None).unwrap();
let candidate = self.cache_slot.as_mut().unwrap();
let cancelled =
self.shared.window(&mut decoder, (&mut self.target, candidate), (source, spec), || event.cancelled());
self.report.check(event.cancelled() && matches!(cancelled, Err(MtpWindowError::Cancelled)));
drop(cancelled);
let actual = collection.finish().unwrap();
self.report.check(row_matches(&actual[0], expected0));
self.report.words += VOCAB + 10240;
self.report.guards += 1;
let unchanged = self.matches_state(target_before) && decoder.test_chunk_eq(&automatic_draft_before);
self.report.check(unchanged);
drop((actual, event, automatic_draft_before, decoder));
}
/// Automatic full restore invalidates the consumed source. Recover via
/// genuine reset/forward, never a clone/remint of that stale capability; then verify a SomeEOS prefix.
fn eos_prefix(
&mut self,
refs: &Refs,
(expected0, expected1): (Expected, Expected),
(target_before, draft_before): (ResetReplaySnapshot, mtp::MtpChunkNumericSnapshot),
) -> (MtpDecoder, TargetStepProduct) {
let binding = self.shared.binding;
self.reset_to_fresh();
let zero = self.zero;
let source = self.step(zero, 0).expect("automatic caller cancellation recovery refused");
let mut decoder = MtpDecoder::new(binding).unwrap();
self.warm(&mut decoder, &source, refs.seed).unwrap();
let candidate = self.cache_slot.as_mut().unwrap();
let proposals = [refs.seed, refs.next, refs.wrong];
let pending = prepare_window!(self, candidate, (&source, &proposals, Some(refs.wrong)))
.expect("SomeEOS accepted prefix refused");
self.report.check(pending.accepted_rows() == 2);
let latest =
pending.publish_joint(binding, &mut decoder.draft, candidate, || false).expect("real jointprefix refused");
let state_ok = self.matches_state(&expected1.state);
self.report.check(state_ok);
self.report.check(decoder.test_chunk_eq(&refs.expected_draft));
let (_, _, streams, _) = latest.mtp_source(binding, &self.target).unwrap();
self.report.check(
latest.predicted(&self.target).unwrap() == expected1.head
&& streams.iter().map(|v| v.to_bits()).eq(expected1.residual.iter().copied()),
);
drop((expected0, expected1, target_before, draft_before));
(decoder, latest)
}
/// Actual wired caller: remaining=1 must not consume more than one true
/// target token; this also exercises speculative rewind + head-free catchup.
fn max_one(
&mut self,
refs: &Refs,
expected_continued: Expected,
decoder: &mut MtpDecoder,
latest: TargetStepProduct,
) -> TargetStepProduct {
let collection = Collection::begin(1).unwrap();
let spec = MtpWindowSpec::new(4, 1, None).unwrap();
let candidate = self.cache_slot.as_mut().unwrap();
let window = self
.shared
.window(decoder, (&mut self.target, candidate), (latest, spec), || false)
.expect("actual max1 decoder caller refused");
let observed = collection.finish().unwrap();
self.report.check(row_matches(&observed[0], &expected_continued));
let (tokens, latest, stopped) = window.into_parts();
self.report.check(tokens == vec![refs.true_next] && !stopped);
let state_ok = self.matches_state(&expected_continued.state);
self.report.check(state_ok);
self.report.check(decoder.test_chunk_eq(&refs.continued_draft));
self.report.words += VOCAB + 10240;
drop(observed);
drop(expected_continued);
latest
}
/// A window with nothing to advance (`remaining` zero or an authoritative EOS) does no draft work and returns
/// the same genuine committed source.
fn idle_window(
&mut self,
decoder: &mut MtpDecoder,
latest: TargetStepProduct,
(remaining, eos, stopped_expected): (usize, Option<TokenId>, bool),
) -> TargetStepProduct {
let spec = MtpWindowSpec::new(4, remaining, eos).unwrap();
let candidate = self.cache_slot.as_mut().unwrap();
let window = self.shared.window(decoder, (&mut self.target, candidate), (latest, spec), || false).unwrap();
self.report.check(window.tokens().is_empty() && window.draft_steps() == 0);
let (_, latest, stopped) = window.into_parts();
self.report.check(stopped == stopped_expected);
self.report.guards += 1;
latest
}
/// Zero remaining and authoritative EOS require no advance, draft work or publication.
fn no_advance(&mut self, mut decoder: MtpDecoder, latest: TargetStepProduct) {
let before = self.target.test_reset_replay_snapshot(self.shared.binding).unwrap();
let draft_before = decoder.test_chunk_snapshot();
let latest = self.idle_window(&mut decoder, latest, (0, None, false));
let eos = latest.predicted(&self.target).unwrap();
let latest = self.idle_window(&mut decoder, latest, (4, Some(eos), true));
let unchanged = self.matches_state(&before) && decoder.test_chunk_eq(&draft_before);
self.report.check(unchanged);
drop(latest);
drop(decoder);
drop(before);
drop(draft_before);
self.reset_to_fresh();
}
}
pub(super) fn check_loaded<'ctx>(
binding: &ModelBinding,
context: &'ctx Rc<leleka_cuda_driver::Context<'ctx>>,
output: &OutputStage<'_, '_>,
kar: &mut KarPleCache<'_>,
cache_slot: &mut Option<MoeWeightCache<'ctx>>,
dense: &DenseWeightCache<'_>,
) -> Report {
admit_binding(binding);
let mut flow = Flow::open(Shared { binding, output, dense, kar }, context, cache_slot);
let prefix = flow.reference_prefix();
let Chain { refs, seed_expected, expected0, expected1, expected_tail, expected_continued } =
flow.reference_tail(prefix);
let source = flow.candidate_seed(seed_expected);
let (first_decoder, target_before, draft_before) =
flow.first_window(&source, (&refs, &expected0, &expected1), expected_tail);
flow.automatic_cancel(source, &expected0, &target_before);
let (mut decoder, latest) = flow.eos_prefix(&refs, (expected0, expected1), (target_before, draft_before));
let latest = flow.max_one(&refs, expected_continued, &mut decoder, latest);
flow.no_advance(decoder, latest);
drop(first_decoder);
flow.report
}
#[path = "check_loaded_fn/position_at_fn.rs"]
mod position_at_fn;
#[allow(unused_imports)]
use position_at_fn::admit_binding;
#[allow(unused_imports)]
use position_at_fn::position_at;
#[path = "check_loaded_fn/impl_flow.rs"]
mod impl_flow;
#[path = "check_loaded_fn/impl_flow_2.rs"]
mod impl_flow_2;
#[allow(unused_imports)]
pub(super) use impl_flow_2::check_loaded;
@@ -0,0 +1,201 @@
//! Moved out of the parent module by STRA-338: impl Flow.
#[allow(unused_imports)]
use super::*;
impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> {
pub(super) fn step(&mut self, token: TokenId, position: u64) -> Result<TargetStepProduct> {
let native = self.cache_slot.as_mut().unwrap();
self.shared.step(&mut self.target, native, (token, position))
}
pub(super) fn warm(&mut self, draft: &mut MtpDecoder, source: &TargetStepProduct, token: TokenId) -> Result<()> {
let native = self.cache_slot.as_mut().unwrap();
draft.warm_retained(self.shared.binding, &mut self.target, source, token, native)
}
pub(super) fn observe(&self, source: &TargetStepProduct) -> Expected {
observe(self.shared.binding, &self.target, self.shared.output, source)
}
pub(super) fn matches_state(&self, expected: &ResetReplaySnapshot) -> bool {
self.target.test_reset_replay_snapshot(self.shared.binding).unwrap().numeric_eq(expected)
}
pub(super) fn reset_to_fresh(&mut self) {
QwenForward::reset(&mut self.target).unwrap();
let ok = self.matches_state(&self.fresh);
self.report.check(ok);
}
/// The scalar seed and the first two rows with the draft warmed over them.
pub(super) fn reference_prefix(&mut self) -> Prefix {
let (zero, binding) = (self.zero, self.shared.binding);
let source = self.step(zero, 0).expect("scalar seed refused");
let seed_expected = self.observe(&source);
let seed = source.predicted(&self.target).unwrap();
let mut draft = MtpDecoder::new(binding).unwrap();
self.warm(&mut draft, &source, seed).expect("actual seed draft warm refused");
let row0 = self.step(seed, 1).expect("scalar row0 refused");
let expected0 = self.observe(&row0);
let next = row0.predicted(&self.target).unwrap();
self.warm(&mut draft, &row0, next).expect("actual row0 draft warm refused");
let row1 = self.step(next, 2).expect("scalar row1 refused");
let expected1 = self.observe(&row1);
let expected_draft = draft.test_chunk_snapshot();
let true_next = row1.predicted(&self.target).unwrap();
let wrong = different_token(&[seed, next, true_next]);
let tokens = (seed, next, wrong, true_next);
Prefix { source, row0, row1, draft, seed_expected, expected0, expected1, expected_draft, tokens }
}
/// The continuation and the rejected-tail reference after a restore; every scalar product is then released.
pub(super) fn reference_tail(&mut self, prefix: Prefix) -> Chain {
let Prefix { source, row0, row1, mut draft, seed_expected, expected0, expected1, expected_draft, tokens } =
prefix;
let (seed, next, wrong, true_next) = tokens;
let prior = self.target.checkpoint().unwrap();
self.warm(&mut draft, &row1, true_next).expect("continuation draft warm refused");
let continued = self.step(true_next, 3).expect("scalar continuation refused");
let expected_continued = self.observe(&continued);
let continued_draft = draft.test_chunk_snapshot();
self.target.restore_checkpoint(&prior).unwrap();
let tail = self.step(wrong, 3).expect("scalar rejected-tail reference refused");
let expected_tail = self.observe(&tail);
drop(tail);
drop(continued);
drop(row1);
drop(row0);
drop(source);
drop(prior);
drop(draft);
self.shared.output.test_reset_replay_record(false).unwrap();
let refs = Refs { seed, next, wrong, true_next, expected_draft, continued_draft };
Chain { refs, seed_expected, expected0, expected1, expected_tail, expected_continued }
}
/// Closes the legacy cache, opens the explicit candidate cache and proves its seed identical to the scalar seed.
pub(super) fn candidate_seed(&mut self, seed_expected: Expected) -> TargetStepProduct {
let old = self.cache_slot.take().unwrap();
self.report.check(old.close().is_ok());
*self.cache_slot = Some(
MoeWeightCache::new_native_integer_iq3_mmq(self.shared.binding, self.context.as_ref())
.expect("explicit candidate cache refused"),
);
self.reset_to_fresh();
self.shared.output.test_reset_replay_record(true).unwrap();
let zero = self.zero;
let source = self.step(zero, 0).expect("candidate seed refused");
let seed_actual = self.observe(&source);
self.report.check(
seed_actual.logits == seed_expected.logits
&& seed_actual.residual == seed_expected.residual
&& seed_actual.state.numeric_eq(&seed_expected.state),
);
self.report.words += VOCAB + 10240;
drop(seed_actual);
drop(seed_expected);
self.shared.output.test_reset_replay_record(false).unwrap();
source
}
/// Refuse T4 and actual authoritative EOS before producer mutation.
pub(super) fn refuse_windows(
&mut self,
source: &TargetStepProduct,
refs: &Refs,
decoder: &MtpDecoder,
(target_before, draft_before): (&ResetReplaySnapshot, &mtp::MtpChunkNumericSnapshot),
) {
let candidate = self.cache_slot.as_mut().unwrap();
let four = [refs.seed, refs.next, refs.wrong, self.zero];
let too_many = prepare_window!(self, candidate, (source, &four, None));
self.report.check(matches!(too_many, Err(Error::InputAllocation)));
drop(too_many);
self.report.guards += 1;
let at_eos = prepare_window!(self, candidate, (source, &[refs.seed], Some(refs.seed)));
self.report.check(matches!(at_eos, Err(Error::IdentityMismatch)));
drop(at_eos);
self.report.guards += 1;
let unchanged = self.matches_state(target_before) && decoder.test_chunk_eq(draft_before);
self.report.check(unchanged);
}
/// ONE actual completed T3 transaction. Cancellation is at the private
/// draft stage boundary after one real causal warm, before joint publish.
pub(super) fn cancelled_publish(
&mut self,
source: &TargetStepProduct,
(refs, expected0, expected1): (&Refs, &Expected, &Expected),
expected_tail: Expected,
decoder: &mut MtpDecoder,
(target_before, draft_before): (&ResetReplaySnapshot, &mtp::MtpChunkNumericSnapshot),
) {
let collection = Collection::begin(3).unwrap();
let candidate = self.cache_slot.as_mut().unwrap();
let proposals = [refs.seed, refs.next, refs.wrong];
let pending = prepare_window!(self, candidate, (source, &proposals, None)).expect("real T3 target refused");
self.report.check(pending.accepted_rows() == 2);
let rows = collection.finish().unwrap();
self.report.check(row_matches(&rows[0], expected0));
self.report.check(row_matches(&rows[1], expected1));
self.report.check(row_matches(&rows[2], &expected_tail));
self.report.words += 3 * (VOCAB + 10240);
drop(rows);
drop(expected_tail);
let mut phase_calls = 0;
let cancelled = pending.publish_joint(self.shared.binding, &mut decoder.draft, candidate, || {
phase_calls += 1;
phase_calls == 3
});
self.report.check(matches!(cancelled, Err(Error::Unsupported(Stage::Executor))) && phase_calls == 3);
self.report.guards += 1;
let unchanged = self.matches_state(target_before) && decoder.test_chunk_eq(draft_before);
self.report.check(unchanged);
}
/// The first decoder warmed over the seed, the T4/EOS refusals, the cancelled T3 transaction and the restore.
pub(super) fn first_window(
&mut self,
source: &TargetStepProduct,
(refs, expected0, expected1): (&Refs, &Expected, &Expected),
expected_tail: Expected,
) -> (MtpDecoder, ResetReplaySnapshot, mtp::MtpChunkNumericSnapshot) {
let binding = self.shared.binding;
let mut decoder = MtpDecoder::new(binding).unwrap();
self.warm(&mut decoder, source, refs.seed).unwrap();
let target_before = self.target.test_reset_replay_snapshot(binding).unwrap();
let draft_before = decoder.test_chunk_snapshot();
let target_prior = self.target.checkpoint().unwrap();
let draft_prior = decoder.draft.checkpoint().unwrap();
self.refuse_windows(source, refs, &decoder, (&target_before, &draft_before));
let before = (&target_before, &draft_before);
self.cancelled_publish(source, (refs, expected0, expected1), expected_tail, &mut decoder, before);
self.report.check(self.target.restore_checkpoint(&target_prior).is_ok());
self.report.check(decoder.draft.restore(&draft_prior).is_ok());
drop(target_prior);
drop(draft_prior);
(decoder, target_before, draft_before)
}
/// The old product was invalidated by real rollback. Reset and recompute
/// the seed; never relabel that product as a fresh origin. Existing caller publishes a real prefix, then its
/// existing cancellation check fires from this exact event. No guessed global callback ordinal.
pub(super) fn automatic_cancel(
&mut self,
source: TargetStepProduct,
expected0: &Expected,
target_before: &ResetReplaySnapshot,
) {
drop(source);
self.reset_to_fresh();
let zero = self.zero;
let source = self.step(zero, 0).expect("recovery seed refused");
let mut decoder = MtpDecoder::new(self.shared.binding).unwrap();
let automatic_draft_before = decoder.test_chunk_snapshot();
let event = PostcommitCancellation::arm().unwrap();
let collection = Collection::begin(1).unwrap();
let spec = MtpWindowSpec::new(4, 1, None).unwrap();
let candidate = self.cache_slot.as_mut().unwrap();
let cancelled =
self.shared.window(&mut decoder, (&mut self.target, candidate), (source, spec), || event.cancelled());
self.report.check(event.cancelled() && matches!(cancelled, Err(MtpWindowError::Cancelled)));
drop(cancelled);
let actual = collection.finish().unwrap();
self.report.check(row_matches(&actual[0], expected0));
self.report.words += VOCAB + 10240;
self.report.guards += 1;
let unchanged = self.matches_state(target_before) && decoder.test_chunk_eq(&automatic_draft_before);
self.report.check(unchanged);
drop((actual, event, automatic_draft_before, decoder));
}
}
@@ -0,0 +1,123 @@
//! Moved out of the parent module by STRA-338: impl Flow (2), fn check_loaded.
#[allow(unused_imports)]
use super::*;
impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> {
/// Automatic full restore invalidates the consumed source. Recover via
/// genuine reset/forward, never a clone/remint of that stale capability; then verify a SomeEOS prefix.
pub(super) fn eos_prefix(
&mut self,
refs: &Refs,
(expected0, expected1): (Expected, Expected),
(target_before, draft_before): (ResetReplaySnapshot, mtp::MtpChunkNumericSnapshot),
) -> (MtpDecoder, TargetStepProduct) {
let binding = self.shared.binding;
self.reset_to_fresh();
let zero = self.zero;
let source = self.step(zero, 0).expect("automatic caller cancellation recovery refused");
let mut decoder = MtpDecoder::new(binding).unwrap();
self.warm(&mut decoder, &source, refs.seed).unwrap();
let candidate = self.cache_slot.as_mut().unwrap();
let proposals = [refs.seed, refs.next, refs.wrong];
let pending = prepare_window!(self, candidate, (&source, &proposals, Some(refs.wrong)))
.expect("SomeEOS accepted prefix refused");
self.report.check(pending.accepted_rows() == 2);
let latest =
pending.publish_joint(binding, &mut decoder.draft, candidate, || false).expect("real jointprefix refused");
let state_ok = self.matches_state(&expected1.state);
self.report.check(state_ok);
self.report.check(decoder.test_chunk_eq(&refs.expected_draft));
let (_, _, streams, _) = latest.mtp_source(binding, &self.target).unwrap();
self.report.check(
latest.predicted(&self.target).unwrap() == expected1.head
&& streams.iter().map(|v| v.to_bits()).eq(expected1.residual.iter().copied()),
);
drop((expected0, expected1, target_before, draft_before));
(decoder, latest)
}
/// Actual wired caller: remaining=1 must not consume more than one true
/// target token; this also exercises speculative rewind + head-free catchup.
pub(super) fn max_one(
&mut self,
refs: &Refs,
expected_continued: Expected,
decoder: &mut MtpDecoder,
latest: TargetStepProduct,
) -> TargetStepProduct {
let collection = Collection::begin(1).unwrap();
let spec = MtpWindowSpec::new(4, 1, None).unwrap();
let candidate = self.cache_slot.as_mut().unwrap();
let window = self
.shared
.window(decoder, (&mut self.target, candidate), (latest, spec), || false)
.expect("actual max1 decoder caller refused");
let observed = collection.finish().unwrap();
self.report.check(row_matches(&observed[0], &expected_continued));
let (tokens, latest, stopped) = window.into_parts();
self.report.check(tokens == vec![refs.true_next] && !stopped);
let state_ok = self.matches_state(&expected_continued.state);
self.report.check(state_ok);
self.report.check(decoder.test_chunk_eq(&refs.continued_draft));
self.report.words += VOCAB + 10240;
drop(observed);
drop(expected_continued);
latest
}
/// A window with nothing to advance (`remaining` zero or an authoritative EOS) does no draft work and returns
/// the same genuine committed source.
pub(super) fn idle_window(
&mut self,
decoder: &mut MtpDecoder,
latest: TargetStepProduct,
(remaining, eos, stopped_expected): (usize, Option<TokenId>, bool),
) -> TargetStepProduct {
let spec = MtpWindowSpec::new(4, remaining, eos).unwrap();
let candidate = self.cache_slot.as_mut().unwrap();
let window = self.shared.window(decoder, (&mut self.target, candidate), (latest, spec), || false).unwrap();
self.report.check(window.tokens().is_empty() && window.draft_steps() == 0);
let (_, latest, stopped) = window.into_parts();
self.report.check(stopped == stopped_expected);
self.report.guards += 1;
latest
}
/// Zero remaining and authoritative EOS require no advance, draft work or publication.
pub(super) fn no_advance(&mut self, mut decoder: MtpDecoder, latest: TargetStepProduct) {
let before = self.target.test_reset_replay_snapshot(self.shared.binding).unwrap();
let draft_before = decoder.test_chunk_snapshot();
let latest = self.idle_window(&mut decoder, latest, (0, None, false));
let eos = latest.predicted(&self.target).unwrap();
let latest = self.idle_window(&mut decoder, latest, (4, Some(eos), true));
let unchanged = self.matches_state(&before) && decoder.test_chunk_eq(&draft_before);
self.report.check(unchanged);
drop(latest);
drop(decoder);
drop(before);
drop(draft_before);
self.reset_to_fresh();
}
}
pub(in super::super) fn check_loaded<'ctx>(
binding: &ModelBinding,
context: &'ctx Rc<leleka_cuda_driver::Context<'ctx>>,
output: &OutputStage<'_, '_>,
kar: &mut KarPleCache<'_>,
cache_slot: &mut Option<MoeWeightCache<'ctx>>,
dense: &DenseWeightCache<'_>,
) -> Report {
admit_binding(binding);
let mut flow = Flow::open(Shared { binding, output, dense, kar }, context, cache_slot);
let prefix = flow.reference_prefix();
let Chain { refs, seed_expected, expected0, expected1, expected_tail, expected_continued } =
flow.reference_tail(prefix);
let source = flow.candidate_seed(seed_expected);
let (first_decoder, target_before, draft_before) =
flow.first_window(&source, (&refs, &expected0, &expected1), expected_tail);
flow.automatic_cancel(source, &expected0, &target_before);
let (mut decoder, latest) = flow.eos_prefix(&refs, (expected0, expected1), (target_before, draft_before));
let latest = flow.max_one(&refs, expected_continued, &mut decoder, latest);
flow.no_advance(decoder, latest);
drop(first_decoder);
flow.report
}
@@ -0,0 +1,75 @@
//! Moved out of the parent module by STRA-338: fn position_at, fn admit_binding, impl Shared, impl Flow.
#[allow(unused_imports)]
use super::*;
pub(super) fn position_at(position: u64) -> Position {
Position::new(position, crate::qwen_forward::contract::position_dimension()).unwrap()
}
/// Ten complete snapshots + transaction peak and draft copies stay below
/// this explicit host cap; production transaction remains exactly512MiB.
pub(super) fn admit_binding(binding: &ModelBinding) {
assert!(ROW_CAP.checked_mul(10).unwrap() + TRANSACTION_CAP + 4 * 1024 * 1024 <= SNAPSHOT_CAP);
assert_eq!(binding.layer_count(), 48);
let disposition = binding.ordered_layers().iter().fold((0, 0), |(g, q), d| match d.kind() {
crate::model_binding::qwen4exp_input::BoundLayerKind::Gdn => (g + 1, q),
crate::model_binding::qwen4exp_input::BoundLayerKind::Qsa => (g, q + 1),
});
assert_eq!(disposition, (36, 12));
}
impl Shared<'_, '_, '_, '_, '_> {
pub(super) fn step<'ctx>(
&mut self,
target: &mut QwenSession<'ctx>,
native: &mut MoeWeightCache<'ctx>,
(token, position): (TokenId, u64),
) -> Result<TargetStepProduct> {
QwenForward::step_for_mtp_cached(
self.binding,
token,
position_at(position),
target,
self.output,
Some(&mut *self.kar),
Some(native),
Some(self.dense),
)
}
pub(super) fn window<'ctx>(
&mut self,
decoder: &mut MtpDecoder,
(target, cache): (&mut QwenSession<'ctx>, &mut MoeWeightCache<'ctx>),
(source, spec): (TargetStepProduct, MtpWindowSpec),
cancelled: impl FnMut() -> bool,
) -> std::result::Result<MtpVerifiedWindow, MtpWindowError> {
decoder.window(
self.binding,
source,
target,
self.output,
Some(&mut *self.kar),
cache,
self.dense,
spec,
cancelled,
)
}
}
impl<'a, 'ctx, 'o, 'p, 'k, 'd> Flow<'a, 'ctx, 'o, 'p, 'k, 'd> {
pub(super) fn open(
shared: Shared<'a, 'o, 'p, 'k, 'd>,
context: &'ctx Rc<leleka_cuda_driver::Context<'ctx>>,
cache_slot: &'a mut Option<MoeWeightCache<'ctx>>,
) -> Self {
let binding = shared.binding;
let zero = TokenId::new(0, Dimension::new(VOCAB as u64).unwrap()).unwrap();
let target = QwenSession::for_binding_on_shared_device(binding, Rc::clone(context));
let fresh = target.test_reset_replay_snapshot(binding).unwrap();
let mut report = Report::default();
report.predicates.try_reserve_exact(40).unwrap();
shared.output.test_reset_replay_record(true).unwrap();
Self { shared, context, cache_slot, target, report, fresh, zero }
}
}
@@ -25,85 +25,7 @@ pub(super) struct MtpBlock {
frame: MtpFrame,
output: Box<[f32]>,
}
impl MtpBlock {
pub(super) fn frame(&self) -> &MtpFrame {
&self.frame
}
pub(super) fn output(&self) -> &[f32] {
&self.output
}
}
pub(super) struct MtpExpertStage;
impl MtpExpertStage {
pub(super) fn run(
binding: &ModelBinding,
input: &MtpMlpReady,
session: &QwenSession<'_>,
cache: &MoeWeightCache<'_>,
failed: Rc<Cell<bool>>,
) -> Result<MtpBlock> {
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
let _owner_wall_scope =
crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Moe);
let result = Self::run_checked(binding, input, session, cache, &failed);
if matches!(result, Err(Error::CudaExecution)) {
failed.set(true);
}
if failed.get() {
cache.note_transport_failure();
}
result
}
fn run_checked(
binding: &ModelBinding,
input: &MtpMlpReady,
session: &QwenSession<'_>,
cache: &MoeWeightCache<'_>,
failed: &Rc<Cell<bool>>,
) -> Result<MtpBlock> {
if failed.get() {
return Err(Error::CudaExecution);
}
admit_input(binding, input, session)?;
let context = session.mtp_context()?;
preflight(context, DEVICE_PEAK)?;
let (ids, weights) = route_mixed(context, binding, input, cache)?;
let output = compose_bound(context, binding, input, session, ids, weights, cache, Rc::clone(failed))?;
validate_values(&output, N)?;
input.frame().validate(binding, session)?;
Ok(MtpBlock { frame: input.frame().clone(), output })
}
}
fn admit_input(binding: &ModelBinding, input: &MtpMlpReady, session: &QwenSession<'_>) -> Result<()> {
input.frame().validate(binding, session)?;
validate_values(input.mixed(), N)?;
validate_values(input.streams(), 4 * N)?;
validate_values(input.inject(), 4)?;
let pack = binding.mtp_weights().map_err(binding_error)?;
// Admit all fixed dense roles before the first model row or CUDA call.
for (role, expected) in [
(MtpRole::Router, (MtpKind::Bf16, 512, N)),
(MtpRole::SharedGate, (MtpKind::Q8_0, FF, N)),
(MtpRole::SharedUp, (MtpKind::Q8_0, FF, N)),
(MtpRole::SharedDown, (MtpKind::Q8_0, N, FF)),
(MtpRole::SharedScalar, (MtpKind::Bf16, 1, N)),
] {
if pack.dense_shape(binding, role).map_err(binding_error)? != expected {
return Err(Error::InvalidDimension);
}
}
Ok(())
}
fn route_mixed(
context: &Context<'_>,
binding: &ModelBinding,
input: &MtpMlpReady,
cache: &MoeWeightCache<'_>,
) -> Result<([u32; K], [f32; K])> {
let logits = project(context, binding, MtpRole::Router, input.mixed(), cache)?;
validate_values(&logits, 512)?;
route(context, &logits)
}
/// The model-side handles one MTP expert invocation runs against.
#[derive(Clone, Copy)]
struct Bound<'a, 'c, 's, 'k> {
@@ -117,306 +39,50 @@ struct BoundWeights<'a, 'k> {
bank: &'a DeviceBuffer<'k>,
shared: [&'a DeviceBuffer<'k>; 4],
}
impl<'a, 'k> Bound<'a, '_, '_, 'k> {
fn admit(&self, frame: &MtpFrame) -> Result<()> {
frame.validate(self.binding, self.session)?;
if !std::ptr::eq(self.context, self.session.mtp_context()?) {
return Err(Error::IdentityMismatch);
}
Ok(())
}
fn matrix(&self, role: MtpRole, expected: (MtpKind, usize, usize)) -> Result<&'a DeviceBuffer<'k>> {
let (kind, rows, columns, weights) = self.cache.mtp_matrix(self.binding, self.context, role)?;
if (kind, rows, columns) != expected {
return Err(Error::InvalidDimension);
}
Ok(weights)
}
fn weights(&self) -> Result<BoundWeights<'a, 'k>> {
self.cache.validate(self.binding, self.context)?;
let bank = self.cache.mtp_bank(self.binding, self.context)?;
let shared = [
self.matrix(MtpRole::SharedGate, (MtpKind::Q8_0, FF, N))?,
self.matrix(MtpRole::SharedUp, (MtpKind::Q8_0, FF, N))?,
self.matrix(MtpRole::SharedDown, (MtpKind::Q8_0, N, FF))?,
self.matrix(MtpRole::SharedScalar, (MtpKind::Bf16, 1, N))?,
];
Ok(BoundWeights { bank, shared })
}
fn compose(
&self,
frame: &MtpFrame,
input: &MtpMlpReady,
weights: BoundWeights<'_, '_>,
picks: ([u32; K], [f32; K]),
failed: Rc<Cell<bool>>,
) -> Result<Box<[f32]>> {
let (ids, route_weights) = picks;
let BoundWeights { bank, shared } = weights;
if self.cache.requires_iq3_mmq_admission() {
let (binding, context, session) = (self.binding, self.context, self.session);
let mixed = input.mixed();
let cache = self.cache;
cache.compose_fixed_mtp_experts(
binding,
context,
frame,
session,
bank,
shared,
mixed,
ids,
route_weights,
failed,
)
} else {
mtp_expert_transport::compose(self.context, bank, shared, input.mixed(), ids, route_weights, failed)
}
}
}
#[allow(clippy::too_many_arguments)]
fn compose_bound(
context: &Context<'_>,
binding: &ModelBinding,
input: &MtpMlpReady,
session: &QwenSession<'_>,
ids: [u32; K],
weights: [f32; K],
cache: &MoeWeightCache<'_>,
failed: Rc<Cell<bool>>,
) -> Result<Box<[f32]>> {
// Only this current frame-bound invocation can supply the numeric helper.
// No device product escapes to a later draft position or rollback epoch.
let call = Bound { context, binding, session, cache };
let frame = input.frame().clone();
call.admit(&frame)?;
let values = call.compose(&frame, input, call.weights()?, (ids, weights), failed)?;
frame.validate(binding, session)?;
if !frame.same(input.frame()) {
return Err(Error::IdentityMismatch);
}
Ok(values)
}
fn moe_driver_error(error: leleka_cuda_driver::Error) -> Error {
match driver_error(error) {
Error::Unsupported(_) => Error::Unsupported(Stage::MoeExpert),
other => other,
}
}
fn validate_route(ids: [i32; K], weights: &[f32]) -> Result<[u32; K]> {
validate_values(weights, K)?;
let mut result = [0u32; K];
for (slot, id) in ids.into_iter().enumerate() {
let id = u32::try_from(id).map_err(|_| Error::InvalidExpert)?;
if id >= 512 || result[..slot].contains(&id) {
return Err(Error::InvalidExpert);
}
if !(0.0..=1.0).contains(&weights[slot]) {
return Err(Error::NonFinite);
}
result[slot] = id;
}
Ok(result)
}
fn route(context: &Context<'_>, logits: &[f32]) -> Result<([u32; K], [f32; K])> {
let x = upload(context, logits)?;
let mut ids = context.allocate(K * 4).map_err(moe_driver_error)?;
let mut weights = allocate(context, K)?;
let result: Result<([u32; K], [f32; K])> = (|| {
context.qwen_route_top10(&x, &mut ids, &mut weights).map_err(moe_driver_error)?;
let raw = download_bytes(&ids, K * 4)?;
let ids = std::array::from_fn(|i| i32::from_le_bytes(raw[i * 4..(i + 1) * 4].try_into().expect("fixed IDs")));
let weights: [f32; K] = download(&weights, K)?.as_ref().try_into().map_err(|_| Error::InvalidDimension)?;
Ok((validate_route(ids, &weights)?, weights))
})();
let cleanup = release([x, ids, weights]);
let value = result?;
cleanup?;
Ok(value)
}
fn compose(
context: &Context<'_>,
binding: &ModelBinding,
mixed: &[f32],
x: &DeviceBuffer<'_>,
ids: [u32; K],
weights: [f32; K],
cache: &MoeWeightCache<'_>,
) -> Result<Box<[f32]>> {
let parts = routed_parts(context, binding, x, ids, cache)?;
let shared = shared(context, binding, mixed, x, cache)?;
combine_uploaded(context, &parts, &weights, &shared)
}
fn routed_parts(
context: &Context<'_>,
binding: &ModelBinding,
x: &DeviceBuffer<'_>,
ids: [u32; K],
cache: &MoeWeightCache<'_>,
) -> Result<Vec<f32>> {
let mut q = context.allocate(2720).map_err(moe_driver_error)?;
let mut scales = allocate(context, 80)?;
context.mtp_quantize_scaled_2560(x, &mut q, &mut scales).map_err(moe_driver_error)?;
download(&scales, 80)?; // Must inspect FP32 scales before any dot.
let mut parts = reserve(K * N)?;
for expert in ids {
let values = routed(context, binding, expert, &q, &scales, cache)?;
validate_values(&values, N)?;
parts.extend_from_slice(&values);
}
release([q, scales])?;
Ok(parts)
}
fn combine_uploaded(context: &Context<'_>, parts: &[f32], weights: &[f32], shared: &[f32]) -> Result<Box<[f32]>> {
let parts = upload(context, parts)?;
let weights = upload(context, weights)?;
let shared = upload(context, shared)?;
let mut out = allocate(context, N)?;
let result: Result<Box<[f32]>> = (|| {
// Original default DOUBLE ordered combine; parts remain router-slot order.
context.moe_combine_f64(&parts, &weights, &shared, &mut out).map_err(moe_driver_error)?;
download(&out, N)
})();
let cleanup = release([parts, weights, shared, out]);
let result = result?;
cleanup?;
Ok(result)
}
fn routed(
context: &Context<'_>,
binding: &ModelBinding,
expert: u32,
q: &DeviceBuffer<'_>,
scales: &DeviceBuffer<'_>,
cache: &MoeWeightCache<'_>,
) -> Result<Box<[f32]>> {
let bank = cache.mtp_bank(binding, context)?;
let hidden = routed_hidden(context, bank, expert, q, scales)?;
routed_down(context, bank, expert, hidden)
}
fn routed_hidden<'a>(
context: &'a Context<'_>,
bank: &DeviceBuffer<'_>,
expert: u32,
q: &DeviceBuffer<'_>,
scales: &DeviceBuffer<'_>,
) -> Result<DeviceBuffer<'a>> {
let mut gateup = allocate(context, 2 * FF)?;
let result = context
.mtp_s2_gate_up_full(bank, expert, q, scales, &mut gateup)
.map_err(moe_driver_error)
.and_then(|()| download(&gateup, 2 * FF));
let _finite = result?;
let mut hidden = allocate(context, FF)?;
context.mtp_swiglu_640(&gateup, &mut hidden).map_err(moe_driver_error)?;
download(&hidden, FF)?;
gateup.release().map_err(moe_driver_error)?;
Ok(hidden)
}
fn routed_down(
context: &Context<'_>,
bank: &DeviceBuffer<'_>,
expert: u32,
hidden: DeviceBuffer<'_>,
) -> Result<Box<[f32]>> {
let mut q = context.allocate(680).map_err(moe_driver_error)?;
let mut scales = allocate(context, 20)?;
context.mtp_quantize_scaled_640(&hidden, &mut q, &mut scales).map_err(moe_driver_error)?;
download(&scales, 20)?;
hidden.release().map_err(moe_driver_error)?;
let mut out = allocate(context, N)?;
let result = context
.mtp_s2_down_full(bank, expert, &q, &scales, &mut out)
.map_err(moe_driver_error)
.and_then(|()| download(&out, N));
let cleanup = release([q, scales, out]);
let values = result?;
cleanup?;
Ok(values)
}
fn shared(
context: &Context<'_>,
binding: &ModelBinding,
mixed: &[f32],
x: &DeviceBuffer<'_>,
cache: &MoeWeightCache<'_>,
) -> Result<Box<[f32]>> {
let hidden_values = shared_hidden(context, binding, mixed, cache)?;
let shared = project(context, binding, MtpRole::SharedDown, &hidden_values, cache)?;
let (_, _, _, scalar_weights) = cache.mtp_matrix(binding, context, MtpRole::SharedScalar)?;
let shared = upload(context, &shared)?;
let mut scalar = allocate(context, 1)?;
context.moe_shared_scalar_f32_bf16(x, scalar_weights, &mut scalar).map_err(moe_driver_error)?;
let scalar_value = download(&scalar, 1)?;
if !(0.0..=1.0).contains(&scalar_value[0]) {
return Err(Error::NonFinite);
}
scale_shared(context, shared, scalar)
}
fn shared_hidden(
context: &Context<'_>,
binding: &ModelBinding,
mixed: &[f32],
cache: &MoeWeightCache<'_>,
) -> Result<Box<[f32]>> {
let gate = project(context, binding, MtpRole::SharedGate, mixed, cache)?;
let up = project(context, binding, MtpRole::SharedUp, mixed, cache)?;
let gate = upload(context, &gate)?;
let up = upload(context, &up)?;
let mut hidden = allocate(context, FF)?;
context.moe_swiglu_f32(&gate, &up, &mut hidden).map_err(moe_driver_error)?;
let hidden_values = download(&hidden, FF)?;
release([gate, up, hidden])?;
Ok(hidden_values)
}
fn scale_shared(context: &Context<'_>, shared: DeviceBuffer<'_>, scalar: DeviceBuffer<'_>) -> Result<Box<[f32]>> {
let mut scaled = allocate(context, N)?;
let result: Result<Box<[f32]>> = (|| {
context.moe_shared_scale_f32(&shared, &scalar, &mut scaled).map_err(moe_driver_error)?;
download(&scaled, N)
})();
let cleanup = release([shared, scalar, scaled]);
let result = result?;
cleanup?;
Ok(result)
}
/// Lossless byte layout only: Q2_0[half2,codes16] into separate source planes.
struct S2Tile {
codes: Vec<u8>,
scales: Vec<u8>,
}
fn gate_up_tile(gate: &[u8], up: &[u8]) -> Result<S2Tile> {
if gate.len() != 16 * 40 * 18 || up.len() != gate.len() {
return Err(Error::InvalidDimension);
}
let mut tile = S2Tile { codes: reserve(32 * 40 * 16)?, scales: reserve(32 * 40 * 2)? };
for row in 0..16 {
for source in [gate, up] {
append_row(&mut tile, &source[row * 40 * 18..(row + 1) * 40 * 18])?;
}
}
Ok(tile)
}
fn down_tile(rows: &[u8]) -> Result<S2Tile> {
if rows.len() != 64 * 10 * 18 {
return Err(Error::InvalidDimension);
}
let mut tile = S2Tile { codes: reserve(64 * 10 * 16)?, scales: reserve(64 * 10 * 2)? };
for row in rows.as_chunks::<{ 10 * 18 }>().0 {
append_row(&mut tile, row)?;
}
Ok(tile)
}
fn append_row(tile: &mut S2Tile, row: &[u8]) -> Result<()> {
for block in row.as_chunks::<18>().0 {
let half = u16::from_le_bytes([block[0], block[1]]);
if half & 0x7c00 == 0x7c00 {
return Err(Error::NonFinite);
}
tile.scales.extend_from_slice(&block[..2]);
tile.codes.extend_from_slice(&block[2..]);
}
Ok(())
}
#[cfg(test)]
mod tests;
mod impl_mtpblock;
#[allow(unused_imports)]
use impl_mtpblock::admit_input;
#[allow(unused_imports)]
use impl_mtpblock::compose_bound;
#[allow(unused_imports)]
use impl_mtpblock::moe_driver_error;
#[allow(unused_imports)]
use impl_mtpblock::route_mixed;
#[allow(unused_imports)]
use impl_mtpblock::validate_route;
mod route_fn;
#[allow(unused_imports)]
use route_fn::combine_uploaded;
#[allow(unused_imports)]
use route_fn::compose;
#[allow(unused_imports)]
use route_fn::down_tile;
#[allow(unused_imports)]
use route_fn::gate_up_tile;
#[allow(unused_imports)]
use route_fn::route;
#[allow(unused_imports)]
use route_fn::routed;
#[allow(unused_imports)]
use route_fn::routed_down;
#[allow(unused_imports)]
use route_fn::routed_hidden;
#[allow(unused_imports)]
use route_fn::routed_parts;
#[allow(unused_imports)]
use route_fn::scale_shared;
#[allow(unused_imports)]
use route_fn::shared;
#[allow(unused_imports)]
use route_fn::shared_hidden;
mod append_row_fn;
#[allow(unused_imports)]
use append_row_fn::append_row;
@@ -0,0 +1,16 @@
//! Moved out of the parent module by STRA-338: fn append_row.
#[allow(unused_imports)]
use super::*;
pub(super) fn append_row(tile: &mut S2Tile, row: &[u8]) -> Result<()> {
for block in row.as_chunks::<18>().0 {
let half = u16::from_le_bytes([block[0], block[1]]);
if half & 0x7c00 == 0x7c00 {
return Err(Error::NonFinite);
}
tile.scales.extend_from_slice(&block[..2]);
tile.codes.extend_from_slice(&block[2..]);
}
Ok(())
}
@@ -0,0 +1,184 @@
//! Moved out of the parent module by STRA-338.
#[allow(unused_imports)]
use super::*;
impl MtpBlock {
pub(in super::super) fn frame(&self) -> &MtpFrame {
&self.frame
}
pub(in super::super) fn output(&self) -> &[f32] {
&self.output
}
}
impl MtpExpertStage {
pub(in super::super) fn run(
binding: &ModelBinding,
input: &MtpMlpReady,
session: &QwenSession<'_>,
cache: &MoeWeightCache<'_>,
failed: Rc<Cell<bool>>,
) -> Result<MtpBlock> {
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
let _owner_wall_scope =
crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Moe);
let result = Self::run_checked(binding, input, session, cache, &failed);
if matches!(result, Err(Error::CudaExecution)) {
failed.set(true);
}
if failed.get() {
cache.note_transport_failure();
}
result
}
pub(super) fn run_checked(
binding: &ModelBinding,
input: &MtpMlpReady,
session: &QwenSession<'_>,
cache: &MoeWeightCache<'_>,
failed: &Rc<Cell<bool>>,
) -> Result<MtpBlock> {
if failed.get() {
return Err(Error::CudaExecution);
}
admit_input(binding, input, session)?;
let context = session.mtp_context()?;
preflight(context, DEVICE_PEAK)?;
let (ids, weights) = route_mixed(context, binding, input, cache)?;
let output = compose_bound(context, binding, input, session, ids, weights, cache, Rc::clone(failed))?;
validate_values(&output, N)?;
input.frame().validate(binding, session)?;
Ok(MtpBlock { frame: input.frame().clone(), output })
}
}
pub(super) fn admit_input(binding: &ModelBinding, input: &MtpMlpReady, session: &QwenSession<'_>) -> Result<()> {
input.frame().validate(binding, session)?;
validate_values(input.mixed(), N)?;
validate_values(input.streams(), 4 * N)?;
validate_values(input.inject(), 4)?;
let pack = binding.mtp_weights().map_err(binding_error)?;
// Admit all fixed dense roles before the first model row or CUDA call.
for (role, expected) in [
(MtpRole::Router, (MtpKind::Bf16, 512, N)),
(MtpRole::SharedGate, (MtpKind::Q8_0, FF, N)),
(MtpRole::SharedUp, (MtpKind::Q8_0, FF, N)),
(MtpRole::SharedDown, (MtpKind::Q8_0, N, FF)),
(MtpRole::SharedScalar, (MtpKind::Bf16, 1, N)),
] {
if pack.dense_shape(binding, role).map_err(binding_error)? != expected {
return Err(Error::InvalidDimension);
}
}
Ok(())
}
pub(super) fn route_mixed(
context: &Context<'_>,
binding: &ModelBinding,
input: &MtpMlpReady,
cache: &MoeWeightCache<'_>,
) -> Result<([u32; K], [f32; K])> {
let logits = project(context, binding, MtpRole::Router, input.mixed(), cache)?;
validate_values(&logits, 512)?;
route(context, &logits)
}
impl<'a, 'k> Bound<'a, '_, '_, 'k> {
pub(super) fn admit(&self, frame: &MtpFrame) -> Result<()> {
frame.validate(self.binding, self.session)?;
if !std::ptr::eq(self.context, self.session.mtp_context()?) {
return Err(Error::IdentityMismatch);
}
Ok(())
}
pub(super) fn matrix(&self, role: MtpRole, expected: (MtpKind, usize, usize)) -> Result<&'a DeviceBuffer<'k>> {
let (kind, rows, columns, weights) = self.cache.mtp_matrix(self.binding, self.context, role)?;
if (kind, rows, columns) != expected {
return Err(Error::InvalidDimension);
}
Ok(weights)
}
pub(super) fn weights(&self) -> Result<BoundWeights<'a, 'k>> {
self.cache.validate(self.binding, self.context)?;
let bank = self.cache.mtp_bank(self.binding, self.context)?;
let shared = [
self.matrix(MtpRole::SharedGate, (MtpKind::Q8_0, FF, N))?,
self.matrix(MtpRole::SharedUp, (MtpKind::Q8_0, FF, N))?,
self.matrix(MtpRole::SharedDown, (MtpKind::Q8_0, N, FF))?,
self.matrix(MtpRole::SharedScalar, (MtpKind::Bf16, 1, N))?,
];
Ok(BoundWeights { bank, shared })
}
pub(super) fn compose(
&self,
frame: &MtpFrame,
input: &MtpMlpReady,
weights: BoundWeights<'_, '_>,
picks: ([u32; K], [f32; K]),
failed: Rc<Cell<bool>>,
) -> Result<Box<[f32]>> {
let (ids, route_weights) = picks;
let BoundWeights { bank, shared } = weights;
if self.cache.requires_iq3_mmq_admission() {
let (binding, context, session) = (self.binding, self.context, self.session);
let mixed = input.mixed();
let cache = self.cache;
cache.compose_fixed_mtp_experts(
binding,
context,
frame,
session,
bank,
shared,
mixed,
ids,
route_weights,
failed,
)
} else {
mtp_expert_transport::compose(self.context, bank, shared, input.mixed(), ids, route_weights, failed)
}
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn compose_bound(
context: &Context<'_>,
binding: &ModelBinding,
input: &MtpMlpReady,
session: &QwenSession<'_>,
ids: [u32; K],
weights: [f32; K],
cache: &MoeWeightCache<'_>,
failed: Rc<Cell<bool>>,
) -> Result<Box<[f32]>> {
// Only this current frame-bound invocation can supply the numeric helper.
// No device product escapes to a later draft position or rollback epoch.
let call = Bound { context, binding, session, cache };
let frame = input.frame().clone();
call.admit(&frame)?;
let values = call.compose(&frame, input, call.weights()?, (ids, weights), failed)?;
frame.validate(binding, session)?;
if !frame.same(input.frame()) {
return Err(Error::IdentityMismatch);
}
Ok(values)
}
pub(super) fn moe_driver_error(error: leleka_cuda_driver::Error) -> Error {
match driver_error(error) {
Error::Unsupported(_) => Error::Unsupported(Stage::MoeExpert),
other => other,
}
}
pub(super) fn validate_route(ids: [i32; K], weights: &[f32]) -> Result<[u32; K]> {
validate_values(weights, K)?;
let mut result = [0u32; K];
for (slot, id) in ids.into_iter().enumerate() {
let id = u32::try_from(id).map_err(|_| Error::InvalidExpert)?;
if id >= 512 || result[..slot].contains(&id) {
return Err(Error::InvalidExpert);
}
if !(0.0..=1.0).contains(&weights[slot]) {
return Err(Error::NonFinite);
}
result[slot] = id;
}
Ok(result)
}
@@ -0,0 +1,198 @@
//! Moved out of the parent module by STRA-338.
#[allow(unused_imports)]
use super::*;
pub(super) fn route(context: &Context<'_>, logits: &[f32]) -> Result<([u32; K], [f32; K])> {
let x = upload(context, logits)?;
let mut ids = context.allocate(K * 4).map_err(moe_driver_error)?;
let mut weights = allocate(context, K)?;
let result: Result<([u32; K], [f32; K])> = (|| {
context.qwen_route_top10(&x, &mut ids, &mut weights).map_err(moe_driver_error)?;
let raw = download_bytes(&ids, K * 4)?;
let ids = std::array::from_fn(|i| i32::from_le_bytes(raw[i * 4..(i + 1) * 4].try_into().expect("fixed IDs")));
let weights: [f32; K] = download(&weights, K)?.as_ref().try_into().map_err(|_| Error::InvalidDimension)?;
Ok((validate_route(ids, &weights)?, weights))
})();
let cleanup = release([x, ids, weights]);
let value = result?;
cleanup?;
Ok(value)
}
pub(super) fn compose(
context: &Context<'_>,
binding: &ModelBinding,
mixed: &[f32],
x: &DeviceBuffer<'_>,
ids: [u32; K],
weights: [f32; K],
cache: &MoeWeightCache<'_>,
) -> Result<Box<[f32]>> {
let parts = routed_parts(context, binding, x, ids, cache)?;
let shared = shared(context, binding, mixed, x, cache)?;
combine_uploaded(context, &parts, &weights, &shared)
}
pub(super) fn routed_parts(
context: &Context<'_>,
binding: &ModelBinding,
x: &DeviceBuffer<'_>,
ids: [u32; K],
cache: &MoeWeightCache<'_>,
) -> Result<Vec<f32>> {
let mut q = context.allocate(2720).map_err(moe_driver_error)?;
let mut scales = allocate(context, 80)?;
context.mtp_quantize_scaled_2560(x, &mut q, &mut scales).map_err(moe_driver_error)?;
download(&scales, 80)?; // Must inspect FP32 scales before any dot.
let mut parts = reserve(K * N)?;
for expert in ids {
let values = routed(context, binding, expert, &q, &scales, cache)?;
validate_values(&values, N)?;
parts.extend_from_slice(&values);
}
release([q, scales])?;
Ok(parts)
}
pub(super) fn combine_uploaded(
context: &Context<'_>,
parts: &[f32],
weights: &[f32],
shared: &[f32],
) -> Result<Box<[f32]>> {
let parts = upload(context, parts)?;
let weights = upload(context, weights)?;
let shared = upload(context, shared)?;
let mut out = allocate(context, N)?;
let result: Result<Box<[f32]>> = (|| {
// Original default DOUBLE ordered combine; parts remain router-slot order.
context.moe_combine_f64(&parts, &weights, &shared, &mut out).map_err(moe_driver_error)?;
download(&out, N)
})();
let cleanup = release([parts, weights, shared, out]);
let result = result?;
cleanup?;
Ok(result)
}
pub(super) fn routed(
context: &Context<'_>,
binding: &ModelBinding,
expert: u32,
q: &DeviceBuffer<'_>,
scales: &DeviceBuffer<'_>,
cache: &MoeWeightCache<'_>,
) -> Result<Box<[f32]>> {
let bank = cache.mtp_bank(binding, context)?;
let hidden = routed_hidden(context, bank, expert, q, scales)?;
routed_down(context, bank, expert, hidden)
}
pub(super) fn routed_hidden<'a>(
context: &'a Context<'_>,
bank: &DeviceBuffer<'_>,
expert: u32,
q: &DeviceBuffer<'_>,
scales: &DeviceBuffer<'_>,
) -> Result<DeviceBuffer<'a>> {
let mut gateup = allocate(context, 2 * FF)?;
let result = context
.mtp_s2_gate_up_full(bank, expert, q, scales, &mut gateup)
.map_err(moe_driver_error)
.and_then(|()| download(&gateup, 2 * FF));
let _finite = result?;
let mut hidden = allocate(context, FF)?;
context.mtp_swiglu_640(&gateup, &mut hidden).map_err(moe_driver_error)?;
download(&hidden, FF)?;
gateup.release().map_err(moe_driver_error)?;
Ok(hidden)
}
pub(super) fn routed_down(
context: &Context<'_>,
bank: &DeviceBuffer<'_>,
expert: u32,
hidden: DeviceBuffer<'_>,
) -> Result<Box<[f32]>> {
let mut q = context.allocate(680).map_err(moe_driver_error)?;
let mut scales = allocate(context, 20)?;
context.mtp_quantize_scaled_640(&hidden, &mut q, &mut scales).map_err(moe_driver_error)?;
download(&scales, 20)?;
hidden.release().map_err(moe_driver_error)?;
let mut out = allocate(context, N)?;
let result = context
.mtp_s2_down_full(bank, expert, &q, &scales, &mut out)
.map_err(moe_driver_error)
.and_then(|()| download(&out, N));
let cleanup = release([q, scales, out]);
let values = result?;
cleanup?;
Ok(values)
}
pub(super) fn shared(
context: &Context<'_>,
binding: &ModelBinding,
mixed: &[f32],
x: &DeviceBuffer<'_>,
cache: &MoeWeightCache<'_>,
) -> Result<Box<[f32]>> {
let hidden_values = shared_hidden(context, binding, mixed, cache)?;
let shared = project(context, binding, MtpRole::SharedDown, &hidden_values, cache)?;
let (_, _, _, scalar_weights) = cache.mtp_matrix(binding, context, MtpRole::SharedScalar)?;
let shared = upload(context, &shared)?;
let mut scalar = allocate(context, 1)?;
context.moe_shared_scalar_f32_bf16(x, scalar_weights, &mut scalar).map_err(moe_driver_error)?;
let scalar_value = download(&scalar, 1)?;
if !(0.0..=1.0).contains(&scalar_value[0]) {
return Err(Error::NonFinite);
}
scale_shared(context, shared, scalar)
}
pub(super) fn shared_hidden(
context: &Context<'_>,
binding: &ModelBinding,
mixed: &[f32],
cache: &MoeWeightCache<'_>,
) -> Result<Box<[f32]>> {
let gate = project(context, binding, MtpRole::SharedGate, mixed, cache)?;
let up = project(context, binding, MtpRole::SharedUp, mixed, cache)?;
let gate = upload(context, &gate)?;
let up = upload(context, &up)?;
let mut hidden = allocate(context, FF)?;
context.moe_swiglu_f32(&gate, &up, &mut hidden).map_err(moe_driver_error)?;
let hidden_values = download(&hidden, FF)?;
release([gate, up, hidden])?;
Ok(hidden_values)
}
pub(super) fn scale_shared(
context: &Context<'_>,
shared: DeviceBuffer<'_>,
scalar: DeviceBuffer<'_>,
) -> Result<Box<[f32]>> {
let mut scaled = allocate(context, N)?;
let result: Result<Box<[f32]>> = (|| {
context.moe_shared_scale_f32(&shared, &scalar, &mut scaled).map_err(moe_driver_error)?;
download(&scaled, N)
})();
let cleanup = release([shared, scalar, scaled]);
let result = result?;
cleanup?;
Ok(result)
}
pub(super) fn gate_up_tile(gate: &[u8], up: &[u8]) -> Result<S2Tile> {
if gate.len() != 16 * 40 * 18 || up.len() != gate.len() {
return Err(Error::InvalidDimension);
}
let mut tile = S2Tile { codes: reserve(32 * 40 * 16)?, scales: reserve(32 * 40 * 2)? };
for row in 0..16 {
for source in [gate, up] {
append_row(&mut tile, &source[row * 40 * 18..(row + 1) * 40 * 18])?;
}
}
Ok(tile)
}
pub(super) fn down_tile(rows: &[u8]) -> Result<S2Tile> {
if rows.len() != 64 * 10 * 18 {
return Err(Error::InvalidDimension);
}
let mut tile = S2Tile { codes: reserve(64 * 10 * 16)?, scales: reserve(64 * 10 * 2)? };
for row in rows.as_chunks::<{ 10 * 18 }>().0 {
append_row(&mut tile, row)?;
}
Ok(tile)
}
@@ -36,23 +36,6 @@ pub(in crate::qwen_forward) struct OriginalMtpRequest {
pub(in crate::qwen_forward) window: i64,
pub(in crate::qwen_forward) kv: OriginalMtpKvStartup,
}
impl OriginalMtpRequest {
/// Original defaults: window 32768 and the INT8 window-ring draft state.
pub(in crate::qwen_forward) fn ring_int8(
max_t: usize,
prompt_capacity: usize,
coupled: bool,
resident_cells: u64,
) -> Self {
Self {
max_t,
prompt_capacity,
coupled,
window: leleka_cuda_driver::MTP_ORIGINAL_WINDOW as i64,
kv: OriginalMtpKvStartup::ring_int8(resident_cells),
}
}
}
/// A load refusal: the fixed runtime error plus, when the driver produced one,
/// the Original `mtp: ...` text the caller may print as `strata generate: ...`.
@@ -61,38 +44,6 @@ pub(in crate::qwen_forward) struct OriginalMtpLoadError {
pub(in crate::qwen_forward) error: Error,
pub(in crate::qwen_forward) message: Option<String>,
}
impl From<Error> for OriginalMtpLoadError {
fn from(error: Error) -> Self {
Self { error, message: None }
}
}
impl From<OriginalMtpLoadFailure> for OriginalMtpLoadError {
fn from(failure: OriginalMtpLoadFailure) -> Self {
let error = match failure.cause() {
Some(leleka_cuda_driver::Error::BudgetExceeded | leleka_cuda_driver::Error::HostAllocation) => {
Error::InputAllocation
}
Some(leleka_cuda_driver::Error::ContextMismatch) => Error::IdentityMismatch,
Some(
leleka_cuda_driver::Error::InvalidQwenShape
| leleka_cuda_driver::Error::InvalidSize
| leleka_cuda_driver::Error::ShapeMismatch { .. },
) => Error::InvalidDimension,
Some(leleka_cuda_driver::Error::UnsupportedQwenOperation) => Error::Unsupported(Stage::Session),
Some(_) => Error::CudaExecution,
None => Error::InputRead,
};
Self { error, message: Some(failure.message().to_owned()) }
}
}
fn plan_error(error: OriginalMtpPlanError) -> OriginalMtpLoadError {
let kind = match error {
OriginalMtpPlanError::ClosedProfile(_) => Error::Unsupported(Stage::Session),
OriginalMtpPlanError::Overflow => Error::Overflow,
_ => Error::InvalidDimension,
};
OriginalMtpLoadError { error: kind, message: Some(error.message()) }
}
/// Model-affine full MTP graphs, their immutable role bank and the loaded
/// actor. The canonical `OriginalDraftSession` receives the one ring created
@@ -126,278 +77,6 @@ pub(in crate::qwen_forward) struct OriginalMtpFullAssembly<'ctx> {
pub(in crate::qwen_forward) owner: OriginalMtpFullOwner<'ctx>,
}
fn capture_of(
binding: &ModelBinding,
context: &Context<'_>,
request: &OriginalMtpRequest,
vocabulary: usize,
) -> OriginalMtpCapture {
OriginalMtpCapture {
// `cudaGetDevice` at load, `g.n_expert`, `ss.k`, `max_cells` of the primary QSA state.
device: context.device_ordinal(),
n_expert: u64::from(binding.expert_count()),
top_k: u64::from(binding.expert_used_count()),
max_cells: u64::from(binding.input_constants().context_length()),
max_t: request.max_t as u64,
window: request.window,
vocabulary: vocabulary as u64,
kv: request.kv,
coupled_requested: request.coupled,
}
}
impl<'ctx> OriginalMtpFullOwner<'ctx> {
/// `bind_bytes` for the startup reserve (generate.cpp `mtp.bind_bytes(...)`):
/// computed from the real native head and the RT directory, before any
/// device bank exists.
pub(in crate::qwen_forward) fn bind_reserve(
binding: &ModelBinding,
context: &Context<'_>,
output: &OriginalNativeOutput<'ctx>,
request: &OriginalMtpRequest,
rt_directory: &Path,
) -> Result<u64> {
let head = output.mtp_head(binding)?;
let capture = capture_of(binding, context, request, head.vocabulary());
let row_bytes = leleka_cuda_driver::native_head_row_bytes(head.kind(), head.columns())
.map_err(|_| Error::InvalidDimension)?;
leleka_cuda_driver::original_mtp_bind_reserve(
&capture,
leleka_cuda_driver::original_mtp_draft_vocab_bytes(rt_directory),
row_bytes as u64,
)
.map_err(|e| plan_error(e).error)
}
/// Literal `MtpDrafter::load` + `bind` from an RT directory. The caller
/// has already loaded the bank into `retained` (`Context::original_mtp_rt_bank`
/// then `RetainedOriginalMtpWeights::from_rt_bank`); `rt_directory` is read
/// again here only for the optional `draft_vocab.bin`, exactly where
/// `bind` reads it.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn assemble_rt(
binding: &ModelBinding,
session: &QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
retained: &RetainedOriginalMtpWeights<'ctx>,
embedding: &OriginalPromptEmbedding<'ctx>,
output: &OriginalNativeOutput<'ctx>,
request: &OriginalMtpRequest,
rt_directory: &Path,
) -> std::result::Result<OriginalMtpFullAssembly<'ctx>, OriginalMtpLoadError> {
Self::assemble_core(binding, session, context, retained, embedding, output, request, Some(rt_directory))
}
/// Same assembly over the digest-pinned pack held by the MoE cache (no RT
/// directory, hence no draft-vocab subset).
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn assemble(
binding: &ModelBinding,
session: &QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
moe: &MoeWeightCache<'ctx>,
embedding: &OriginalPromptEmbedding<'ctx>,
output: &OriginalNativeOutput<'ctx>,
request: &OriginalMtpRequest,
) -> std::result::Result<OriginalMtpFullAssembly<'ctx>, OriginalMtpLoadError> {
// Source keeps all MTP roles immutable for the life of cached graphs.
let retained = moe.retain_original_mtp_weights(binding, context)?;
Self::assemble_core(binding, session, context, &retained, embedding, output, request, None)
}
#[allow(clippy::too_many_arguments)]
fn assemble_core(
binding: &ModelBinding,
session: &QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
retained: &RetainedOriginalMtpWeights<'ctx>,
embedding: &OriginalPromptEmbedding<'ctx>,
output: &OriginalNativeOutput<'ctx>,
request: &OriginalMtpRequest,
rt_directory: Option<&Path>,
) -> std::result::Result<OriginalMtpFullAssembly<'ctx>, OriginalMtpLoadError> {
Self::admit_core(binding, session, context, request)?;
let prepared = Self::prepare_load(binding, context, (retained, output), (request, rt_directory))?;
let weights = Self::retained_weights(binding, context, (retained, embedding), &prepared)?;
// This returns exactly one main arena and mapped records shared by
// scalar prefill and full forward, plus the matching physical KV ring.
let shape = (request.max_t, request.prompt_capacity, prepared.coupled_layout);
let (ring, drafter) = Self::shared_drafter(context, &weights, shape)?;
let (actor, ring) = Self::adopt_actor(context, prepared, (drafter, ring, weights), retained)?;
let draft = match OriginalDraftSession::from_original_ring(binding, session, context, ring) {
Ok(value) => value,
Err(primary) => {
let _ = actor.close();
return Err(primary.into());
}
};
let owner =
Self { binding: binding.identity(), context, actor: Some(actor), max_t: request.max_t, failed: false };
Ok(OriginalMtpFullAssembly { draft, owner })
}
fn admit_core(
binding: &ModelBinding,
session: &QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
request: &OriginalMtpRequest,
) -> std::result::Result<(), OriginalMtpLoadError> {
let (max_t, prompt_capacity) = (request.max_t, request.prompt_capacity);
if binding.layer_count() != 48
|| !(1..=8).contains(&max_t)
|| !(1..=8192).contains(&prompt_capacity)
|| !std::ptr::eq(context, session.mtp_context()?)
{
return Err(Error::IdentityMismatch.into());
}
Ok(())
}
/// The load meter, the native head, the checked plan and the optional draft head, in source order.
fn prepare_load(
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
(retained, output): (&RetainedOriginalMtpWeights<'ctx>, &OriginalNativeOutput<'ctx>),
(request, rt_directory): (&OriginalMtpRequest, Option<&Path>),
) -> std::result::Result<PreparedLoad<'ctx>, OriginalMtpLoadError> {
// Fresh ledger window: the bank's own bytes are added by `finish`.
let meter = OriginalMtpLoadMeter::start(context);
let head = output.mtp_head(binding)?;
// geometry/session/device capture -> checked plan (refuses what the
// retained owners cannot represent instead of planning around it)
let capture = capture_of(binding, context, request, head.vocabulary());
let plan = OriginalMtpLoadPlan::new(capture, retained.dense_file_bytes()).map_err(plan_error)?;
// ---- bind: optional draft head (needs the main head's weights)
let draft_head: Option<OriginalMtpDraftHead<'ctx>> = match rt_directory {
Some(directory) => {
let weights = head.weights();
context.original_mtp_draft_head(directory, &weights, head.kind(), head.columns(), head.vocabulary())?
}
None => None,
};
let subset = draft_head.as_ref().map(|h| h.count() as u64);
let coupled_layout = plan.coupled_layout(subset).map_err(plan_error)?;
Ok(PreparedLoad { meter, head, plan, draft_head, coupled_layout })
}
fn retained_weights(
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
(retained, embedding): (&RetainedOriginalMtpWeights<'ctx>, &OriginalPromptEmbedding<'ctx>),
prepared: &PreparedLoad<'ctx>,
) -> std::result::Result<Rc<OriginalMtpRetainedFullWeights<'ctx>>, OriginalMtpLoadError> {
let head = &prepared.head;
let scalar = retained.scalar_prefill_weights(binding, context, embedding)?;
let prefix = Rc::new(OriginalMtpRetainedPrefix::from_scalar(scalar).map_err(driver_error)?);
let draft_head = prepared.draft_head.as_ref();
Ok(retained.full_forward_weights(binding, context, prefix, head, head.vocabulary(), draft_head)?)
}
fn shared_drafter(
context: &'ctx Context<'ctx>,
weights: &Rc<OriginalMtpRetainedFullWeights<'ctx>>,
(max_t, prompt_capacity, coupled_layout): (usize, usize, bool),
) -> std::result::Result<(MtpOriginalInt8<'ctx>, OriginalMtpDrafter<'ctx>), OriginalMtpLoadError> {
let (ring, scalar, full) = context
.original_mtp_shared_layout_with_ring(Rc::clone(weights), max_t, prompt_capacity, coupled_layout)
.map_err(driver_error)?;
match OriginalMtpDrafter::new(full, scalar) {
Ok(drafter) => Ok((ring, drafter)),
Err(primary) => {
let close = ring.close().map_err(driver_error);
Err(match close {
Err(cleanup) => cleanup,
Ok(()) => driver_error(primary),
}
.into())
}
}
}
/// Meters the finished load and adopts drafter, ring and weights into the actor; the failure paths close what exists.
fn adopt_actor(
context: &'ctx Context<'ctx>,
prepared: PreparedLoad<'ctx>,
(drafter, ring, weights): AdoptParts<'ctx>,
retained: &RetainedOriginalMtpWeights<'ctx>,
) -> std::result::Result<(OriginalMtpActor<'ctx>, MtpOriginalInt8<'ctx>), OriginalMtpLoadError> {
let PreparedLoad { meter, plan, draft_head, .. } = prepared;
let evidence = match meter.finish(context, draft_head.as_ref(), retained.loaded_bytes()) {
Ok(value) => value,
Err(primary) => {
let _ = drafter.close();
let _ = ring.close();
return Err(primary.into());
}
};
match OriginalMtpActor::adopt(context, plan, drafter, &ring, weights, evidence) {
Ok(actor) => Ok((actor, ring)),
Err(primary) => {
let _ = ring.close();
Err(primary.into())
}
}
}
pub(in crate::qwen_forward) fn validate(
&self,
binding: &ModelBinding,
context: &Context<'ctx>,
max_t: usize,
) -> Result<()> {
if self.failed
|| self.max_t != max_t
|| !self.binding.matches(&binding.identity())
|| !std::ptr::eq(self.context, context)
{
return Err(Error::IdentityMismatch);
}
self.actor.as_ref().ok_or(Error::IdentityMismatch)?.validate_context(context).map_err(driver_error)
}
/// The verified-session adapter loans the canonical ring from
/// `OriginalDraftSession::with_pending_ring` and invokes this exact actor.
/// No public mutable ring reference escapes this module.
pub(in crate::qwen_forward) fn actor_mut(
&mut self,
binding: &ModelBinding,
context: &Context<'ctx>,
max_t: usize,
) -> Result<&mut OriginalMtpActor<'ctx>> {
self.validate(binding, context, max_t)?;
self.actor.as_mut().ok_or(Error::IdentityMismatch)
}
/// Read-only view for `device()`, `vram_bytes()`, `first_needed()`, plans.
pub(in crate::qwen_forward) fn actor(&self) -> Result<&OriginalMtpActor<'ctx>> {
self.actor.as_ref().ok_or(Error::IdentityMismatch)
}
pub(in crate::qwen_forward) fn close(mut self) -> Result<()> {
self.close_inner()
}
fn close_inner(&mut self) -> Result<()> {
self.failed = true;
// The actor drains its stream and closes the drafter before the retained
// weights it holds are released, the same order as the source.
self.actor.take().map_or(Ok(()), |owner| owner.close().map_err(driver_error))
}
}
impl Drop for OriginalMtpFullOwner<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
fn driver_error(error: leleka_cuda_driver::Error) -> Error {
if crate::driver_errors_traced() {
eprintln!("driver error: {error:?}");
}
match error {
leleka_cuda_driver::Error::ContextMismatch => Error::IdentityMismatch,
leleka_cuda_driver::Error::InvalidQwenShape
| leleka_cuda_driver::Error::InvalidSize
| leleka_cuda_driver::Error::InvalidProjectionShape => Error::InvalidDimension,
leleka_cuda_driver::Error::BudgetExceeded | leleka_cuda_driver::Error::HostAllocation => Error::InputAllocation,
leleka_cuda_driver::Error::UnsupportedQwenOperation => Error::Unsupported(Stage::Session),
_ => Error::CudaExecution,
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -442,3 +121,13 @@ mod tests {
);
}
}
mod impl_originalmtprequest;
#[allow(unused_imports)]
use impl_originalmtprequest::capture_of;
#[allow(unused_imports)]
use impl_originalmtprequest::plan_error;
mod impl_originalmtpfullowner;
mod impl_originalmtpfullowner_2;
#[allow(unused_imports)]
use impl_originalmtpfullowner_2::driver_error;
@@ -0,0 +1,193 @@
//! Moved out of the parent module by STRA-338: impl OriginalMtpFullOwner.
#[allow(unused_imports)]
use super::*;
impl<'ctx> OriginalMtpFullOwner<'ctx> {
/// `bind_bytes` for the startup reserve (generate.cpp `mtp.bind_bytes(...)`):
/// computed from the real native head and the RT directory, before any
/// device bank exists.
pub(in crate::qwen_forward) fn bind_reserve(
binding: &ModelBinding,
context: &Context<'_>,
output: &OriginalNativeOutput<'ctx>,
request: &OriginalMtpRequest,
rt_directory: &Path,
) -> Result<u64> {
let head = output.mtp_head(binding)?;
let capture = capture_of(binding, context, request, head.vocabulary());
let row_bytes = leleka_cuda_driver::native_head_row_bytes(head.kind(), head.columns())
.map_err(|_| Error::InvalidDimension)?;
leleka_cuda_driver::original_mtp_bind_reserve(
&capture,
leleka_cuda_driver::original_mtp_draft_vocab_bytes(rt_directory),
row_bytes as u64,
)
.map_err(|e| plan_error(e).error)
}
/// Literal `MtpDrafter::load` + `bind` from an RT directory. The caller
/// has already loaded the bank into `retained` (`Context::original_mtp_rt_bank`
/// then `RetainedOriginalMtpWeights::from_rt_bank`); `rt_directory` is read
/// again here only for the optional `draft_vocab.bin`, exactly where
/// `bind` reads it.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn assemble_rt(
binding: &ModelBinding,
session: &QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
retained: &RetainedOriginalMtpWeights<'ctx>,
embedding: &OriginalPromptEmbedding<'ctx>,
output: &OriginalNativeOutput<'ctx>,
request: &OriginalMtpRequest,
rt_directory: &Path,
) -> std::result::Result<OriginalMtpFullAssembly<'ctx>, OriginalMtpLoadError> {
Self::assemble_core(binding, session, context, retained, embedding, output, request, Some(rt_directory))
}
/// Same assembly over the digest-pinned pack held by the MoE cache (no RT
/// directory, hence no draft-vocab subset).
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn assemble(
binding: &ModelBinding,
session: &QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
moe: &MoeWeightCache<'ctx>,
embedding: &OriginalPromptEmbedding<'ctx>,
output: &OriginalNativeOutput<'ctx>,
request: &OriginalMtpRequest,
) -> std::result::Result<OriginalMtpFullAssembly<'ctx>, OriginalMtpLoadError> {
// Source keeps all MTP roles immutable for the life of cached graphs.
let retained = moe.retain_original_mtp_weights(binding, context)?;
Self::assemble_core(binding, session, context, &retained, embedding, output, request, None)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn assemble_core(
binding: &ModelBinding,
session: &QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
retained: &RetainedOriginalMtpWeights<'ctx>,
embedding: &OriginalPromptEmbedding<'ctx>,
output: &OriginalNativeOutput<'ctx>,
request: &OriginalMtpRequest,
rt_directory: Option<&Path>,
) -> std::result::Result<OriginalMtpFullAssembly<'ctx>, OriginalMtpLoadError> {
Self::admit_core(binding, session, context, request)?;
let prepared = Self::prepare_load(binding, context, (retained, output), (request, rt_directory))?;
let weights = Self::retained_weights(binding, context, (retained, embedding), &prepared)?;
// This returns exactly one main arena and mapped records shared by
// scalar prefill and full forward, plus the matching physical KV ring.
let shape = (request.max_t, request.prompt_capacity, prepared.coupled_layout);
let (ring, drafter) = Self::shared_drafter(context, &weights, shape)?;
let (actor, ring) = Self::adopt_actor(context, prepared, (drafter, ring, weights), retained)?;
let draft = match OriginalDraftSession::from_original_ring(binding, session, context, ring) {
Ok(value) => value,
Err(primary) => {
let _ = actor.close();
return Err(primary.into());
}
};
let owner =
Self { binding: binding.identity(), context, actor: Some(actor), max_t: request.max_t, failed: false };
Ok(OriginalMtpFullAssembly { draft, owner })
}
pub(super) fn admit_core(
binding: &ModelBinding,
session: &QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
request: &OriginalMtpRequest,
) -> std::result::Result<(), OriginalMtpLoadError> {
let (max_t, prompt_capacity) = (request.max_t, request.prompt_capacity);
if binding.layer_count() != 48
|| !(1..=8).contains(&max_t)
|| !(1..=8192).contains(&prompt_capacity)
|| !std::ptr::eq(context, session.mtp_context()?)
{
return Err(Error::IdentityMismatch.into());
}
Ok(())
}
/// The load meter, the native head, the checked plan and the optional draft head, in source order.
pub(super) fn prepare_load(
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
(retained, output): (&RetainedOriginalMtpWeights<'ctx>, &OriginalNativeOutput<'ctx>),
(request, rt_directory): (&OriginalMtpRequest, Option<&Path>),
) -> std::result::Result<PreparedLoad<'ctx>, OriginalMtpLoadError> {
// Fresh ledger window: the bank's own bytes are added by `finish`.
let meter = OriginalMtpLoadMeter::start(context);
let head = output.mtp_head(binding)?;
// geometry/session/device capture -> checked plan (refuses what the
// retained owners cannot represent instead of planning around it)
let capture = capture_of(binding, context, request, head.vocabulary());
let plan = OriginalMtpLoadPlan::new(capture, retained.dense_file_bytes()).map_err(plan_error)?;
// ---- bind: optional draft head (needs the main head's weights)
let draft_head: Option<OriginalMtpDraftHead<'ctx>> = match rt_directory {
Some(directory) => {
let weights = head.weights();
context.original_mtp_draft_head(directory, &weights, head.kind(), head.columns(), head.vocabulary())?
}
None => None,
};
let subset = draft_head.as_ref().map(|h| h.count() as u64);
let coupled_layout = plan.coupled_layout(subset).map_err(plan_error)?;
Ok(PreparedLoad { meter, head, plan, draft_head, coupled_layout })
}
pub(super) fn retained_weights(
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
(retained, embedding): (&RetainedOriginalMtpWeights<'ctx>, &OriginalPromptEmbedding<'ctx>),
prepared: &PreparedLoad<'ctx>,
) -> std::result::Result<Rc<OriginalMtpRetainedFullWeights<'ctx>>, OriginalMtpLoadError> {
let head = &prepared.head;
let scalar = retained.scalar_prefill_weights(binding, context, embedding)?;
let prefix = Rc::new(OriginalMtpRetainedPrefix::from_scalar(scalar).map_err(driver_error)?);
let draft_head = prepared.draft_head.as_ref();
Ok(retained.full_forward_weights(binding, context, prefix, head, head.vocabulary(), draft_head)?)
}
pub(super) fn shared_drafter(
context: &'ctx Context<'ctx>,
weights: &Rc<OriginalMtpRetainedFullWeights<'ctx>>,
(max_t, prompt_capacity, coupled_layout): (usize, usize, bool),
) -> std::result::Result<(MtpOriginalInt8<'ctx>, OriginalMtpDrafter<'ctx>), OriginalMtpLoadError> {
let (ring, scalar, full) = context
.original_mtp_shared_layout_with_ring(Rc::clone(weights), max_t, prompt_capacity, coupled_layout)
.map_err(driver_error)?;
match OriginalMtpDrafter::new(full, scalar) {
Ok(drafter) => Ok((ring, drafter)),
Err(primary) => {
let close = ring.close().map_err(driver_error);
Err(match close {
Err(cleanup) => cleanup,
Ok(()) => driver_error(primary),
}
.into())
}
}
}
/// Meters the finished load and adopts drafter, ring and weights into the actor; the failure paths close what exists.
pub(super) fn adopt_actor(
context: &'ctx Context<'ctx>,
prepared: PreparedLoad<'ctx>,
(drafter, ring, weights): AdoptParts<'ctx>,
retained: &RetainedOriginalMtpWeights<'ctx>,
) -> std::result::Result<(OriginalMtpActor<'ctx>, MtpOriginalInt8<'ctx>), OriginalMtpLoadError> {
let PreparedLoad { meter, plan, draft_head, .. } = prepared;
let evidence = match meter.finish(context, draft_head.as_ref(), retained.loaded_bytes()) {
Ok(value) => value,
Err(primary) => {
let _ = drafter.close();
let _ = ring.close();
return Err(primary.into());
}
};
match OriginalMtpActor::adopt(context, plan, drafter, &ring, weights, evidence) {
Ok(actor) => Ok((actor, ring)),
Err(primary) => {
let _ = ring.close();
Err(primary.into())
}
}
}
}
@@ -0,0 +1,69 @@
//! Moved out of the parent module by STRA-338.
#[allow(unused_imports)]
use super::*;
impl<'ctx> OriginalMtpFullOwner<'ctx> {
pub(in crate::qwen_forward) fn validate(
&self,
binding: &ModelBinding,
context: &Context<'ctx>,
max_t: usize,
) -> Result<()> {
if self.failed
|| self.max_t != max_t
|| !self.binding.matches(&binding.identity())
|| !std::ptr::eq(self.context, context)
{
return Err(Error::IdentityMismatch);
}
self.actor.as_ref().ok_or(Error::IdentityMismatch)?.validate_context(context).map_err(driver_error)
}
/// The verified-session adapter loans the canonical ring from
/// `OriginalDraftSession::with_pending_ring` and invokes this exact actor.
/// No public mutable ring reference escapes this module.
pub(in crate::qwen_forward) fn actor_mut(
&mut self,
binding: &ModelBinding,
context: &Context<'ctx>,
max_t: usize,
) -> Result<&mut OriginalMtpActor<'ctx>> {
self.validate(binding, context, max_t)?;
self.actor.as_mut().ok_or(Error::IdentityMismatch)
}
/// Read-only view for `device()`, `vram_bytes()`, `first_needed()`, plans.
pub(in crate::qwen_forward) fn actor(&self) -> Result<&OriginalMtpActor<'ctx>> {
self.actor.as_ref().ok_or(Error::IdentityMismatch)
}
pub(in crate::qwen_forward) fn close(mut self) -> Result<()> {
self.close_inner()
}
pub(super) fn close_inner(&mut self) -> Result<()> {
self.failed = true;
// The actor drains its stream and closes the drafter before the retained
// weights it holds are released, the same order as the source.
self.actor.take().map_or(Ok(()), |owner| owner.close().map_err(driver_error))
}
}
impl Drop for OriginalMtpFullOwner<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
pub(super) fn driver_error(error: leleka_cuda_driver::Error) -> Error {
if crate::driver_errors_traced() {
eprintln!("driver error: {error:?}");
}
match error {
leleka_cuda_driver::Error::ContextMismatch => Error::IdentityMismatch,
leleka_cuda_driver::Error::InvalidQwenShape
| leleka_cuda_driver::Error::InvalidSize
| leleka_cuda_driver::Error::InvalidProjectionShape => Error::InvalidDimension,
leleka_cuda_driver::Error::BudgetExceeded | leleka_cuda_driver::Error::HostAllocation => Error::InputAllocation,
leleka_cuda_driver::Error::UnsupportedQwenOperation => Error::Unsupported(Stage::Session),
_ => Error::CudaExecution,
}
}
@@ -0,0 +1,74 @@
//! Moved out of the parent module by STRA-338.
#[allow(unused_imports)]
use super::*;
impl OriginalMtpRequest {
/// Original defaults: window 32768 and the INT8 window-ring draft state.
pub(in crate::qwen_forward) fn ring_int8(
max_t: usize,
prompt_capacity: usize,
coupled: bool,
resident_cells: u64,
) -> Self {
Self {
max_t,
prompt_capacity,
coupled,
window: leleka_cuda_driver::MTP_ORIGINAL_WINDOW as i64,
kv: OriginalMtpKvStartup::ring_int8(resident_cells),
}
}
}
impl From<Error> for OriginalMtpLoadError {
fn from(error: Error) -> Self {
Self { error, message: None }
}
}
impl From<OriginalMtpLoadFailure> for OriginalMtpLoadError {
fn from(failure: OriginalMtpLoadFailure) -> Self {
let error = match failure.cause() {
Some(leleka_cuda_driver::Error::BudgetExceeded | leleka_cuda_driver::Error::HostAllocation) => {
Error::InputAllocation
}
Some(leleka_cuda_driver::Error::ContextMismatch) => Error::IdentityMismatch,
Some(
leleka_cuda_driver::Error::InvalidQwenShape
| leleka_cuda_driver::Error::InvalidSize
| leleka_cuda_driver::Error::ShapeMismatch { .. },
) => Error::InvalidDimension,
Some(leleka_cuda_driver::Error::UnsupportedQwenOperation) => Error::Unsupported(Stage::Session),
Some(_) => Error::CudaExecution,
None => Error::InputRead,
};
Self { error, message: Some(failure.message().to_owned()) }
}
}
pub(super) fn plan_error(error: OriginalMtpPlanError) -> OriginalMtpLoadError {
let kind = match error {
OriginalMtpPlanError::ClosedProfile(_) => Error::Unsupported(Stage::Session),
OriginalMtpPlanError::Overflow => Error::Overflow,
_ => Error::InvalidDimension,
};
OriginalMtpLoadError { error: kind, message: Some(error.message()) }
}
pub(super) fn capture_of(
binding: &ModelBinding,
context: &Context<'_>,
request: &OriginalMtpRequest,
vocabulary: usize,
) -> OriginalMtpCapture {
OriginalMtpCapture {
// `cudaGetDevice` at load, `g.n_expert`, `ss.k`, `max_cells` of the primary QSA state.
device: context.device_ordinal(),
n_expert: u64::from(binding.expert_count()),
top_k: u64::from(binding.expert_used_count()),
max_cells: u64::from(binding.input_constants().context_length()),
max_t: request.max_t as u64,
window: request.window,
vocabulary: vocabulary as u64,
kv: request.kv,
coupled_requested: request.coupled,
}
}
@@ -50,153 +50,6 @@ pub(in crate::qwen_forward) struct OriginalMtpDraftReceipt<'ctx> {
origin: TargetStepOrigin,
completed: CompletedOriginalMtpDraft<'ctx>,
}
impl<'ctx> OriginalMtpDraftReceipt<'ctx> {
pub(in crate::qwen_forward) fn ids(&self) -> &[i32] {
self.completed.ids()
}
pub(in crate::qwen_forward) fn probabilities(&self) -> &[f32] {
self.completed.probabilities()
}
pub(in crate::qwen_forward) fn count(&self) -> usize {
self.completed.count()
}
pub(in crate::qwen_forward) fn first_position(&self) -> usize {
self.completed.first_position()
}
pub(in crate::qwen_forward) fn accepted_row(&self) -> usize {
self.completed.accepted_row()
}
/// The next verifier may read these predictions only while the real target
/// prefix still equals the commit that produced this draft. The MTP ring
/// intentionally contains provisional catch-up cells past target position.
pub(in crate::qwen_forward) fn validate_current(
&self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
draft: &mut OriginalDraftSession<'ctx>,
) -> Result<()> {
if !self.binding.matches(&binding.identity()) || !std::ptr::eq(self.context, session.mtp_context()?) {
return Err(Error::IdentityMismatch);
}
draft.with_mtp_current_ring(binding, session, &self.origin, |ring, _| {
self.completed.validate_current(ring).map_err(driver_error)
})
}
}
impl<'ctx> OriginalVerifiedMtpReceipt<'ctx> {
pub(in crate::qwen_forward) fn new(
binding: &ModelBinding,
session: &QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
window: OriginalVerifyWindow<'ctx>,
selection: NativeHeadSelection,
accepted_row: usize,
) -> Result<Self> {
let before = session.target_origin()?;
window.validate_context(context).map_err(driver_error)?;
window.validate_selection(&selection).map_err(driver_error)?;
let first = window.first_position();
if !std::ptr::eq(context, session.mtp_context()?)
|| first != usize::try_from(before.next_position()).map_err(|_| Error::Overflow)?
|| accepted_row >= window.rows()
{
return Err(Error::IdentityMismatch);
}
Ok(Self { binding: binding.identity(), context, window, selection, before, first, accepted_row })
}
/// Must be called after the genuine verifier has committed exactly the
/// source accept count through `QwenChunkTxn::publish_verified_joint`.
/// The resulting `TargetStepProduct` rejects skipped, extra, manually
/// advanced, or cross-branch target publication before MTP capture.
pub(in crate::qwen_forward) fn after_target_commit(
self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
committed_source: &TargetStepProduct,
) -> Result<OriginalCommittedMtpReceipt<'ctx>> {
let committed = session.target_origin()?;
let (_, source_position, _, source_origin) = committed_source.mtp_source(binding, session)?;
self.before.validate_projection_branch(session)?;
let expected =
self.first.checked_add(self.accepted_row).and_then(|n| n.checked_add(1)).ok_or(Error::Overflow)?;
if !self.binding.matches(&binding.identity())
|| !std::ptr::eq(self.context, session.mtp_context()?)
|| !self.before.same_session(&committed)
|| !source_origin.same_prefix(&committed)
|| source_position.get().checked_add(1).ok_or(Error::Overflow)? != committed.next_position()
|| usize::try_from(committed.next_position()).map_err(|_| Error::Overflow)? != expected
{
return Err(Error::IdentityMismatch);
}
Ok(OriginalCommittedMtpReceipt {
binding: self.binding,
context: self.context,
window: self.window,
selection: self.selection,
before: self.before,
committed,
accepted_row: self.accepted_row,
})
}
}
impl<'ctx> OriginalCommittedMtpReceipt<'ctx> {
/// The receipt of a completed verifier window whose accepted prefix the session ALREADY holds.
/// The serve path publishes the session when the commit event completes (the accepted state is read
/// back from the verifier then), so the draft is requested with the pre-window origin captured at
/// `run` time and the session's current (committed) origin; nothing here advances either. Exactly the
/// same acceptance rules as `after_target_commit`, without a `TargetStepProduct` (the native verifier
/// has none): same session and branch, the window started where the session stood, and the session now
/// stands exactly `accepted_row + 1` rows later.
pub(in crate::qwen_forward) fn for_published_window(
binding: &ModelBinding,
session: &QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
window: OriginalVerifyWindow<'ctx>,
selection: NativeHeadSelection,
before: TargetStepOrigin,
accepted_row: usize,
) -> Result<Self> {
let committed = session.target_origin()?;
window.validate_context(context).map_err(driver_error)?;
window.validate_selection(&selection).map_err(driver_error)?;
let first = u64::try_from(window.first_position()).map_err(|_| Error::Overflow)?;
let expected = first.checked_add(accepted_row as u64).and_then(|n| n.checked_add(1)).ok_or(Error::Overflow)?;
if !std::ptr::eq(context, session.mtp_context()?)
|| accepted_row >= window.rows()
|| !before.same_session(&committed)
|| before.next_position() != first
|| committed.next_position() != expected
{
return Err(Error::IdentityMismatch);
}
before.validate_projection_branch(session)?;
Ok(Self { binding: binding.identity(), context, window, selection, before, committed, accepted_row })
}
fn validate(&self, binding: &ModelBinding, session: &QwenSession<'ctx>, context: &Context<'ctx>) -> Result<()> {
self.window.validate_context(context).map_err(driver_error)?;
self.window.validate_selection(&self.selection).map_err(driver_error)?;
let expected = self
.window
.first_position()
.checked_add(self.accepted_row)
.and_then(|n| n.checked_add(1))
.ok_or(Error::Overflow)?;
self.before.validate_projection_branch(session)?;
self.committed.validate(session)?;
if !self.binding.matches(&binding.identity())
|| !std::ptr::eq(self.context, context)
|| !std::ptr::eq(context, session.mtp_context()?)
|| !self.before.same_session(&self.committed)
|| usize::try_from(self.committed.next_position()).map_err(|_| Error::Overflow)? != expected
|| self.accepted_row >= self.window.rows()
{
return Err(Error::IdentityMismatch);
}
Ok(())
}
}
/// A draft launched behind an enqueued, not yet published commit (`launch_committing_mtp`). It names the branch the
/// session stood on and the one the commit publishes; `finish_committing_mtp` completes it only once the session
@@ -207,208 +60,8 @@ pub(in crate::qwen_forward) struct OriginalLaunchedMtpDraft {
prospective: TargetStepOrigin,
}
impl<'ctx> OriginalPromptExecutor<'ctx> {
/// generate.cpp's order without the host wait between them: the verifier commit of `accepted_row + 1` rows is
/// enqueued (`after` is its completion event, which the draft stream waits on the device) and the full MTP draft
/// of the same completed window is enqueued behind it, while the session still stands at `before`. The same
/// acceptance rules as `OriginalCommittedMtpReceipt::for_published_window`, with the published origin replaced by
/// the one the commit will publish.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn launch_committing_mtp(
&mut self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
draft: &mut OriginalDraftSession<'ctx>,
window: OriginalVerifyWindow<'ctx>,
selection: NativeHeadSelection,
before: TargetStepOrigin,
accepted_row: usize,
min_p: f32,
policy: &OriginalMtpFullPolicy,
after: Option<&mut OriginalGpuEvent<'ctx>>,
) -> Result<OriginalLaunchedMtpDraft> {
self.admit_launch(&window, &selection, min_p)?;
let prospective = self.launch_origin(session, &window, &before, accepted_row)?;
before.validate(session)?;
let actor = self.checked_mtp_actor(binding)?;
draft.with_mtp_launch_ring(binding, session, &before, &prospective, |ring, prior| {
actor
.launch_draft_from_verifier(ring, prior, window, selection, accepted_row, min_p, policy, after)
.map_err(driver_error)
})?;
Ok(OriginalLaunchedMtpDraft { binding: binding.identity(), before, prospective })
}
fn admit_launch(
&self,
window: &OriginalVerifyWindow<'ctx>,
selection: &NativeHeadSelection,
min_p: f32,
) -> Result<()> {
window.validate_context(self.context).map_err(driver_error)?;
window.validate_selection(selection).map_err(driver_error)?;
if !min_p.is_finite() {
return Err(Error::InvalidDimension);
}
Ok(())
}
/// The origin the enqueued commit will publish, after the window and the session agree on where it stands.
fn launch_origin(
&self,
session: &QwenSession<'ctx>,
window: &OriginalVerifyWindow<'ctx>,
before: &TargetStepOrigin,
accepted_row: usize,
) -> Result<TargetStepOrigin> {
let first = u64::try_from(window.first_position()).map_err(|_| Error::Overflow)?;
let prospective = session.original_origin_after(accepted_row.checked_add(1).ok_or(Error::Overflow)?)?;
let expected = first.checked_add(accepted_row as u64).and_then(|n| n.checked_add(1)).ok_or(Error::Overflow)?;
if !std::ptr::eq(self.context, session.mtp_context()?)
|| accepted_row >= window.rows()
|| before.next_position() != first
|| prospective.next_position() != expected
{
return Err(Error::IdentityMismatch);
}
Ok(prospective)
}
/// The second half of `launch_committing_mtp`, after the commit was published: the session must hold exactly the
/// launched draft's prospective origin. Then the completion is published to the ring as `draft_committed_mtp` does.
pub(in crate::qwen_forward) fn finish_committing_mtp(
&mut self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
draft: &mut OriginalDraftSession<'ctx>,
launched: OriginalLaunchedMtpDraft,
policy: &OriginalMtpFullPolicy,
) -> Result<OriginalMtpDraftReceipt<'ctx>> {
let committed = session.target_origin()?;
if !launched.binding.matches(&binding.identity()) || !launched.prospective.same_prefix(&committed) {
return Err(Error::IdentityMismatch);
}
let actor = self.mtp_actor(binding)?;
let completed =
draft.with_mtp_transition_ring(binding, session, &launched.before, &committed, |ring, prior| {
actor.finish_draft_from_verifier(ring, prior, policy).map_err(driver_error)
})?;
draft.publish_mtp_completion(binding, session, &launched.before, &committed, &completed)?;
Ok(OriginalMtpDraftReceipt { binding: binding.identity(), context: self.context, origin: committed, completed })
}
/// Literal source order: verifier completion -> target commit -> full MTP
/// draft. This neither commits target state nor accepts tokens; both are
/// already evidenced by `OriginalCommittedMtpReceipt`. `max_drafts` and
/// the coupled request/history come from the loaded actor (`set_max_drafts`,
/// `set_draft_sampling`, `set_draft_history`), as in `MtpDrafter::draft`.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn draft_committed_mtp(
&mut self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
draft: &mut OriginalDraftSession<'ctx>,
receipt: OriginalCommittedMtpReceipt<'ctx>,
min_p: f32,
policy: &OriginalMtpFullPolicy,
) -> Result<OriginalMtpDraftReceipt<'ctx>> {
receipt.validate(binding, session, self.context)?;
if !min_p.is_finite() {
return Err(Error::InvalidDimension);
}
let actor = self.checked_mtp_actor(binding)?;
let completed =
draft.with_mtp_transition_ring(binding, session, &receipt.before, &receipt.committed, |ring, prior| {
actor
.draft_from_verifier(
ring,
prior,
receipt.window,
receipt.selection,
receipt.accepted_row,
min_p,
policy,
)
.map_err(driver_error)
})?;
self.publish_draft_receipt(binding, session, draft, (&receipt.before, receipt.committed), completed)
}
/// generate.cpp `mtp.draft_first(o.spec, ss.R, x, p - 1, drafts, ...)`: the
/// first round after the prompt, from the single-row verifier window of the
/// final prompt seed (the Original repeat-row path), not `draft`'s catch-up.
/// Same order and receipts as `draft_committed_mtp`; `rows` is `T`.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn draft_first_committed_mtp(
&mut self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
draft: &mut OriginalDraftSession<'ctx>,
receipt: OriginalCommittedMtpReceipt<'ctx>,
rows: usize,
min_p: f32,
policy: &OriginalMtpFullPolicy,
) -> Result<OriginalMtpDraftReceipt<'ctx>> {
receipt.validate(binding, session, self.context)?;
if !min_p.is_finite() || receipt.accepted_row != 0 || receipt.window.rows() != 1 {
return Err(Error::InvalidDimension);
}
let actor = self.checked_mtp_actor(binding)?;
let completed =
draft.with_mtp_transition_ring(binding, session, &receipt.before, &receipt.committed, |ring, prior| {
actor
.draft_first_from_verifier(ring, prior, receipt.window, receipt.selection, rows, min_p, policy)
.map_err(driver_error)
})?;
self.publish_draft_receipt(binding, session, draft, (&receipt.before, receipt.committed), completed)
}
/// The loaded actor, refused when its draft cap was never configured.
fn checked_mtp_actor(&mut self, binding: &ModelBinding) -> Result<&mut leleka_cuda_driver::OriginalMtpActor<'ctx>> {
let actor = self.mtp_actor(binding)?;
if actor.settings().max_drafts() < 0 {
return Err(Error::InvalidDimension);
}
Ok(actor)
}
/// Publishes the completed draft to the ring and seals it into the receipt of the committed origin.
fn publish_draft_receipt(
&self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
draft: &mut OriginalDraftSession<'ctx>,
(before, committed): (&TargetStepOrigin, TargetStepOrigin),
completed: CompletedOriginalMtpDraft<'ctx>,
) -> Result<OriginalMtpDraftReceipt<'ctx>> {
draft.publish_mtp_completion(binding, session, before, &committed, &completed)?;
Ok(OriginalMtpDraftReceipt { binding: binding.identity(), context: self.context, origin: committed, completed })
}
/// `mtp.set_draft_sampling(req_sp)` (a no-op unless coupled setup succeeded).
pub(in crate::qwen_forward) fn set_mtp_draft_sampling(
&mut self,
binding: &ModelBinding,
params: &SamplerParams,
) -> Result<()> {
self.mtp_actor(binding)?.set_draft_sampling(params);
Ok(())
}
/// `mtp.set_draft_history(consumed, n, next)` before the next draft.
pub(in crate::qwen_forward) fn set_mtp_draft_history(
&mut self,
binding: &ModelBinding,
tail: &[i32],
next: i32,
) -> Result<()> {
self.mtp_actor(binding)?.set_draft_history(tail, next).map_err(driver_error)
}
}
fn driver_error(error: leleka_cuda_driver::Error) -> Error {
if crate::driver_errors_traced() {
eprintln!("driver error: {error:?}");
}
match error {
leleka_cuda_driver::Error::ContextMismatch => Error::IdentityMismatch,
leleka_cuda_driver::Error::InvalidQwenShape
| leleka_cuda_driver::Error::InvalidSize
| leleka_cuda_driver::Error::InvalidProjectionShape => Error::InvalidDimension,
leleka_cuda_driver::Error::BudgetExceeded | leleka_cuda_driver::Error::HostAllocation => Error::InputAllocation,
leleka_cuda_driver::Error::UnsupportedQwenOperation => Error::Unsupported(super::contract::Stage::Session),
leleka_cuda_driver::Error::NonFiniteMmqOutput(_) => Error::NonFinite,
_ => Error::CudaExecution,
}
}
mod driver_error_fn;
mod impl_originalmtpdraftreceipt;
mod impl_originalpromptexecutor;
#[allow(unused_imports)]
use driver_error_fn::driver_error;
@@ -0,0 +1,22 @@
//! Moved out of the parent module by STRA-338: fn driver_error.
#[allow(unused_imports)]
use super::*;
pub(super) fn driver_error(error: leleka_cuda_driver::Error) -> Error {
if crate::driver_errors_traced() {
eprintln!("driver error: {error:?}");
}
match error {
leleka_cuda_driver::Error::ContextMismatch => Error::IdentityMismatch,
leleka_cuda_driver::Error::InvalidQwenShape
| leleka_cuda_driver::Error::InvalidSize
| leleka_cuda_driver::Error::InvalidProjectionShape => Error::InvalidDimension,
leleka_cuda_driver::Error::BudgetExceeded | leleka_cuda_driver::Error::HostAllocation => Error::InputAllocation,
leleka_cuda_driver::Error::UnsupportedQwenOperation => {
Error::Unsupported(super::super::contract::Stage::Session)
}
leleka_cuda_driver::Error::NonFiniteMmqOutput(_) => Error::NonFinite,
_ => Error::CudaExecution,
}
}
@@ -0,0 +1,157 @@
//! Moved out of the parent module by STRA-338.
#[allow(unused_imports)]
use super::*;
impl<'ctx> OriginalMtpDraftReceipt<'ctx> {
pub(in crate::qwen_forward) fn ids(&self) -> &[i32] {
self.completed.ids()
}
pub(in crate::qwen_forward) fn probabilities(&self) -> &[f32] {
self.completed.probabilities()
}
pub(in crate::qwen_forward) fn count(&self) -> usize {
self.completed.count()
}
pub(in crate::qwen_forward) fn first_position(&self) -> usize {
self.completed.first_position()
}
pub(in crate::qwen_forward) fn accepted_row(&self) -> usize {
self.completed.accepted_row()
}
/// The next verifier may read these predictions only while the real target
/// prefix still equals the commit that produced this draft. The MTP ring
/// intentionally contains provisional catch-up cells past target position.
pub(in crate::qwen_forward) fn validate_current(
&self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
draft: &mut OriginalDraftSession<'ctx>,
) -> Result<()> {
if !self.binding.matches(&binding.identity()) || !std::ptr::eq(self.context, session.mtp_context()?) {
return Err(Error::IdentityMismatch);
}
draft.with_mtp_current_ring(binding, session, &self.origin, |ring, _| {
self.completed.validate_current(ring).map_err(driver_error)
})
}
}
impl<'ctx> OriginalVerifiedMtpReceipt<'ctx> {
pub(in crate::qwen_forward) fn new(
binding: &ModelBinding,
session: &QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
window: OriginalVerifyWindow<'ctx>,
selection: NativeHeadSelection,
accepted_row: usize,
) -> Result<Self> {
let before = session.target_origin()?;
window.validate_context(context).map_err(driver_error)?;
window.validate_selection(&selection).map_err(driver_error)?;
let first = window.first_position();
if !std::ptr::eq(context, session.mtp_context()?)
|| first != usize::try_from(before.next_position()).map_err(|_| Error::Overflow)?
|| accepted_row >= window.rows()
{
return Err(Error::IdentityMismatch);
}
Ok(Self { binding: binding.identity(), context, window, selection, before, first, accepted_row })
}
/// Must be called after the genuine verifier has committed exactly the
/// source accept count through `QwenChunkTxn::publish_verified_joint`.
/// The resulting `TargetStepProduct` rejects skipped, extra, manually
/// advanced, or cross-branch target publication before MTP capture.
pub(in crate::qwen_forward) fn after_target_commit(
self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
committed_source: &TargetStepProduct,
) -> Result<OriginalCommittedMtpReceipt<'ctx>> {
let committed = session.target_origin()?;
let (_, source_position, _, source_origin) = committed_source.mtp_source(binding, session)?;
self.before.validate_projection_branch(session)?;
let expected =
self.first.checked_add(self.accepted_row).and_then(|n| n.checked_add(1)).ok_or(Error::Overflow)?;
if !self.binding.matches(&binding.identity())
|| !std::ptr::eq(self.context, session.mtp_context()?)
|| !self.before.same_session(&committed)
|| !source_origin.same_prefix(&committed)
|| source_position.get().checked_add(1).ok_or(Error::Overflow)? != committed.next_position()
|| usize::try_from(committed.next_position()).map_err(|_| Error::Overflow)? != expected
{
return Err(Error::IdentityMismatch);
}
Ok(OriginalCommittedMtpReceipt {
binding: self.binding,
context: self.context,
window: self.window,
selection: self.selection,
before: self.before,
committed,
accepted_row: self.accepted_row,
})
}
}
impl<'ctx> OriginalCommittedMtpReceipt<'ctx> {
/// The receipt of a completed verifier window whose accepted prefix the session ALREADY holds.
/// The serve path publishes the session when the commit event completes (the accepted state is read
/// back from the verifier then), so the draft is requested with the pre-window origin captured at
/// `run` time and the session's current (committed) origin; nothing here advances either. Exactly the
/// same acceptance rules as `after_target_commit`, without a `TargetStepProduct` (the native verifier
/// has none): same session and branch, the window started where the session stood, and the session now
/// stands exactly `accepted_row + 1` rows later.
pub(in crate::qwen_forward) fn for_published_window(
binding: &ModelBinding,
session: &QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
window: OriginalVerifyWindow<'ctx>,
selection: NativeHeadSelection,
before: TargetStepOrigin,
accepted_row: usize,
) -> Result<Self> {
let committed = session.target_origin()?;
window.validate_context(context).map_err(driver_error)?;
window.validate_selection(&selection).map_err(driver_error)?;
let first = u64::try_from(window.first_position()).map_err(|_| Error::Overflow)?;
let expected = first.checked_add(accepted_row as u64).and_then(|n| n.checked_add(1)).ok_or(Error::Overflow)?;
if !std::ptr::eq(context, session.mtp_context()?)
|| accepted_row >= window.rows()
|| !before.same_session(&committed)
|| before.next_position() != first
|| committed.next_position() != expected
{
return Err(Error::IdentityMismatch);
}
before.validate_projection_branch(session)?;
Ok(Self { binding: binding.identity(), context, window, selection, before, committed, accepted_row })
}
pub(super) fn validate(
&self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
context: &Context<'ctx>,
) -> Result<()> {
self.window.validate_context(context).map_err(driver_error)?;
self.window.validate_selection(&self.selection).map_err(driver_error)?;
let expected = self
.window
.first_position()
.checked_add(self.accepted_row)
.and_then(|n| n.checked_add(1))
.ok_or(Error::Overflow)?;
self.before.validate_projection_branch(session)?;
self.committed.validate(session)?;
if !self.binding.matches(&binding.identity())
|| !std::ptr::eq(self.context, context)
|| !std::ptr::eq(context, session.mtp_context()?)
|| !self.before.same_session(&self.committed)
|| usize::try_from(self.committed.next_position()).map_err(|_| Error::Overflow)? != expected
|| self.accepted_row >= self.window.rows()
{
return Err(Error::IdentityMismatch);
}
Ok(())
}
}
@@ -0,0 +1,197 @@
//! Moved out of the parent module by STRA-338: impl OriginalPromptExecutor.
#[allow(unused_imports)]
use super::*;
impl<'ctx> OriginalPromptExecutor<'ctx> {
/// generate.cpp's order without the host wait between them: the verifier commit of `accepted_row + 1` rows is
/// enqueued (`after` is its completion event, which the draft stream waits on the device) and the full MTP draft
/// of the same completed window is enqueued behind it, while the session still stands at `before`. The same
/// acceptance rules as `OriginalCommittedMtpReceipt::for_published_window`, with the published origin replaced by
/// the one the commit will publish.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn launch_committing_mtp(
&mut self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
draft: &mut OriginalDraftSession<'ctx>,
window: OriginalVerifyWindow<'ctx>,
selection: NativeHeadSelection,
before: TargetStepOrigin,
accepted_row: usize,
min_p: f32,
policy: &OriginalMtpFullPolicy,
after: Option<&mut OriginalGpuEvent<'ctx>>,
) -> Result<OriginalLaunchedMtpDraft> {
self.admit_launch(&window, &selection, min_p)?;
let prospective = self.launch_origin(session, &window, &before, accepted_row)?;
before.validate(session)?;
let actor = self.checked_mtp_actor(binding)?;
draft.with_mtp_launch_ring(binding, session, &before, &prospective, |ring, prior| {
actor
.launch_draft_from_verifier(ring, prior, window, selection, accepted_row, min_p, policy, after)
.map_err(driver_error)
})?;
Ok(OriginalLaunchedMtpDraft { binding: binding.identity(), before, prospective })
}
pub(super) fn admit_launch(
&self,
window: &OriginalVerifyWindow<'ctx>,
selection: &NativeHeadSelection,
min_p: f32,
) -> Result<()> {
window.validate_context(self.context).map_err(driver_error)?;
window.validate_selection(selection).map_err(driver_error)?;
if !min_p.is_finite() {
return Err(Error::InvalidDimension);
}
Ok(())
}
/// The origin the enqueued commit will publish, after the window and the session agree on where it stands.
pub(super) fn launch_origin(
&self,
session: &QwenSession<'ctx>,
window: &OriginalVerifyWindow<'ctx>,
before: &TargetStepOrigin,
accepted_row: usize,
) -> Result<TargetStepOrigin> {
let first = u64::try_from(window.first_position()).map_err(|_| Error::Overflow)?;
let prospective = session.original_origin_after(accepted_row.checked_add(1).ok_or(Error::Overflow)?)?;
let expected = first.checked_add(accepted_row as u64).and_then(|n| n.checked_add(1)).ok_or(Error::Overflow)?;
if !std::ptr::eq(self.context, session.mtp_context()?)
|| accepted_row >= window.rows()
|| before.next_position() != first
|| prospective.next_position() != expected
{
return Err(Error::IdentityMismatch);
}
Ok(prospective)
}
/// The second half of `launch_committing_mtp`, after the commit was published: the session must hold exactly the
/// launched draft's prospective origin. Then the completion is published to the ring as `draft_committed_mtp` does.
pub(in crate::qwen_forward) fn finish_committing_mtp(
&mut self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
draft: &mut OriginalDraftSession<'ctx>,
launched: OriginalLaunchedMtpDraft,
policy: &OriginalMtpFullPolicy,
) -> Result<OriginalMtpDraftReceipt<'ctx>> {
let committed = session.target_origin()?;
if !launched.binding.matches(&binding.identity()) || !launched.prospective.same_prefix(&committed) {
return Err(Error::IdentityMismatch);
}
let actor = self.mtp_actor(binding)?;
let completed =
draft.with_mtp_transition_ring(binding, session, &launched.before, &committed, |ring, prior| {
actor.finish_draft_from_verifier(ring, prior, policy).map_err(driver_error)
})?;
draft.publish_mtp_completion(binding, session, &launched.before, &committed, &completed)?;
Ok(OriginalMtpDraftReceipt { binding: binding.identity(), context: self.context, origin: committed, completed })
}
/// Literal source order: verifier completion -> target commit -> full MTP
/// draft. This neither commits target state nor accepts tokens; both are
/// already evidenced by `OriginalCommittedMtpReceipt`. `max_drafts` and
/// the coupled request/history come from the loaded actor (`set_max_drafts`,
/// `set_draft_sampling`, `set_draft_history`), as in `MtpDrafter::draft`.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn draft_committed_mtp(
&mut self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
draft: &mut OriginalDraftSession<'ctx>,
receipt: OriginalCommittedMtpReceipt<'ctx>,
min_p: f32,
policy: &OriginalMtpFullPolicy,
) -> Result<OriginalMtpDraftReceipt<'ctx>> {
receipt.validate(binding, session, self.context)?;
if !min_p.is_finite() {
return Err(Error::InvalidDimension);
}
let actor = self.checked_mtp_actor(binding)?;
let completed =
draft.with_mtp_transition_ring(binding, session, &receipt.before, &receipt.committed, |ring, prior| {
actor
.draft_from_verifier(
ring,
prior,
receipt.window,
receipt.selection,
receipt.accepted_row,
min_p,
policy,
)
.map_err(driver_error)
})?;
self.publish_draft_receipt(binding, session, draft, (&receipt.before, receipt.committed), completed)
}
/// generate.cpp `mtp.draft_first(o.spec, ss.R, x, p - 1, drafts, ...)`: the
/// first round after the prompt, from the single-row verifier window of the
/// final prompt seed (the Original repeat-row path), not `draft`'s catch-up.
/// Same order and receipts as `draft_committed_mtp`; `rows` is `T`.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn draft_first_committed_mtp(
&mut self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
draft: &mut OriginalDraftSession<'ctx>,
receipt: OriginalCommittedMtpReceipt<'ctx>,
rows: usize,
min_p: f32,
policy: &OriginalMtpFullPolicy,
) -> Result<OriginalMtpDraftReceipt<'ctx>> {
receipt.validate(binding, session, self.context)?;
if !min_p.is_finite() || receipt.accepted_row != 0 || receipt.window.rows() != 1 {
return Err(Error::InvalidDimension);
}
let actor = self.checked_mtp_actor(binding)?;
let completed =
draft.with_mtp_transition_ring(binding, session, &receipt.before, &receipt.committed, |ring, prior| {
actor
.draft_first_from_verifier(ring, prior, receipt.window, receipt.selection, rows, min_p, policy)
.map_err(driver_error)
})?;
self.publish_draft_receipt(binding, session, draft, (&receipt.before, receipt.committed), completed)
}
/// The loaded actor, refused when its draft cap was never configured.
pub(super) fn checked_mtp_actor(
&mut self,
binding: &ModelBinding,
) -> Result<&mut leleka_cuda_driver::OriginalMtpActor<'ctx>> {
let actor = self.mtp_actor(binding)?;
if actor.settings().max_drafts() < 0 {
return Err(Error::InvalidDimension);
}
Ok(actor)
}
/// Publishes the completed draft to the ring and seals it into the receipt of the committed origin.
pub(super) fn publish_draft_receipt(
&self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
draft: &mut OriginalDraftSession<'ctx>,
(before, committed): (&TargetStepOrigin, TargetStepOrigin),
completed: CompletedOriginalMtpDraft<'ctx>,
) -> Result<OriginalMtpDraftReceipt<'ctx>> {
draft.publish_mtp_completion(binding, session, before, &committed, &completed)?;
Ok(OriginalMtpDraftReceipt { binding: binding.identity(), context: self.context, origin: committed, completed })
}
/// `mtp.set_draft_sampling(req_sp)` (a no-op unless coupled setup succeeded).
pub(in crate::qwen_forward) fn set_mtp_draft_sampling(
&mut self,
binding: &ModelBinding,
params: &SamplerParams,
) -> Result<()> {
self.mtp_actor(binding)?.set_draft_sampling(params);
Ok(())
}
/// `mtp.set_draft_history(consumed, n, next)` before the next draft.
pub(in crate::qwen_forward) fn set_mtp_draft_history(
&mut self,
binding: &ModelBinding,
tail: &[i32],
next: i32,
) -> Result<()> {
self.mtp_actor(binding)?.set_draft_history(tail, next).map_err(driver_error)
}
}
@@ -1,409 +1,23 @@
//! Moved out of the parent module by STRA-338: impl OriginalFirstDraftEngine_for_OriginalServeEngine, impl OriginalServeSettings, fn serve_request, fn tr_port, impl OriginalServePort_for_TracePort.
//! Moved out of the parent module by STRA-338.
#[allow(unused_imports)]
use super::*;
/// Seed receipt for the CLI `draft_first` path; same one-shot caching.
impl<P: OriginalServePort> OriginalFirstDraftEngine<P::Seed> for OriginalServeEngine<P> {
fn replay_first_seed_kv(&mut self, _seed: &P::Seed, t: usize, cell: i64, token: i32) -> Result<()> {
self.usable()?;
if t != self.max_t
|| cell < 0
|| token < 0
|| token as u32 >= self.vocabulary
|| self.commit_pending
|| !matches!(self.first, FirstStage::Idle)
|| !matches!(self.draft, DraftStage::Idle)
|| self.live_windows != 0
{
return Err(Error::IdentityMismatch);
}
Ok(())
}
fn full_first_seed(&mut self, seed: &P::Seed, cell: i64, token: i32, coupled: bool) -> Result<DraftPick> {
self.usable()?;
if !matches!(self.first, FirstStage::Idle) {
return Err(Error::IdentityMismatch);
}
let completion = self.port.draft_first(seed, self.max_t, cell, token, self.max_drafts, self.min_p, coupled)?;
completion.validate(self.vocabulary, self.max_drafts.max(1), cell, 0)?;
let pick = self.cached_pick(&completion, 0);
self.first = FirstStage::Seeded { completion, next: 1, cell };
Ok(pick)
}
fn first_chain_step(&mut self, cell: i64, j: usize, previous_token: i32, _coupled: bool) -> Result<DraftPick> {
self.usable()?;
let FirstStage::Seeded { completion, next, cell: first } = &self.first else {
return Err(Error::IdentityMismatch);
};
if j != *next
|| j >= completion.ids.len()
|| cell != first.checked_add(j as i64).ok_or(Error::Overflow)?
|| previous_token != completion.ids[j - 1]
{
return Err(Error::IdentityMismatch);
}
let pick = self.cached_pick(completion, j);
if let FirstStage::Seeded { next, .. } = &mut self.first {
*next += 1;
}
Ok(pick)
}
fn drain_first_seed(&mut self) -> Result<()> {
let drained = self.port.drain_first();
self.first = FirstStage::Idle;
if drained.is_err() {
self.poisoned = true;
}
drained
}
}
impl OriginalServeSettings {
pub(crate) fn mode17(max_context: i64, vocabulary: u32, coupled: bool) -> Self {
const SPEC: usize = 4;
const SUFFIX: usize = 3;
Self {
max_t: (SPEC + 2).min(MAX_T),
mtp_max_t: SPEC,
max_context,
vocabulary,
suffix_min_match: SUFFIX,
coupled,
adaptive: None,
nan_guard: NanGuard::off(),
request_min_p: None,
}
}
/// Mode17 with the operator's overrides from the environment (read once per stack):
/// `LELEKA_SPEC` (the Original's `--spec`: MTP window, verify windows up to `spec + 2`, at most 8),
/// `LELEKA_SPEC_MTP_MAX_T` (`--mtp-max-t`, 0 = spec), `LELEKA_SPEC_SUFFIX` (`--suffix-draft`, 0 = off), and
/// `LELEKA_SPEC_ADAPTIVE=on` (adaptive window; widest window `LELEKA_SPEC_ADAPTIVE_MAX_T`, default 8 rows, MTP chain up
/// to `max_t - 1` drafts). Unset = mode17 exactly.
pub(crate) fn from_environment(max_context: i64, vocabulary: u32, coupled: bool, env: &impl EnvSource) -> Self {
let num = |name: &str| env.get(name).and_then(|v| v.trim().parse::<usize>().ok());
let mut s = Self::mode17(max_context, vocabulary, coupled);
s.nan_guard = NanGuard::from_environment(env);
if let Some(spec) = num("LELEKA_SPEC") {
let spec = spec.clamp(2, MAX_T);
s.max_t = (spec + 2).min(MAX_T);
s.mtp_max_t = spec;
}
if let Some(m) = num("LELEKA_SPEC_MTP_MAX_T") {
s.mtp_max_t = if m == 0 { s.max_t.min(s.mtp_max_t) } else { m.min(s.max_t) };
}
if let Some(n) = num("LELEKA_SPEC_SUFFIX") {
s.suffix_min_match = n;
}
let explicit = env.get("LELEKA_SPEC_ADAPTIVE");
if Self::adaptive_wanted(explicit.as_deref(), env.is_set("LELEKA_SPEC")) {
let max_t = num("LELEKA_SPEC_ADAPTIVE_MAX_T").unwrap_or(MAX_T).clamp(2, MAX_T);
s.max_t = max_t;
s.mtp_max_t = max_t;
s.adaptive = Some(super::super::original_spec_adaptive_env::from_environment(
AdaptiveConfig::new(max_t, max_t - 1),
env,
));
}
s
}
/// Adaptive window or the fixed mode17 window: an explicit `LELEKA_SPEC_ADAPTIVE` (`on`/`1`/`yes` or `off`/`0`/`no`) decides; otherwise
/// a fixed `LELEKA_SPEC=N` means the fixed window and nothing set means [`ADAPTIVE_DEFAULT`].
pub(crate) fn adaptive_wanted(explicit: Option<&str>, fixed_spec_set: bool) -> bool {
match explicit {
Some("on" | "1" | "yes") => true,
Some("off" | "0" | "no") => false,
_ => !fixed_spec_set && ADAPTIVE_DEFAULT,
}
}
/// `LELEKA_SPEC_ARMS=fixed3,fixed4,fixed6,adaptive`: named window policies one process can switch between per request (an
/// A/B inside one model load, same tier and caches). `fixedN` is the Original's `--spec N` (suffix 3), `adaptive` the
/// adaptive window; the verifier is built for the widest arm. Empty when unset.
pub(crate) fn arms_from_environment(
max_context: i64,
vocabulary: u32,
coupled: bool,
env: &impl EnvSource,
) -> Vec<(String, Self)> {
let Some(list) = env.get("LELEKA_SPEC_ARMS") else { return Vec::new() };
let base = Self::from_environment(max_context, vocabulary, coupled, env);
let mut arms = Vec::new();
for entry in list.split(',').map(str::trim).filter(|l| !l.is_empty()) {
if let Some(arm) = base.arm(entry, env) {
arms.push((entry.to_owned(), arm));
}
}
arms
}
/// One `LELEKA_SPEC_ARMS` entry; `None` drops the arm (unknown label or option).
fn arm(self, entry: &str, env: &impl EnvSource) -> Option<Self> {
// `name@MIN_P` pins the arm's request floor; `+flag` suffixes (`adaptive@0+tail7`) are the replay
// harness's, the label keeps them
let main = entry.split_once('+').map_or(entry, |(m, _)| m);
// `~key=value` suffixes set constants of the adaptive policy for this arm alone
// (`adaptive@0~step=0.3~explore=0`, `AdaptiveConfig::set_option`); an unknown key drops the arm
let mut options = main.split('~');
let main = options.next().unwrap_or(main);
let (label, min_p) = match main.split_once('@') {
Some((l, p)) => (l, p.parse::<f32>().ok()),
None => (main, None),
};
let mut s = self;
s.adaptive = None;
s.request_min_p = min_p;
s.apply_arm(label, options, env).then_some(s)
}
fn apply_arm(&mut self, label: &str, mut options: std::str::Split<'_, char>, env: &impl EnvSource) -> bool {
if let Some(n) = label.strip_prefix("fixed").and_then(|n| n.parse::<usize>().ok()) {
let n = n.clamp(2, MAX_T);
self.max_t = (n + 2).min(MAX_T);
self.mtp_max_t = n;
self.suffix_min_match = 3;
true
} else if label == "adaptive" {
self.max_t = MAX_T;
self.mtp_max_t = MAX_T;
self.suffix_min_match = 3;
let mut cfg =
super::super::original_spec_adaptive_env::from_environment(AdaptiveConfig::new(MAX_T, MAX_T - 1), env);
if !options.all(|o| o.split_once('=').is_some_and(|(k, v)| cfg.set_option(k, v))) {
return false;
}
self.adaptive = Some(cfg);
true
} else {
false
}
}
/// The same policy for a verifier that records windows only up to `cap` rows (a window graph did not fit in device memory): the
/// widest window, the MTP chain and the adaptive policy's bounds are cut to it, everything else is unchanged.
pub(crate) fn with_window_cap(mut self, cap: usize) -> Self {
let cap = cap.clamp(1, MAX_T);
self.max_t = self.max_t.min(cap);
self.mtp_max_t = self.mtp_max_t.min(self.max_t);
if let Some(a) = self.adaptive.as_mut() {
a.max_t = a.max_t.min(self.max_t);
a.max_drafts = a.max_drafts.min(a.max_t.saturating_sub(1));
}
self
}
/// Draft cap the engine shares with the controller's `DraftPreparation`.
pub(crate) fn max_drafts(&self) -> usize {
self.mtp_max_t.min(self.max_t).saturating_sub(1)
}
/// The width the MTP drafter is LOADED with: generate.cpp rewrites `o.spec` to the verify width (`min(spec+2, 8)`, line 1537)
/// before `mtp.load(..., o.spec, ...)` (line 2610), so the drafter accepts every window the verifier runs (suffix drafts go up to
/// `max_t`) while its own chain stays capped by `max_drafts()` (`set_max_drafts(S_mtp - 1)`). Loading it at `mtp_max_t` made every
/// window wider than that fail `draft` (`T > max_t_`) with InvalidQwenShape.
pub(crate) fn mtp_load_t(&self) -> usize {
self.max_t
}
/// The one production call of `OriginalSpecController::new`.
pub(crate) fn controller(&self) -> Result<OriginalSpecController> {
OriginalSpecController::new(
SpecConfig::new(
self.max_t,
self.mtp_max_t,
self.max_context,
self.vocabulary,
self.suffix_min_match,
self.coupled,
)?
.with_adaptive(self.adaptive)
.with_nan_guard(self.nan_guard),
)
}
}
/// The produced-token and round counters of one served request, and why it stopped if a round decided that.
struct RoundTally {
produced: usize,
rounds: usize,
stop: Option<ServeStop>,
}
/// generate.cpp's serve loop for one request: begin, then verify/commit, emit the committed
/// tokens, finish the round (draft + adaptive join + drain), repeat; `finish_request` waits the
/// last commit before anything reads the session. `emit` runs only AFTER the commit succeeded.
pub(crate) fn serve_request<E: OriginalSpecEngine>(
controller: &mut OriginalSpecController,
engine: &mut E,
prompt: &[i32],
max_new: usize,
min_p: f32,
eos: &[i32],
mut emit: impl FnMut(&[i32]) -> Result<()>,
mut cancel: impl FnMut() -> bool,
mut clock_ms: impl FnMut() -> f64,
) -> std::result::Result<ServeOutcome, SpecError> {
let begin_span = super::super::original_serve_profile::span("ctrl.begin_request");
controller.begin_request(prompt, max_new, min_p, eos)?;
drop(begin_span);
let mut tally = RoundTally { produced: 0, rounds: 0, stop: None };
let looped = serve_rounds(controller, engine, &mut tally, (&mut emit, &mut cancel, &mut clock_ms));
if let Err(e) = looped {
// Close the request best-effort (waits the last commit) so the controller is reusable
// unless a restore/finish failure already marked it failed.
let _ = controller.finish_request(engine);
return Err(e);
}
controller.finish_request(engine)?;
let RoundTally { produced, rounds, stop } = tally;
let stop = stop.unwrap_or(if produced >= max_new { ServeStop::Length } else { ServeStop::Context });
Ok(ServeOutcome { stop, produced, rounds })
}
fn serve_rounds<E: OriginalSpecEngine>(
controller: &mut OriginalSpecController,
engine: &mut E,
tally: &mut RoundTally,
(emit, cancel, clock_ms): (
&mut impl FnMut(&[i32]) -> Result<()>,
&mut impl FnMut() -> bool,
&mut impl FnMut() -> f64,
),
) -> std::result::Result<(), SpecError> {
while !controller.finished() {
if !serve_round(controller, engine, tally, (&mut *emit, &mut *cancel, &mut *clock_ms))? {
break;
}
}
Ok(())
}
/// One verify/commit/emit/finish round; `false` when the controller had no round to run.
fn serve_round<E: OriginalSpecEngine>(
controller: &mut OriginalSpecController,
engine: &mut E,
tally: &mut RoundTally,
(emit, cancel, clock_ms): (
&mut impl FnMut(&[i32]) -> Result<()>,
&mut impl FnMut() -> bool,
&mut impl FnMut() -> f64,
),
) -> std::result::Result<bool, SpecError> {
let started = clock_ms();
let vc_span = super::super::original_serve_profile::span("round.verify_commit");
let Some(round) = controller.verify_commit(engine, &mut *cancel)? else { return Ok(false) };
drop(vc_span);
let emit_span = super::super::original_serve_profile::span("round.emit");
let emitted = emit(round.tokens());
drop(emit_span);
tally.produced += round.tokens().len();
tally.rounds += 1;
if round.stopped_on_eos() {
tally.stop = Some(ServeStop::Eos);
}
// A failed emit still finishes the round (drain + join) before reporting.
let fr_span = super::super::original_serve_profile::span("round.finish");
let finished = controller.finish_round(engine, round, || clock_ms() - started, &mut *cancel);
drop(fr_span);
emitted?;
finished?;
Ok(true)
}
pub(super) fn tr_port<T>(name: &str, f: impl FnOnce() -> Result<T>) -> Result<T> {
let started = std::time::Instant::now();
let r = f();
if crate::bringup_trace_enabled() {
let state = match &r {
Ok(_) => "ok".to_string(),
Err(e) => format!("ERR {e:?}"),
};
eprintln!(
"DBG[{:.0}s] port.{name} {:.3}ms -> {state}",
crate::qwen_forward::original_serve_stack::dbg_el(),
started.elapsed().as_secs_f64() * 1e3
);
}
r
}
impl<P: OriginalServePort> OriginalServePort for TracePort<P> {
type Window = P::Window;
type Seed = P::Seed;
type TargetCheckpoint = P::TargetCheckpoint;
type DraftCheckpoint = P::DraftCheckpoint;
type Adaptive = P::Adaptive;
fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()> {
tr_port("validate_current", || self.0.validate_current(consumed, input, position))
}
fn checkpoint_target(&self) -> Result<Self::TargetCheckpoint> {
tr_port("checkpoint_target", || self.0.checkpoint_target())
}
fn checkpoint_draft(&self) -> Result<Self::DraftCheckpoint> {
tr_port("checkpoint_draft", || self.0.checkpoint_draft())
}
fn restore_target(&mut self, c: &Self::TargetCheckpoint) -> Result<()> {
tr_port("restore_target", || self.0.restore_target(c))
}
fn restore_draft(&mut self, c: &Self::DraftCheckpoint) -> Result<()> {
tr_port("restore_draft", || self.0.restore_draft(c))
}
fn apply_pending(&mut self) -> Result<()> {
tr_port("apply_pending", || self.0.apply_pending())
}
fn run_window(&mut self, position: i64, inputs: &[i32], consumed: &[i32]) -> Result<Self::Window> {
crate::bringup_trace!(
"DBG port.run_window position={position} inputs={inputs:?} consumed_len={}",
consumed.len()
);
tr_port("run_window", || self.0.run_window(position, inputs, consumed))
}
fn validate_window(&self, window: &Self::Window, position: i64, inputs: &[i32]) -> Result<()> {
tr_port("validate_window", || self.0.validate_window(window, position, inputs))
}
fn window_outputs<'a>(&self, window: &'a Self::Window) -> &'a [i32] {
self.0.window_outputs(window)
}
fn commit_window(&mut self, window: &mut Self::Window, keep: usize) -> Result<()> {
tr_port("commit_window", || self.0.commit_window(window, keep))
}
fn wait_commit(&mut self) -> Result<()> {
tr_port("wait_commit", || self.0.wait_commit())
}
fn drain_window(&mut self, window: Self::Window) -> Result<()> {
tr_port("drain_window", || self.0.drain_window(window))
}
fn discard_window(&mut self) -> Result<()> {
tr_port("discard_window", || self.0.discard_window())
}
fn begin_adaptation(&mut self, next_round: u64) -> Result<Self::Adaptive> {
tr_port("begin_adaptation", || self.0.begin_adaptation(next_round))
}
fn join_adaptation(&mut self, work: Self::Adaptive) -> Result<()> {
tr_port("join_adaptation", || self.0.join_adaptation(work))
}
fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()> {
tr_port("stage_draft_history", || self.0.stage_draft_history(consumed, next))
}
#[allow(clippy::too_many_arguments)]
fn draft_committed(
&mut self,
window: &Self::Window,
position: i64,
accepted_row: usize,
outputs: &[i32],
max_drafts: usize,
min_p: f32,
coupled: bool,
) -> Result<DraftCompletion> {
tr_port("draft_committed", || {
self.0.draft_committed(window, position, accepted_row, outputs, max_drafts, min_p, coupled)
})
}
fn drain_draft(&mut self) -> Result<()> {
tr_port("drain_draft", || self.0.drain_draft())
}
#[allow(clippy::too_many_arguments)]
fn draft_first(
&mut self,
seed: &Self::Seed,
t: usize,
cell: i64,
token: i32,
max_drafts: usize,
min_p: f32,
coupled: bool,
) -> Result<DraftCompletion> {
tr_port("draft_first", || self.0.draft_first(seed, t, cell, token, max_drafts, min_p, coupled))
}
fn drain_first(&mut self) -> Result<()> {
tr_port("drain_first", || self.0.drain_first())
}
}
mod impl_originalfirstdraftengine_for_originalservee_2;
mod impl_originalservesettings;
#[allow(unused_imports)]
pub(crate) use impl_originalservesettings::serve_request;
mod serve_rounds_fn;
#[allow(unused_imports)]
use serve_rounds_fn::serve_round;
#[allow(unused_imports)]
use serve_rounds_fn::serve_rounds;
#[allow(unused_imports)]
pub(super) use serve_rounds_fn::tr_port;
@@ -0,0 +1,60 @@
//! Moved out of the parent module by STRA-338: impl OriginalFirstDraftEngine_for_OriginalServeEngine.
#[allow(unused_imports)]
use super::*;
/// Seed receipt for the CLI `draft_first` path; same one-shot caching.
impl<P: OriginalServePort> OriginalFirstDraftEngine<P::Seed> for OriginalServeEngine<P> {
fn replay_first_seed_kv(&mut self, _seed: &P::Seed, t: usize, cell: i64, token: i32) -> Result<()> {
self.usable()?;
if t != self.max_t
|| cell < 0
|| token < 0
|| token as u32 >= self.vocabulary
|| self.commit_pending
|| !matches!(self.first, FirstStage::Idle)
|| !matches!(self.draft, DraftStage::Idle)
|| self.live_windows != 0
{
return Err(Error::IdentityMismatch);
}
Ok(())
}
fn full_first_seed(&mut self, seed: &P::Seed, cell: i64, token: i32, coupled: bool) -> Result<DraftPick> {
self.usable()?;
if !matches!(self.first, FirstStage::Idle) {
return Err(Error::IdentityMismatch);
}
let completion = self.port.draft_first(seed, self.max_t, cell, token, self.max_drafts, self.min_p, coupled)?;
completion.validate(self.vocabulary, self.max_drafts.max(1), cell, 0)?;
let pick = self.cached_pick(&completion, 0);
self.first = FirstStage::Seeded { completion, next: 1, cell };
Ok(pick)
}
fn first_chain_step(&mut self, cell: i64, j: usize, previous_token: i32, _coupled: bool) -> Result<DraftPick> {
self.usable()?;
let FirstStage::Seeded { completion, next, cell: first } = &self.first else {
return Err(Error::IdentityMismatch);
};
if j != *next
|| j >= completion.ids.len()
|| cell != first.checked_add(j as i64).ok_or(Error::Overflow)?
|| previous_token != completion.ids[j - 1]
{
return Err(Error::IdentityMismatch);
}
let pick = self.cached_pick(completion, j);
if let FirstStage::Seeded { next, .. } = &mut self.first {
*next += 1;
}
Ok(pick)
}
fn drain_first_seed(&mut self) -> Result<()> {
let drained = self.port.drain_first();
self.first = FirstStage::Idle;
if drained.is_err() {
self.poisoned = true;
}
drained
}
}
@@ -0,0 +1,197 @@
//! Moved out of the parent module by STRA-338: impl OriginalServeSettings, fn serve_request.
#[allow(unused_imports)]
use super::*;
impl OriginalServeSettings {
pub(crate) fn mode17(max_context: i64, vocabulary: u32, coupled: bool) -> Self {
const SPEC: usize = 4;
const SUFFIX: usize = 3;
Self {
max_t: (SPEC + 2).min(MAX_T),
mtp_max_t: SPEC,
max_context,
vocabulary,
suffix_min_match: SUFFIX,
coupled,
adaptive: None,
nan_guard: NanGuard::off(),
request_min_p: None,
}
}
/// Mode17 with the operator's overrides from the environment (read once per stack):
/// `LELEKA_SPEC` (the Original's `--spec`: MTP window, verify windows up to `spec + 2`, at most 8),
/// `LELEKA_SPEC_MTP_MAX_T` (`--mtp-max-t`, 0 = spec), `LELEKA_SPEC_SUFFIX` (`--suffix-draft`, 0 = off), and
/// `LELEKA_SPEC_ADAPTIVE=on` (adaptive window; widest window `LELEKA_SPEC_ADAPTIVE_MAX_T`, default 8 rows, MTP chain up
/// to `max_t - 1` drafts). Unset = mode17 exactly.
pub(crate) fn from_environment(max_context: i64, vocabulary: u32, coupled: bool, env: &impl EnvSource) -> Self {
let num = |name: &str| env.get(name).and_then(|v| v.trim().parse::<usize>().ok());
let mut s = Self::mode17(max_context, vocabulary, coupled);
s.nan_guard = NanGuard::from_environment(env);
if let Some(spec) = num("LELEKA_SPEC") {
let spec = spec.clamp(2, MAX_T);
s.max_t = (spec + 2).min(MAX_T);
s.mtp_max_t = spec;
}
if let Some(m) = num("LELEKA_SPEC_MTP_MAX_T") {
s.mtp_max_t = if m == 0 { s.max_t.min(s.mtp_max_t) } else { m.min(s.max_t) };
}
if let Some(n) = num("LELEKA_SPEC_SUFFIX") {
s.suffix_min_match = n;
}
let explicit = env.get("LELEKA_SPEC_ADAPTIVE");
if Self::adaptive_wanted(explicit.as_deref(), env.is_set("LELEKA_SPEC")) {
let max_t = num("LELEKA_SPEC_ADAPTIVE_MAX_T").unwrap_or(MAX_T).clamp(2, MAX_T);
s.max_t = max_t;
s.mtp_max_t = max_t;
s.adaptive = Some(super::super::super::original_spec_adaptive_env::from_environment(
AdaptiveConfig::new(max_t, max_t - 1),
env,
));
}
s
}
/// Adaptive window or the fixed mode17 window: an explicit `LELEKA_SPEC_ADAPTIVE` (`on`/`1`/`yes` or `off`/`0`/`no`) decides; otherwise
/// a fixed `LELEKA_SPEC=N` means the fixed window and nothing set means [`ADAPTIVE_DEFAULT`].
pub(crate) fn adaptive_wanted(explicit: Option<&str>, fixed_spec_set: bool) -> bool {
match explicit {
Some("on" | "1" | "yes") => true,
Some("off" | "0" | "no") => false,
_ => !fixed_spec_set && ADAPTIVE_DEFAULT,
}
}
/// `LELEKA_SPEC_ARMS=fixed3,fixed4,fixed6,adaptive`: named window policies one process can switch between per request (an
/// A/B inside one model load, same tier and caches). `fixedN` is the Original's `--spec N` (suffix 3), `adaptive` the
/// adaptive window; the verifier is built for the widest arm. Empty when unset.
pub(crate) fn arms_from_environment(
max_context: i64,
vocabulary: u32,
coupled: bool,
env: &impl EnvSource,
) -> Vec<(String, Self)> {
let Some(list) = env.get("LELEKA_SPEC_ARMS") else { return Vec::new() };
let base = Self::from_environment(max_context, vocabulary, coupled, env);
let mut arms = Vec::new();
for entry in list.split(',').map(str::trim).filter(|l| !l.is_empty()) {
if let Some(arm) = base.arm(entry, env) {
arms.push((entry.to_owned(), arm));
}
}
arms
}
/// One `LELEKA_SPEC_ARMS` entry; `None` drops the arm (unknown label or option).
pub(super) fn arm(self, entry: &str, env: &impl EnvSource) -> Option<Self> {
// `name@MIN_P` pins the arm's request floor; `+flag` suffixes (`adaptive@0+tail7`) are the replay
// harness's, the label keeps them
let main = entry.split_once('+').map_or(entry, |(m, _)| m);
// `~key=value` suffixes set constants of the adaptive policy for this arm alone
// (`adaptive@0~step=0.3~explore=0`, `AdaptiveConfig::set_option`); an unknown key drops the arm
let mut options = main.split('~');
let main = options.next().unwrap_or(main);
let (label, min_p) = match main.split_once('@') {
Some((l, p)) => (l, p.parse::<f32>().ok()),
None => (main, None),
};
let mut s = self;
s.adaptive = None;
s.request_min_p = min_p;
s.apply_arm(label, options, env).then_some(s)
}
pub(super) fn apply_arm(
&mut self,
label: &str,
mut options: std::str::Split<'_, char>,
env: &impl EnvSource,
) -> bool {
if let Some(n) = label.strip_prefix("fixed").and_then(|n| n.parse::<usize>().ok()) {
let n = n.clamp(2, MAX_T);
self.max_t = (n + 2).min(MAX_T);
self.mtp_max_t = n;
self.suffix_min_match = 3;
true
} else if label == "adaptive" {
self.max_t = MAX_T;
self.mtp_max_t = MAX_T;
self.suffix_min_match = 3;
let mut cfg = super::super::super::original_spec_adaptive_env::from_environment(
AdaptiveConfig::new(MAX_T, MAX_T - 1),
env,
);
if !options.all(|o| o.split_once('=').is_some_and(|(k, v)| cfg.set_option(k, v))) {
return false;
}
self.adaptive = Some(cfg);
true
} else {
false
}
}
/// The same policy for a verifier that records windows only up to `cap` rows (a window graph did not fit in device memory): the
/// widest window, the MTP chain and the adaptive policy's bounds are cut to it, everything else is unchanged.
pub(crate) fn with_window_cap(mut self, cap: usize) -> Self {
let cap = cap.clamp(1, MAX_T);
self.max_t = self.max_t.min(cap);
self.mtp_max_t = self.mtp_max_t.min(self.max_t);
if let Some(a) = self.adaptive.as_mut() {
a.max_t = a.max_t.min(self.max_t);
a.max_drafts = a.max_drafts.min(a.max_t.saturating_sub(1));
}
self
}
/// Draft cap the engine shares with the controller's `DraftPreparation`.
pub(crate) fn max_drafts(&self) -> usize {
self.mtp_max_t.min(self.max_t).saturating_sub(1)
}
/// The width the MTP drafter is LOADED with: generate.cpp rewrites `o.spec` to the verify width (`min(spec+2, 8)`, line 1537)
/// before `mtp.load(..., o.spec, ...)` (line 2610), so the drafter accepts every window the verifier runs (suffix drafts go up to
/// `max_t`) while its own chain stays capped by `max_drafts()` (`set_max_drafts(S_mtp - 1)`). Loading it at `mtp_max_t` made every
/// window wider than that fail `draft` (`T > max_t_`) with InvalidQwenShape.
pub(crate) fn mtp_load_t(&self) -> usize {
self.max_t
}
/// The one production call of `OriginalSpecController::new`.
pub(crate) fn controller(&self) -> Result<OriginalSpecController> {
OriginalSpecController::new(
SpecConfig::new(
self.max_t,
self.mtp_max_t,
self.max_context,
self.vocabulary,
self.suffix_min_match,
self.coupled,
)?
.with_adaptive(self.adaptive)
.with_nan_guard(self.nan_guard),
)
}
}
/// generate.cpp's serve loop for one request: begin, then verify/commit, emit the committed
/// tokens, finish the round (draft + adaptive join + drain), repeat; `finish_request` waits the
/// last commit before anything reads the session. `emit` runs only AFTER the commit succeeded.
pub(crate) fn serve_request<E: OriginalSpecEngine>(
controller: &mut OriginalSpecController,
engine: &mut E,
prompt: &[i32],
max_new: usize,
min_p: f32,
eos: &[i32],
mut emit: impl FnMut(&[i32]) -> Result<()>,
mut cancel: impl FnMut() -> bool,
mut clock_ms: impl FnMut() -> f64,
) -> std::result::Result<ServeOutcome, SpecError> {
let begin_span = super::super::super::original_serve_profile::span("ctrl.begin_request");
controller.begin_request(prompt, max_new, min_p, eos)?;
drop(begin_span);
let mut tally = RoundTally { produced: 0, rounds: 0, stop: None };
let looped = serve_rounds(controller, engine, &mut tally, (&mut emit, &mut cancel, &mut clock_ms));
if let Err(e) = looped {
// Close the request best-effort (waits the last commit) so the controller is reusable
// unless a restore/finish failure already marked it failed.
let _ = controller.finish_request(engine);
return Err(e);
}
controller.finish_request(engine)?;
let RoundTally { produced, rounds, stop } = tally;
let stop = stop.unwrap_or(if produced >= max_new { ServeStop::Length } else { ServeStop::Context });
Ok(ServeOutcome { stop, produced, rounds })
}
@@ -0,0 +1,162 @@
//! Moved out of the parent module by STRA-338.
#[allow(unused_imports)]
use super::*;
pub(super) fn serve_rounds<E: OriginalSpecEngine>(
controller: &mut OriginalSpecController,
engine: &mut E,
tally: &mut RoundTally,
(emit, cancel, clock_ms): (
&mut impl FnMut(&[i32]) -> Result<()>,
&mut impl FnMut() -> bool,
&mut impl FnMut() -> f64,
),
) -> std::result::Result<(), SpecError> {
while !controller.finished() {
if !serve_round(controller, engine, tally, (&mut *emit, &mut *cancel, &mut *clock_ms))? {
break;
}
}
Ok(())
}
/// One verify/commit/emit/finish round; `false` when the controller had no round to run.
pub(super) fn serve_round<E: OriginalSpecEngine>(
controller: &mut OriginalSpecController,
engine: &mut E,
tally: &mut RoundTally,
(emit, cancel, clock_ms): (
&mut impl FnMut(&[i32]) -> Result<()>,
&mut impl FnMut() -> bool,
&mut impl FnMut() -> f64,
),
) -> std::result::Result<bool, SpecError> {
let started = clock_ms();
let vc_span = super::super::super::original_serve_profile::span("round.verify_commit");
let Some(round) = controller.verify_commit(engine, &mut *cancel)? else { return Ok(false) };
drop(vc_span);
let emit_span = super::super::super::original_serve_profile::span("round.emit");
let emitted = emit(round.tokens());
drop(emit_span);
tally.produced += round.tokens().len();
tally.rounds += 1;
if round.stopped_on_eos() {
tally.stop = Some(ServeStop::Eos);
}
// A failed emit still finishes the round (drain + join) before reporting.
let fr_span = super::super::super::original_serve_profile::span("round.finish");
let finished = controller.finish_round(engine, round, || clock_ms() - started, &mut *cancel);
drop(fr_span);
emitted?;
finished?;
Ok(true)
}
pub(in super::super) fn tr_port<T>(name: &str, f: impl FnOnce() -> Result<T>) -> Result<T> {
let started = std::time::Instant::now();
let r = f();
if crate::bringup_trace_enabled() {
let state = match &r {
Ok(_) => "ok".to_string(),
Err(e) => format!("ERR {e:?}"),
};
eprintln!(
"DBG[{:.0}s] port.{name} {:.3}ms -> {state}",
crate::qwen_forward::original_serve_stack::dbg_el(),
started.elapsed().as_secs_f64() * 1e3
);
}
r
}
impl<P: OriginalServePort> OriginalServePort for TracePort<P> {
type Window = P::Window;
type Seed = P::Seed;
type TargetCheckpoint = P::TargetCheckpoint;
type DraftCheckpoint = P::DraftCheckpoint;
type Adaptive = P::Adaptive;
fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()> {
tr_port("validate_current", || self.0.validate_current(consumed, input, position))
}
fn checkpoint_target(&self) -> Result<Self::TargetCheckpoint> {
tr_port("checkpoint_target", || self.0.checkpoint_target())
}
fn checkpoint_draft(&self) -> Result<Self::DraftCheckpoint> {
tr_port("checkpoint_draft", || self.0.checkpoint_draft())
}
fn restore_target(&mut self, c: &Self::TargetCheckpoint) -> Result<()> {
tr_port("restore_target", || self.0.restore_target(c))
}
fn restore_draft(&mut self, c: &Self::DraftCheckpoint) -> Result<()> {
tr_port("restore_draft", || self.0.restore_draft(c))
}
fn apply_pending(&mut self) -> Result<()> {
tr_port("apply_pending", || self.0.apply_pending())
}
fn run_window(&mut self, position: i64, inputs: &[i32], consumed: &[i32]) -> Result<Self::Window> {
crate::bringup_trace!(
"DBG port.run_window position={position} inputs={inputs:?} consumed_len={}",
consumed.len()
);
tr_port("run_window", || self.0.run_window(position, inputs, consumed))
}
fn validate_window(&self, window: &Self::Window, position: i64, inputs: &[i32]) -> Result<()> {
tr_port("validate_window", || self.0.validate_window(window, position, inputs))
}
fn window_outputs<'a>(&self, window: &'a Self::Window) -> &'a [i32] {
self.0.window_outputs(window)
}
fn commit_window(&mut self, window: &mut Self::Window, keep: usize) -> Result<()> {
tr_port("commit_window", || self.0.commit_window(window, keep))
}
fn wait_commit(&mut self) -> Result<()> {
tr_port("wait_commit", || self.0.wait_commit())
}
fn drain_window(&mut self, window: Self::Window) -> Result<()> {
tr_port("drain_window", || self.0.drain_window(window))
}
fn discard_window(&mut self) -> Result<()> {
tr_port("discard_window", || self.0.discard_window())
}
fn begin_adaptation(&mut self, next_round: u64) -> Result<Self::Adaptive> {
tr_port("begin_adaptation", || self.0.begin_adaptation(next_round))
}
fn join_adaptation(&mut self, work: Self::Adaptive) -> Result<()> {
tr_port("join_adaptation", || self.0.join_adaptation(work))
}
fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()> {
tr_port("stage_draft_history", || self.0.stage_draft_history(consumed, next))
}
#[allow(clippy::too_many_arguments)]
fn draft_committed(
&mut self,
window: &Self::Window,
position: i64,
accepted_row: usize,
outputs: &[i32],
max_drafts: usize,
min_p: f32,
coupled: bool,
) -> Result<DraftCompletion> {
tr_port("draft_committed", || {
self.0.draft_committed(window, position, accepted_row, outputs, max_drafts, min_p, coupled)
})
}
fn drain_draft(&mut self) -> Result<()> {
tr_port("drain_draft", || self.0.drain_draft())
}
#[allow(clippy::too_many_arguments)]
fn draft_first(
&mut self,
seed: &Self::Seed,
t: usize,
cell: i64,
token: i32,
max_drafts: usize,
min_p: f32,
coupled: bool,
) -> Result<DraftCompletion> {
tr_port("draft_first", || self.0.draft_first(seed, t, cell, token, max_drafts, min_p, coupled))
}
fn drain_first(&mut self) -> Result<()> {
tr_port("drain_first", || self.0.drain_first())
}
}
@@ -7,9 +7,6 @@ use leleka_cuda_driver::{
QsaNativeGate,
};
use std::cell::Cell;
fn driver(e: leleka_cuda_driver::Error) -> Error {
device_error(e)
}
pub(in crate::qwen_forward) struct ResidentQsaScalar<'source, 'lease, 'index, 'weights, 'ctx> {
binding: BindingIdentity,
context: &'ctx Context<'ctx>,
@@ -44,398 +41,32 @@ struct ScalarHost {
iq: Box<[f32]>,
gate: Box<[f32]>,
}
impl ScalarHost {
fn gather(
context: &Context<'_>,
binding: &ModelBinding,
cache: &DenseWeightCache<'_>,
entry: &QsaResident,
input: &ResidualReady,
) -> Result<Self> {
let at = |role| project(context, binding, &entry.weights, role, input.mixed(), Some(cache));
let raw = at(QsaMatrixRole::IndexK)?;
let k = at(QsaMatrixRole::K)?;
let v = at(QsaMatrixRole::V)?;
let qfull = at(QsaMatrixRole::Q)?;
let iq = at(QsaMatrixRole::IndexQ)?;
for (values, n) in [(&raw, 128), (&k, 512), (&v, 512), (&qfull, 12288), (&iq, 512)] {
validate_values(values, n)?;
}
let gate = scalar_gate(&qfull)?;
Ok(Self { raw, k, v, qfull, iq, gate })
}
fn select<'lease, 'index, 'weights, 'ctx>(
&self,
owner: &'lease mut OriginalQsaResidentScalarIndex<'ctx>,
(resident, prior): (&'index mut OriginalQsaResidentIndex<'ctx>, &OriginalQsaIndexCheckpoint<'ctx>),
norms: [&'weights DeviceBuffer<'ctx>; 4],
workspace: &mut NativeBatchWorkspace<'ctx>,
) -> Result<OriginalQsaResidentScalarSelection<'lease, 'index, 'weights, 'ctx>> {
owner
.prepare(resident, prior, &self.raw, &self.k, &self.v, &self.qfull, &self.iq, norms, workspace)
.map_err(driver)
}
}
fn scalar_gate(qfull: &[f32]) -> Result<Box<[f32]>> {
let mut gate = Vec::new();
gate.try_reserve_exact(6144).map_err(|_| Error::InputAllocation)?;
for head in 0..24 {
gate.extend_from_slice(&qfull[head * 512 + 256..head * 512 + 512]);
}
validate_values(&gate, 6144)?;
Ok(gate.into_boxed_slice())
}
fn check_txn_input(txn: &QwenStepTxn<'_, '_>, binding: &ModelBinding, input: &ResidualReady) -> Result<()> {
txn.validate_binding(&binding.identity())?;
txn.validate_input(input.identity().token(), input.identity().position())
}
fn check_scalar_txn(
txn: &QwenStepTxn<'_, '_>,
binding: &ModelBinding,
input: &ResidualReady,
layer: LayerId,
prior: &ResidentQsaPrior<'_>,
) -> Result<()> {
check_txn_input(txn, binding, input)?;
input.identity().validate(txn.token(), txn.position(), layer)?;
input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?;
txn.validate_projection_branch(&prior.0.origin)
}
fn check_scalar_shapes(entry: &QsaResident) -> Result<()> {
for (role, width) in [
(QsaMatrixRole::IndexK, 128),
(QsaMatrixRole::K, 512),
(QsaMatrixRole::V, 512),
(QsaMatrixRole::Q, 12288),
(QsaMatrixRole::IndexQ, 512),
] {
if entry.weights.shape(role) != (2560, width) {
return Err(Error::InvalidDimension);
}
}
Ok(())
}
impl<'ctx> ResidentQsaLayer<'ctx> {
/// The guards of `prepare_scalar` before any projection: the step, the lineage, the weights and the input.
fn scalar_guards<'w>(
&self,
binding: &ModelBinding,
cache: &'w DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
layer: LayerId,
input: &ResidualReady,
prior: &ResidentQsaPrior<'ctx>,
) -> Result<(&'ctx Context<'ctx>, &'w QsaResident, Rc<()>)> {
check_scalar_txn(txn, binding, input, layer, prior)?;
let context = cache.retained_context(binding, txn.cuda_context()?)?;
cache.validate(binding)?;
let entry = cache.qsa(binding, layer.get())?;
self.check_scalar_prior(binding, txn, layer, prior, (context, entry))?;
validate_values(input.mixed(), 2560)?;
check_scalar_shapes(entry)?;
Ok((context, entry, txn.residual_handoff_owner()?))
}
fn check_scalar_prior(
&self,
binding: &ModelBinding,
txn: &QwenStepTxn<'_, '_>,
layer: LayerId,
prior: &ResidentQsaPrior<'ctx>,
(context, entry): (&Context<'ctx>, &QsaResident),
) -> Result<()> {
if !self.current.same_prior(prior)
|| layer != prior.layer()
|| prior.next_position() != txn.position().get()
|| !prior.0.binding.matches(&binding.identity())
|| !std::ptr::eq(context, self.context)
|| !Rc::ptr_eq(&entry.weights, &prior.0.provider)
{
return Err(Error::IdentityMismatch);
}
self.index.validate_context(context).map_err(driver)?;
self.index.validate_checkpoint(&prior.0.index).map_err(driver)?;
self.kv.validate_prefix(&prior.0.kv).map_err(driver)
}
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn prepare_scalar<'source, 'lease, 'index, 'weights>(
&'index mut self,
binding: &ModelBinding,
cache: &'weights DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
layer: LayerId,
input: &'source ResidualReady,
prior: &ResidentQsaPrior<'ctx>,
owner: &'lease mut OriginalQsaResidentScalarIndex<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
) -> Result<ResidentQsaScalar<'source, 'lease, 'index, 'weights, 'ctx>> {
let (context, entry, transaction) = self.scalar_guards(binding, cache, txn, layer, input, prior)?;
let host = ScalarHost::gather(context, binding, cache, entry, input)?;
let norms = cache.qsa_norms(entry)?;
let selected = host.select(owner, (&mut self.index, &prior.0.index), norms, workspace)?;
check_txn_input(txn, binding, input)?;
cache.validate(binding)?;
Ok(ResidentQsaScalar {
binding: binding.identity(),
context,
layer,
source: input,
prior: prior.clone(),
provider: entry.weights.clone(),
transaction,
gate: host.gate,
selected,
kv: &mut self.kv,
})
}
}
impl<'source, 'lease, 'index, 'weights, 'ctx> ResidentQsaScalar<'source, 'lease, 'index, 'weights, 'ctx> {
fn validate(
&self,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
input: &ResidualReady,
) -> Result<()> {
txn.validate_binding(&binding.identity())?;
txn.validate_input(input.identity().token(), input.identity().position())?;
input.identity().validate(txn.token(), txn.position(), self.layer)?;
input.validate_origin(&binding.identity(), GrRole::Attention(self.layer.get()))?;
txn.validate_projection_branch(&self.prior.0.origin)?;
let context = cache.retained_context(binding, txn.cuda_context()?)?;
let entry = cache.qsa(binding, self.layer.get())?;
if !self.binding.matches(&binding.identity())
|| !std::ptr::eq(context, self.context)
|| !std::ptr::eq(input, self.source)
|| !Rc::ptr_eq(&self.provider, &entry.weights)
|| !Rc::ptr_eq(&self.transaction, &txn.residual_handoff_owner()?)
|| self.prior.next_position() != txn.position().get()
|| self.selected.first_position() as u64 != txn.position().get()
{
return Err(Error::IdentityMismatch);
}
validate_values(&self.gate, 6144)
}
/// The attention of the appended row over the completed buffers.
fn attend(
&mut self,
workspace: &mut NativeBatchWorkspace<'ctx>,
attention: &mut QsaNativeDecode<'ctx>,
append: &OriginalQsaMappedAppend,
) -> Result<Box<[f32]>> {
self.selected
.with_completed_buffers(|q, ids, steps| {
let inputs = QsaAttentionInputs::new(q, ids, steps, 1)?;
let actual = attention.attend_resident(workspace, self.kv, append.final_prefix(), &inputs)?;
actual.into_values()
})
.map_err(driver)
}
fn gate_out(
&self,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
attended: &[f32],
gate_owner: &mut QsaNativeGate<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
) -> Result<Box<[f32]>> {
let failed = cache.transport_failure_flag(binding, self.context)?;
let provider = self.provider.as_ref();
gate_and_out(binding, cache, self.context, provider, attended, &self.gate, gate_owner, workspace, &failed)
}
/// The device work of one scalar row: append, attend, gate and Out; the seal or the abort follows.
fn run(
&mut self,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
input: &ResidualReady,
(attention, stage, gate_owner): ScalarOwners<'_, 'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
) -> Result<(Box<[f32]>, OriginalQsaMappedAppend)> {
self.validate(binding, cache, txn, input)?;
super::super::admit_budget(self.context)?;
let append =
self.kv.append_resident_decode(workspace, stage, &self.prior.0.kv, &self.selected).map_err(driver)?;
let attended = self.attend(workspace, attention, &append)?;
validate_values(&attended, 6144)?;
let values = self.gate_out(binding, cache, &attended, gate_owner, workspace)?;
self.validate(binding, cache, txn, input)?;
validate_values(&values, 2560)?;
Ok((values, append))
}
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn complete(
mut self,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
input: &ResidualReady,
attention: &mut QsaNativeDecode<'ctx>,
stage: &mut OriginalQsaResidentTransport<'ctx>,
gate_owner: &mut QsaNativeGate<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
) -> Result<ResidentQsaScalarReady<'source, 'ctx>> {
match self.run(binding, cache, txn, input, (attention, stage, gate_owner), workspace) {
Err(primary) => {
let index = self.selected.abort(workspace).map_err(driver);
let kv = self.kv.rollback(workspace, &self.prior.0.kv).map_err(driver);
let _ = (index, kv);
Err(primary)
}
Ok((values, append)) => self.seal_ready(binding, cache, txn, workspace, (values, append)),
}
}
fn seal_ready(
self,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
workspace: &mut NativeBatchWorkspace<'ctx>,
(values, append): (Box<[f32]>, OriginalQsaMappedAppend),
) -> Result<ResidentQsaScalarReady<'source, 'ctx>> {
let Self { binding: id, context, layer, source, prior, provider, transaction, selected, kv: journal, .. } =
self;
let index = selected.seal(workspace, 1).map_err(driver);
let kv = journal.accept_prefix(workspace, &append, 1).map_err(driver);
let (index, kv) = (index?, kv?);
cache.validate(binding)?;
cache.retained_context(binding, context)?;
txn.validate_projection_branch(&prior.0.origin)?;
let (owner, origin) = (prior.0.owner.clone(), prior.0.origin.clone());
let next = mint(id.clone(), owner, origin, (layer, provider.clone()), (index, kv));
let seal = ResidentQsaSeal { context, previous: prior, next, accepted: 1 };
Ok(ResidentQsaScalarReady { binding: id, context, layer, source, provider, transaction, values, seal })
}
}
impl<'source, 'ctx> ResidentQsaScalarReady<'source, 'ctx> {
pub(in crate::qwen_forward) fn into_parts(
self,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
input: &ResidualReady,
) -> Result<(TokenLayer, Box<[f32]>, ResidentQsaSeal<'ctx>)> {
txn.validate_binding(&binding.identity())?;
txn.validate_input(input.identity().token(), input.identity().position())?;
input.identity().validate(txn.token(), txn.position(), self.layer)?;
input.validate_origin(&binding.identity(), GrRole::Attention(self.layer.get()))?;
txn.validate_projection_branch(&self.seal.next.0.origin)?;
let context = cache.retained_context(binding, txn.cuda_context()?)?;
let entry = cache.qsa(binding, self.layer.get())?;
if !self.binding.matches(&binding.identity())
|| !std::ptr::eq(context, self.context)
|| !std::ptr::eq(input, self.source)
|| !Rc::ptr_eq(&self.provider, &entry.weights)
|| !Rc::ptr_eq(&self.transaction, &txn.residual_handoff_owner()?)
{
return Err(Error::IdentityMismatch);
}
validate_values(&self.values, 2560)?;
Ok((input.identity(), self.values, self.seal))
}
}
/// The role buffers of one gate-and-Out run: attended, gate, gated, Out.
type GateBuffers<'ctx> = [Option<DeviceBuffer<'ctx>>; 4];
fn upload_gate_inputs<'ctx>(
buffers: &mut GateBuffers<'ctx>,
context: &'ctx Context<'ctx>,
(attended, gate): (&[f32], &[f32]),
failed: &Cell<bool>,
) -> Result<()> {
if failed.get() {
return Err(Error::CudaExecution);
}
validate_values(attended, 6144)?;
validate_values(gate, 6144)?;
buffers[0] = Some(upload(context, attended)?);
buffers[1] = Some(upload(context, gate)?);
buffers[2] = Some(allocate(context, 6144)?);
Ok(())
}
fn apply_gate<'ctx>(
buffers: &mut GateBuffers<'ctx>,
owner: &mut QsaNativeGate<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
) -> Result<()> {
let (inputs, outputs) = buffers.split_at_mut(2);
owner
.apply(
workspace,
inputs[0].as_ref().ok_or(Error::IdentityMismatch)?,
inputs[1].as_ref().ok_or(Error::IdentityMismatch)?,
outputs[0].as_mut().ok_or(Error::IdentityMismatch)?,
)
.map_err(driver)
}
fn project_gated_out<'ctx>(
buffers: &mut GateBuffers<'ctx>,
(binding, cache): (&ModelBinding, &DenseWeightCache<'ctx>),
context: &'ctx Context<'ctx>,
weights: &QsaWeights,
) -> Result<Box<[f32]>> {
// Entire attended tensor was finite before gate, and entire gated result
// is finite BEFORE acquiring Out, so a later projection cannot mask it.
let gated = download(buffers[2].as_ref().ok_or(Error::IdentityMismatch)?, 6144)?;
validate_values(&gated, 6144)?;
let entry = cache.qsa(binding, weights.layer())?;
if !std::ptr::eq(entry.weights.as_ref(), weights) || weights.shape(QsaMatrixRole::Out) != (6144, 2560) {
return Err(Error::IdentityMismatch);
}
let (matrix, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?;
// This selected literal native profile only has Original quantized kinds;
// BF16 must not silently become a different decode arithmetic fallback.
if kind == QsaMatrixKind::Bf16 {
return Err(Error::Unsupported(Stage::QsaIndex));
}
buffers[3] = Some(allocate(context, 2560)?);
let (inputs, outputs) = buffers.split_at_mut(3);
project_scratch_out_numeric(
context,
matrix,
inputs[2].as_ref().ok_or(Error::IdentityMismatch)?,
outputs[0].as_mut().ok_or(Error::IdentityMismatch)?,
kind,
)
}
/// Release every role buffer; the first release failure is the one returned.
fn release_gate_buffers(buffers: GateBuffers<'_>) -> Result<()> {
let mut cleanup = Ok(());
for buffer in buffers.into_iter().flatten() {
if let Err(error) = buffer.release().map_err(driver) {
if cleanup.is_ok() {
cleanup = Err(error);
}
}
}
cleanup
}
#[allow(clippy::too_many_arguments)] // Actual role-specific weights and closed current finite inputs.
fn gate_and_out<'ctx>(
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
context: &'ctx Context<'ctx>,
weights: &QsaWeights,
attended: &[f32],
gate: &[f32],
owner: &mut QsaNativeGate<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
failed: &Cell<bool>,
) -> Result<Box<[f32]>> {
let mut buffers: GateBuffers<'ctx> = std::array::from_fn(|_| None);
let operation = (|| {
upload_gate_inputs(&mut buffers, context, (attended, gate), failed)?;
apply_gate(&mut buffers, owner, workspace)?;
project_gated_out(&mut buffers, (binding, cache), context, weights)
})();
let cleanup = release_gate_buffers(buffers);
if matches!(&operation, Err(Error::CudaExecution)) || cleanup.is_err() || context.is_poisoned() {
failed.set(true);
}
match operation {
Err(primary) => Err(primary),
Ok(values) => {
cleanup?;
Ok(values)
}
}
}
#[path = "qsa_resident_scalar/driver_fn.rs"]
mod driver_fn;
#[allow(unused_imports)]
use driver_fn::check_scalar_shapes;
#[allow(unused_imports)]
use driver_fn::check_scalar_txn;
#[allow(unused_imports)]
use driver_fn::check_txn_input;
#[allow(unused_imports)]
use driver_fn::driver;
#[allow(unused_imports)]
use driver_fn::scalar_gate;
#[path = "qsa_resident_scalar/impl_residentqsascalar.rs"]
mod impl_residentqsascalar;
#[allow(unused_imports)]
use impl_residentqsascalar::apply_gate;
#[allow(unused_imports)]
use impl_residentqsascalar::upload_gate_inputs;
#[path = "qsa_resident_scalar/project_gated_out_fn.rs"]
mod project_gated_out_fn;
#[allow(unused_imports)]
use project_gated_out_fn::gate_and_out;
#[allow(unused_imports)]
use project_gated_out_fn::project_gated_out;
#[allow(unused_imports)]
use project_gated_out_fn::release_gate_buffers;
@@ -0,0 +1,152 @@
//! Moved out of the parent module by STRA-338.
#[allow(unused_imports)]
use super::*;
pub(super) fn driver(e: leleka_cuda_driver::Error) -> Error {
device_error(e)
}
impl ScalarHost {
pub(super) fn gather(
context: &Context<'_>,
binding: &ModelBinding,
cache: &DenseWeightCache<'_>,
entry: &QsaResident,
input: &ResidualReady,
) -> Result<Self> {
let at = |role| project(context, binding, &entry.weights, role, input.mixed(), Some(cache));
let raw = at(QsaMatrixRole::IndexK)?;
let k = at(QsaMatrixRole::K)?;
let v = at(QsaMatrixRole::V)?;
let qfull = at(QsaMatrixRole::Q)?;
let iq = at(QsaMatrixRole::IndexQ)?;
for (values, n) in [(&raw, 128), (&k, 512), (&v, 512), (&qfull, 12288), (&iq, 512)] {
validate_values(values, n)?;
}
let gate = scalar_gate(&qfull)?;
Ok(Self { raw, k, v, qfull, iq, gate })
}
pub(super) fn select<'lease, 'index, 'weights, 'ctx>(
&self,
owner: &'lease mut OriginalQsaResidentScalarIndex<'ctx>,
(resident, prior): (&'index mut OriginalQsaResidentIndex<'ctx>, &OriginalQsaIndexCheckpoint<'ctx>),
norms: [&'weights DeviceBuffer<'ctx>; 4],
workspace: &mut NativeBatchWorkspace<'ctx>,
) -> Result<OriginalQsaResidentScalarSelection<'lease, 'index, 'weights, 'ctx>> {
owner
.prepare(resident, prior, &self.raw, &self.k, &self.v, &self.qfull, &self.iq, norms, workspace)
.map_err(driver)
}
}
pub(super) fn scalar_gate(qfull: &[f32]) -> Result<Box<[f32]>> {
let mut gate = Vec::new();
gate.try_reserve_exact(6144).map_err(|_| Error::InputAllocation)?;
for head in 0..24 {
gate.extend_from_slice(&qfull[head * 512 + 256..head * 512 + 512]);
}
validate_values(&gate, 6144)?;
Ok(gate.into_boxed_slice())
}
pub(super) fn check_txn_input(txn: &QwenStepTxn<'_, '_>, binding: &ModelBinding, input: &ResidualReady) -> Result<()> {
txn.validate_binding(&binding.identity())?;
txn.validate_input(input.identity().token(), input.identity().position())
}
pub(super) fn check_scalar_txn(
txn: &QwenStepTxn<'_, '_>,
binding: &ModelBinding,
input: &ResidualReady,
layer: LayerId,
prior: &ResidentQsaPrior<'_>,
) -> Result<()> {
check_txn_input(txn, binding, input)?;
input.identity().validate(txn.token(), txn.position(), layer)?;
input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?;
txn.validate_projection_branch(&prior.0.origin)
}
pub(super) fn check_scalar_shapes(entry: &QsaResident) -> Result<()> {
for (role, width) in [
(QsaMatrixRole::IndexK, 128),
(QsaMatrixRole::K, 512),
(QsaMatrixRole::V, 512),
(QsaMatrixRole::Q, 12288),
(QsaMatrixRole::IndexQ, 512),
] {
if entry.weights.shape(role) != (2560, width) {
return Err(Error::InvalidDimension);
}
}
Ok(())
}
impl<'ctx> ResidentQsaLayer<'ctx> {
/// The guards of `prepare_scalar` before any projection: the step, the lineage, the weights and the input.
pub(super) fn scalar_guards<'w>(
&self,
binding: &ModelBinding,
cache: &'w DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
layer: LayerId,
input: &ResidualReady,
prior: &ResidentQsaPrior<'ctx>,
) -> Result<(&'ctx Context<'ctx>, &'w QsaResident, Rc<()>)> {
check_scalar_txn(txn, binding, input, layer, prior)?;
let context = cache.retained_context(binding, txn.cuda_context()?)?;
cache.validate(binding)?;
let entry = cache.qsa(binding, layer.get())?;
self.check_scalar_prior(binding, txn, layer, prior, (context, entry))?;
validate_values(input.mixed(), 2560)?;
check_scalar_shapes(entry)?;
Ok((context, entry, txn.residual_handoff_owner()?))
}
pub(super) fn check_scalar_prior(
&self,
binding: &ModelBinding,
txn: &QwenStepTxn<'_, '_>,
layer: LayerId,
prior: &ResidentQsaPrior<'ctx>,
(context, entry): (&Context<'ctx>, &QsaResident),
) -> Result<()> {
if !self.current.same_prior(prior)
|| layer != prior.layer()
|| prior.next_position() != txn.position().get()
|| !prior.0.binding.matches(&binding.identity())
|| !std::ptr::eq(context, self.context)
|| !Rc::ptr_eq(&entry.weights, &prior.0.provider)
{
return Err(Error::IdentityMismatch);
}
self.index.validate_context(context).map_err(driver)?;
self.index.validate_checkpoint(&prior.0.index).map_err(driver)?;
self.kv.validate_prefix(&prior.0.kv).map_err(driver)
}
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn prepare_scalar<'source, 'lease, 'index, 'weights>(
&'index mut self,
binding: &ModelBinding,
cache: &'weights DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
layer: LayerId,
input: &'source ResidualReady,
prior: &ResidentQsaPrior<'ctx>,
owner: &'lease mut OriginalQsaResidentScalarIndex<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
) -> Result<ResidentQsaScalar<'source, 'lease, 'index, 'weights, 'ctx>> {
let (context, entry, transaction) = self.scalar_guards(binding, cache, txn, layer, input, prior)?;
let host = ScalarHost::gather(context, binding, cache, entry, input)?;
let norms = cache.qsa_norms(entry)?;
let selected = host.select(owner, (&mut self.index, &prior.0.index), norms, workspace)?;
check_txn_input(txn, binding, input)?;
cache.validate(binding)?;
Ok(ResidentQsaScalar {
binding: binding.identity(),
context,
layer,
source: input,
prior: prior.clone(),
provider: entry.weights.clone(),
transaction,
gate: host.gate,
selected,
kv: &mut self.kv,
})
}
}
@@ -0,0 +1,182 @@
//! Moved out of the parent module by STRA-338.
#[allow(unused_imports)]
use super::*;
impl<'source, 'lease, 'index, 'weights, 'ctx> ResidentQsaScalar<'source, 'lease, 'index, 'weights, 'ctx> {
pub(super) fn validate(
&self,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
input: &ResidualReady,
) -> Result<()> {
txn.validate_binding(&binding.identity())?;
txn.validate_input(input.identity().token(), input.identity().position())?;
input.identity().validate(txn.token(), txn.position(), self.layer)?;
input.validate_origin(&binding.identity(), GrRole::Attention(self.layer.get()))?;
txn.validate_projection_branch(&self.prior.0.origin)?;
let context = cache.retained_context(binding, txn.cuda_context()?)?;
let entry = cache.qsa(binding, self.layer.get())?;
if !self.binding.matches(&binding.identity())
|| !std::ptr::eq(context, self.context)
|| !std::ptr::eq(input, self.source)
|| !Rc::ptr_eq(&self.provider, &entry.weights)
|| !Rc::ptr_eq(&self.transaction, &txn.residual_handoff_owner()?)
|| self.prior.next_position() != txn.position().get()
|| self.selected.first_position() as u64 != txn.position().get()
{
return Err(Error::IdentityMismatch);
}
validate_values(&self.gate, 6144)
}
/// The attention of the appended row over the completed buffers.
pub(super) fn attend(
&mut self,
workspace: &mut NativeBatchWorkspace<'ctx>,
attention: &mut QsaNativeDecode<'ctx>,
append: &OriginalQsaMappedAppend,
) -> Result<Box<[f32]>> {
self.selected
.with_completed_buffers(|q, ids, steps| {
let inputs = QsaAttentionInputs::new(q, ids, steps, 1)?;
let actual = attention.attend_resident(workspace, self.kv, append.final_prefix(), &inputs)?;
actual.into_values()
})
.map_err(driver)
}
pub(super) fn gate_out(
&self,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
attended: &[f32],
gate_owner: &mut QsaNativeGate<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
) -> Result<Box<[f32]>> {
let failed = cache.transport_failure_flag(binding, self.context)?;
let provider = self.provider.as_ref();
gate_and_out(binding, cache, self.context, provider, attended, &self.gate, gate_owner, workspace, &failed)
}
/// The device work of one scalar row: append, attend, gate and Out; the seal or the abort follows.
pub(super) fn run(
&mut self,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
input: &ResidualReady,
(attention, stage, gate_owner): ScalarOwners<'_, 'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
) -> Result<(Box<[f32]>, OriginalQsaMappedAppend)> {
self.validate(binding, cache, txn, input)?;
super::super::super::admit_budget(self.context)?;
let append =
self.kv.append_resident_decode(workspace, stage, &self.prior.0.kv, &self.selected).map_err(driver)?;
let attended = self.attend(workspace, attention, &append)?;
validate_values(&attended, 6144)?;
let values = self.gate_out(binding, cache, &attended, gate_owner, workspace)?;
self.validate(binding, cache, txn, input)?;
validate_values(&values, 2560)?;
Ok((values, append))
}
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn complete(
mut self,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
input: &ResidualReady,
attention: &mut QsaNativeDecode<'ctx>,
stage: &mut OriginalQsaResidentTransport<'ctx>,
gate_owner: &mut QsaNativeGate<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
) -> Result<ResidentQsaScalarReady<'source, 'ctx>> {
match self.run(binding, cache, txn, input, (attention, stage, gate_owner), workspace) {
Err(primary) => {
let index = self.selected.abort(workspace).map_err(driver);
let kv = self.kv.rollback(workspace, &self.prior.0.kv).map_err(driver);
let _ = (index, kv);
Err(primary)
}
Ok((values, append)) => self.seal_ready(binding, cache, txn, workspace, (values, append)),
}
}
pub(super) fn seal_ready(
self,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
workspace: &mut NativeBatchWorkspace<'ctx>,
(values, append): (Box<[f32]>, OriginalQsaMappedAppend),
) -> Result<ResidentQsaScalarReady<'source, 'ctx>> {
let Self { binding: id, context, layer, source, prior, provider, transaction, selected, kv: journal, .. } =
self;
let index = selected.seal(workspace, 1).map_err(driver);
let kv = journal.accept_prefix(workspace, &append, 1).map_err(driver);
let (index, kv) = (index?, kv?);
cache.validate(binding)?;
cache.retained_context(binding, context)?;
txn.validate_projection_branch(&prior.0.origin)?;
let (owner, origin) = (prior.0.owner.clone(), prior.0.origin.clone());
let next = mint(id.clone(), owner, origin, (layer, provider.clone()), (index, kv));
let seal = ResidentQsaSeal { context, previous: prior, next, accepted: 1 };
Ok(ResidentQsaScalarReady { binding: id, context, layer, source, provider, transaction, values, seal })
}
}
impl<'source, 'ctx> ResidentQsaScalarReady<'source, 'ctx> {
pub(in crate::qwen_forward) fn into_parts(
self,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
input: &ResidualReady,
) -> Result<(TokenLayer, Box<[f32]>, ResidentQsaSeal<'ctx>)> {
txn.validate_binding(&binding.identity())?;
txn.validate_input(input.identity().token(), input.identity().position())?;
input.identity().validate(txn.token(), txn.position(), self.layer)?;
input.validate_origin(&binding.identity(), GrRole::Attention(self.layer.get()))?;
txn.validate_projection_branch(&self.seal.next.0.origin)?;
let context = cache.retained_context(binding, txn.cuda_context()?)?;
let entry = cache.qsa(binding, self.layer.get())?;
if !self.binding.matches(&binding.identity())
|| !std::ptr::eq(context, self.context)
|| !std::ptr::eq(input, self.source)
|| !Rc::ptr_eq(&self.provider, &entry.weights)
|| !Rc::ptr_eq(&self.transaction, &txn.residual_handoff_owner()?)
{
return Err(Error::IdentityMismatch);
}
validate_values(&self.values, 2560)?;
Ok((input.identity(), self.values, self.seal))
}
}
pub(super) fn upload_gate_inputs<'ctx>(
buffers: &mut GateBuffers<'ctx>,
context: &'ctx Context<'ctx>,
(attended, gate): (&[f32], &[f32]),
failed: &Cell<bool>,
) -> Result<()> {
if failed.get() {
return Err(Error::CudaExecution);
}
validate_values(attended, 6144)?;
validate_values(gate, 6144)?;
buffers[0] = Some(upload(context, attended)?);
buffers[1] = Some(upload(context, gate)?);
buffers[2] = Some(allocate(context, 6144)?);
Ok(())
}
pub(super) fn apply_gate<'ctx>(
buffers: &mut GateBuffers<'ctx>,
owner: &mut QsaNativeGate<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
) -> Result<()> {
let (inputs, outputs) = buffers.split_at_mut(2);
owner
.apply(
workspace,
inputs[0].as_ref().ok_or(Error::IdentityMismatch)?,
inputs[1].as_ref().ok_or(Error::IdentityMismatch)?,
outputs[0].as_mut().ok_or(Error::IdentityMismatch)?,
)
.map_err(driver)
}
@@ -0,0 +1,77 @@
//! Moved out of the parent module by STRA-338: fn project_gated_out, fn release_gate_buffers, fn gate_and_out.
#[allow(unused_imports)]
use super::*;
pub(super) fn project_gated_out<'ctx>(
buffers: &mut GateBuffers<'ctx>,
(binding, cache): (&ModelBinding, &DenseWeightCache<'ctx>),
context: &'ctx Context<'ctx>,
weights: &QsaWeights,
) -> Result<Box<[f32]>> {
// Entire attended tensor was finite before gate, and entire gated result
// is finite BEFORE acquiring Out, so a later projection cannot mask it.
let gated = download(buffers[2].as_ref().ok_or(Error::IdentityMismatch)?, 6144)?;
validate_values(&gated, 6144)?;
let entry = cache.qsa(binding, weights.layer())?;
if !std::ptr::eq(entry.weights.as_ref(), weights) || weights.shape(QsaMatrixRole::Out) != (6144, 2560) {
return Err(Error::IdentityMismatch);
}
let (matrix, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?;
// This selected literal native profile only has Original quantized kinds;
// BF16 must not silently become a different decode arithmetic fallback.
if kind == QsaMatrixKind::Bf16 {
return Err(Error::Unsupported(Stage::QsaIndex));
}
buffers[3] = Some(allocate(context, 2560)?);
let (inputs, outputs) = buffers.split_at_mut(3);
project_scratch_out_numeric(
context,
matrix,
inputs[2].as_ref().ok_or(Error::IdentityMismatch)?,
outputs[0].as_mut().ok_or(Error::IdentityMismatch)?,
kind,
)
}
/// Release every role buffer; the first release failure is the one returned.
pub(super) fn release_gate_buffers(buffers: GateBuffers<'_>) -> Result<()> {
let mut cleanup = Ok(());
for buffer in buffers.into_iter().flatten() {
if let Err(error) = buffer.release().map_err(driver) {
if cleanup.is_ok() {
cleanup = Err(error);
}
}
}
cleanup
}
#[allow(clippy::too_many_arguments)] // Actual role-specific weights and closed current finite inputs.
pub(super) fn gate_and_out<'ctx>(
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
context: &'ctx Context<'ctx>,
weights: &QsaWeights,
attended: &[f32],
gate: &[f32],
owner: &mut QsaNativeGate<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
failed: &Cell<bool>,
) -> Result<Box<[f32]>> {
let mut buffers: GateBuffers<'ctx> = std::array::from_fn(|_| None);
let operation = (|| {
upload_gate_inputs(&mut buffers, context, (attended, gate), failed)?;
apply_gate(&mut buffers, owner, workspace)?;
project_gated_out(&mut buffers, (binding, cache), context, weights)
})();
let cleanup = release_gate_buffers(buffers);
if matches!(&operation, Err(Error::CudaExecution)) || cleanup.is_err() || context.is_poisoned() {
failed.set(true);
}
match operation {
Err(primary) => Err(primary),
Ok(values) => {
cleanup?;
Ok(values)
}
}
}
+135 -1
View File
@@ -38,6 +38,56 @@
"reason": "moved verbatim by the size split of STRA-338 (size-rest); not yet decomposed",
"owner": "STRA-338"
},
{
"path": "crates/cuda-driver/src/qsa_late_gpu/impl_rng.rs",
"name": "topk_matches_original",
"fn_lines": 28,
"complexity": 1,
"nesting": 0,
"width": 1,
"reason": "moved verbatim by the mechanical splitter from an oversize legacy file (STRA-338 size2 merge); shrinks in the next size round",
"owner": "STRA-338"
},
{
"path": "crates/cuda-driver/src/qsa_late_gpu/scan_both_fn.rs",
"name": "bench_case",
"fn_lines": 31,
"complexity": 5,
"nesting": 2,
"width": 0,
"reason": "moved verbatim by the mechanical splitter from an oversize legacy file (STRA-338 size2 merge); shrinks in the next size round",
"owner": "STRA-338"
},
{
"path": "crates/cuda-driver/src/qsa_late_gpu/time_scores_and_topk_fn.rs",
"name": "time_scores_and_topk",
"fn_lines": 24,
"complexity": 1,
"nesting": 0,
"width": 1,
"reason": "moved verbatim by the mechanical splitter from an oversize legacy file (STRA-338 size2 merge); shrinks in the next size round",
"owner": "STRA-338"
},
{
"path": "crates/cuda-driver/src/qsa_prompt_attention/impl_qsapromptattention/impl_qsapromptattention_2_2.rs",
"name": "QsaPromptAttention::admit_inputs",
"fn_lines": 29,
"complexity": 14,
"nesting": 3,
"width": 0,
"reason": "moved verbatim by the mechanical splitter from an oversize legacy file (STRA-338 size2 merge); shrinks in the next size round",
"owner": "STRA-338"
},
{
"path": "crates/cuda-driver/src/qsa_prompt_attention/impl_qsapromptattention/impl_qsapromptattention_2_2.rs",
"name": "QsaPromptAttention::attend_kernel",
"fn_lines": 26,
"complexity": 13,
"nesting": 1,
"width": 0,
"reason": "moved verbatim by the mechanical splitter from an oversize legacy file (STRA-338 size2 merge); shrinks in the next size round",
"owner": "STRA-338"
},
{
"path": "crates/deploy/src/app/entry.rs",
"name": "<file>",
@@ -971,6 +1021,90 @@
"reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches",
"owner": "STRA-338"
},
{
"path": "crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/route_fn.rs",
"name": "route",
"fn_lines": 16,
"complexity": 11,
"nesting": 1,
"width": 0,
"reason": "moved verbatim by the mechanical splitter from an oversize legacy file (STRA-338 size2 merge); shrinks in the next size round",
"owner": "STRA-338"
},
{
"path": "crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner/impl_originalmtpfullowner.rs",
"name": "<file>",
"width": 1,
"reason": "moved verbatim by the mechanical splitter from an oversize legacy file (STRA-338 size2 merge); shrinks in the next size round",
"owner": "STRA-338"
},
{
"path": "crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalmtpdraftreceipt.rs",
"name": "OriginalCommittedMtpReceipt::for_published_window",
"fn_lines": 25,
"complexity": 13,
"nesting": 1,
"width": 0,
"reason": "moved verbatim by the mechanical splitter from an oversize legacy file (STRA-338 size2 merge); shrinks in the next size round",
"owner": "STRA-338"
},
{
"path": "crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalmtpdraftreceipt.rs",
"name": "OriginalCommittedMtpReceipt::validate",
"fn_lines": 27,
"complexity": 14,
"nesting": 1,
"width": 0,
"reason": "moved verbatim by the mechanical splitter from an oversize legacy file (STRA-338 size2 merge); shrinks in the next size round",
"owner": "STRA-338"
},
{
"path": "crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalmtpdraftreceipt.rs",
"name": "OriginalVerifiedMtpReceipt::after_target_commit",
"fn_lines": 30,
"complexity": 14,
"nesting": 1,
"width": 0,
"reason": "moved verbatim by the mechanical splitter from an oversize legacy file (STRA-338 size2 merge); shrinks in the next size round",
"owner": "STRA-338"
},
{
"path": "crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee/impl_originalservesettings.rs",
"name": "<file>",
"width": 8,
"reason": "moved verbatim by the mechanical splitter from an oversize legacy file (STRA-338 size2 merge); shrinks in the next size round",
"owner": "STRA-338"
},
{
"path": "crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/impl_residentqsascalar.rs",
"name": "ResidentQsaScalar::validate",
"fn_lines": 26,
"complexity": 17,
"nesting": 1,
"width": 0,
"reason": "moved verbatim by the mechanical splitter from an oversize legacy file (STRA-338 size2 merge); shrinks in the next size round",
"owner": "STRA-338"
},
{
"path": "crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/impl_residentqsascalar.rs",
"name": "ResidentQsaScalarReady::into_parts",
"fn_lines": 25,
"complexity": 16,
"nesting": 1,
"width": 0,
"reason": "moved verbatim by the mechanical splitter from an oversize legacy file (STRA-338 size2 merge); shrinks in the next size round",
"owner": "STRA-338"
},
{
"path": "crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/project_gated_out_fn.rs",
"name": "project_gated_out",
"fn_lines": 30,
"complexity": 12,
"nesting": 1,
"width": 0,
"reason": "moved verbatim by the mechanical splitter from an oversize legacy file (STRA-338 size2 merge); shrinks in the next size round",
"owner": "STRA-338"
},
{
"path": "crates/gateway-text/src/tool_output/tests/array_arguments_and_typed_values.rs",
"name": "parses_typed_values_and_preserves_text_around_calls",
@@ -1266,4 +1400,4 @@
"owner": "STRA-338"
}
]
}
}
+7 -12
View File
@@ -20,23 +20,18 @@
"width": 5
},
"leleka-cuda-driver": {
"fn_lines": 586,
"width": 815,
"complexity": 574,
"nesting": 23
"width": 671,
"complexity": 193,
"fn_lines": 3,
"nesting": 1
},
"leleka-deploy": {
"width": 247
},
"leleka-engine-core": {
"fn_lines": 11,
"complexity": 8
},
"leleka-engine-qwen35-cuda": {
"fn_lines": 517,
"width": 567,
"complexity": 526,
"nesting": 10
"width": 507,
"complexity": 262,
"fn_lines": 82
},
"leleka-experimental-ref": {
"width": 4