STRA-338 size: cuda-driver qsa_prompt_index: run split into upload/plan/push/execute/check phases (fn_lines 363 -> 48)

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 13:36:24 +01:00
parent 9592d92148
commit 1fdb1011cc
3 changed files with 480 additions and 324 deletions
@@ -83,3 +83,4 @@ mod impl_qsapromptindexworkspace;
mod impl_qsapromptindexworkspace_2;
mod impl_qsapromptindexworkspace_3;
mod impl_qsapromptindexworkspace_4;
mod run_phases;
@@ -1,5 +1,6 @@
//! Moved out of the parent module by STRA-338: impl QsaPromptIndexWorkspace (3).
use super::run_phases::{HostStaging, RunPlan, run_theta, step_bytes};
#[allow(unused_imports)]
use super::*;
@@ -24,348 +25,62 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
) -> Result<()> {
let n = t as usize;
let p = p0 as usize;
let end = p + n;
let nb = end / 4;
if !pooled.is_empty() {
self.upload(0, pooled)?;
}
// The current spare is genuine prior state even when this batch completes no block.
let spare = encode(dead)?;
let result = self.buffers[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(p / 4 * 128 * 4, &spare);
if result.is_err() {
self.failed = true;
}
result?;
self.upload(1, tail)?;
self.upload(2, dead)?;
for (i, x) in [(4, raw), (7, qfull), (8, iq)] {
self.upload(i, x)?;
}
let mut steps = Vec::new();
steps.try_reserve_exact(n * 16).map_err(|_| Error::HostAllocation)?;
for row in 0..n {
let pos = p + row;
for x in [pos, pos + 1, (pos + 1) / 4, (pos + 1).min(CAP)] {
steps.extend((x as i32).to_le_bytes());
}
}
let zero = vec![0u8; 64];
let mut flags = vec![0u8; 64];
self.upload_run_inputs(p, pooled, tail, dead, raw, qfull, iq)?;
let steps = step_bytes(p, n)?;
let status = self.handle(10, 64)?;
let mut commands: Vec<(Launch, Arguments)> = Vec::new();
commands.try_reserve_exact(32 + 4 * n.div_ceil(256)).map_err(|_| Error::HostAllocation)?;
let mut push = |shape, args| -> Result<()> {
commands.push((shape, Arguments::for_launch(shape, args)?));
Ok(())
let theta = run_theta()?;
let (decode_positions, positions) = if decode {
let (words, span) = self.decode_position_words(p0, n)?;
(words, Some(span))
} else {
(Vec::new(), None)
};
let theta = crate::qsa_index_ffi::theta();
if !theta.is_finite() || theta <= 0.0 {
return Err(Error::InvalidDriverValue("QSA theta"));
}
let mut decode_positions = Vec::new();
let positions = if decode {
decode_positions.try_reserve_exact(24 * 4).map_err(|_| Error::HostAllocation)?;
for _ in 0..24 {
decode_positions.extend((p0 as i32).to_le_bytes());
}
let b = self.buffers[4].as_ref().ok_or(Error::ContextPoisoned)?;
let full = self.handle(4, self.sizes[4])?;
let h = full.checked_subspan(b.len(), self.sizes[4] - 24 * 4, 24 * 4)?;
h.validate_projection_extent(24 * 4, 4)?;
if h.overlaps(24 * 4, self.handle(4, n * 128 * 4)?, n * 128 * 4) {
return Err(Error::OutputAliasesInput);
}
Some(h)
} else {
None
};
let raw_h = self.handle(4, n * 128 * 4)?;
let k_h = out[0];
let iq_h = self.handle(8, n * 512 * 4)?;
let pooled_h = self.handle(0, self.sizes[0])?;
let tail_h = self.handle(1, self.sizes[1])?;
let dead_h = self.handle(2, self.sizes[2])?;
if let Some(positions) = positions {
push(
Launch::DecodeRms(2),
vec![A::Address(k_h), A::Address(gamma[1]), A::Address(k_h), A::I32(256), A::F32(1e-6)],
)?;
push(
Launch::DecodeRope(2),
vec![A::Address(k_h), A::Address(k_h), A::I32(2), A::I32(256), A::F32(theta), A::Address(positions)],
)?;
} else {
push(
Launch::Rms(t * 2),
vec![A::Address(k_h), A::Address(gamma[1]), A::I64(256), A::I64(256), A::F32(1e-6)],
)?;
push(
Launch::Rope(t * 2),
vec![A::Address(k_h), A::I64(2), A::I64(256), A::I64(512), A::I64(p0 as i64), A::F32(theta)],
)?;
}
push(
Launch::Scan((n * 512) as u32),
vec![A::Address(k_h), A::I64((n * 512) as i64), A::Address(status), A::U32(0)],
)?;
push(
Launch::Split((n * 6144) as u32),
vec![A::Address(self.handle(7, n * 12288 * 4)?), A::Address(out[2]), A::I64(t as i64)],
)?;
if let Some(positions) = positions {
push(
Launch::DecodeRms(24),
vec![A::Address(out[2]), A::Address(gamma[0]), A::Address(out[2]), A::I32(256), A::F32(1e-6)],
)?;
push(
Launch::DecodeRope(24),
vec![
A::Address(out[2]),
A::Address(out[2]),
A::I32(24),
A::I32(256),
A::F32(theta),
A::Address(positions),
],
)?;
} else {
push(
Launch::Rms(t * 24),
vec![A::Address(out[2]), A::Address(gamma[0]), A::I64(256), A::I64(256), A::F32(1e-6)],
)?;
push(
Launch::Rope(t * 24),
vec![A::Address(out[2]), A::I64(24), A::I64(256), A::I64(6144), A::I64(p0 as i64), A::F32(theta)],
)?;
}
push(
Launch::Scan((n * 6144) as u32),
vec![A::Address(out[2]), A::I64((n * 6144) as i64), A::Address(status), A::U32(1)],
)?;
if let Some(positions) = positions {
push(
Launch::DecodeRms(4),
vec![A::Address(iq_h), A::Address(gamma[2]), A::Address(iq_h), A::I32(128), A::F32(1e-6)],
)?;
push(
Launch::DecodeRope(4),
vec![A::Address(iq_h), A::Address(iq_h), A::I32(4), A::I32(128), A::F32(theta), A::Address(positions)],
)?;
} else {
push(
Launch::Rms(t * 4),
vec![A::Address(iq_h), A::Address(gamma[2]), A::I64(128), A::I64(128), A::F32(1e-6)],
)?;
push(
Launch::Rope(t * 4),
vec![A::Address(iq_h), A::I64(4), A::I64(128), A::I64(512), A::I64(p0 as i64), A::F32(theta)],
)?;
}
push(
Launch::Scan((n * 512) as u32),
vec![A::Address(iq_h), A::I64((n * 512) as i64), A::Address(status), A::U32(2)],
)?;
if decode {
push(
Launch::DecodeAppend,
vec![
A::Address(raw_h),
A::Address(out[4]),
A::I32(0),
A::Address(gamma[3]),
A::F32(1e-6),
A::Address(tail_h),
A::Address(dead_h),
A::Address(pooled_h),
A::Address(self.handle(3, 4)?),
A::I32(crate::serving_context::geometry().cells() as i32),
A::F32(theta),
],
)?;
} else {
if p == 0 {
push(
Launch::First,
vec![
A::Address(raw_h),
A::Address(gamma[3]),
A::F32(1e-6),
A::Address(dead_h),
A::Address(pooled_h),
A::F32(theta),
],
)?;
}
let first = if p <= 3 { 0 } else { (p - 3).div_ceil(4) };
let hi = if end - 1 >= 3 { Some((end - 4) / 4) } else { None };
if let Some(hi) = hi.filter(|hi| *hi >= first) {
push(
Launch::Blocks((hi - first + 1) as u32),
vec![
A::Address(raw_h),
A::I64(t as i64),
A::I64(p0 as i64),
A::I32(0),
A::Address(gamma[3]),
A::F32(1e-6),
A::Address(tail_h),
A::Address(dead_h),
A::Address(pooled_h),
A::Address(self.handle(3, 4)?),
A::I64(first as i64),
A::I64(hi as i64),
A::F32(theta),
],
)?;
}
push(Launch::Tail, vec![A::Address(raw_h), A::I64(t as i64), A::I64(p0 as i64), A::Address(tail_h)])?;
}
for (h, count) in [(pooled_h, (nb + 1) * 128), (tail_h, 384), (dead_h, 128)] {
push(Launch::Scan(count as u32), vec![A::Address(h), A::I64(count as i64), A::Address(status), A::U32(3)])?;
}
// Original prompt selection reuses one 256-row score tile. Every
// offset is checked against the actual whole producer allocation.
let tile_rows = if decode { 1 } else { n.min(256) };
let scores = self.handle(9, tile_rows * max_blocks() * 4)?;
for first_row in (0..n).step_by(256) {
let count = (n - first_row).min(256);
let ct = count as u32;
let iq_tile = iq_h.checked_subspan(n * 512 * 4, first_row * 512 * 4, count * 512 * 4)?;
let steps_tile = out[4].checked_subspan(n * 16, first_row * 16, count * 16)?;
let ids_tile = out[3].checked_subspan(n * CAP * 4, first_row * CAP * 4, count * CAP * 4)?;
let tile_reach = (p + first_row + count) / 4 + 1;
if decode {
push(
Launch::DecodeScores,
vec![
A::Address(pooled_h),
A::Address(dead_h),
A::Address(iq_tile),
A::Address(steps_tile),
A::I32(1),
A::I64(max_blocks() as i64),
A::Address(scores),
],
)?;
} else {
push(
Launch::Tc { t: ct, reach: tile_reach as u32 },
vec![
A::Address(pooled_h),
A::Address(iq_tile),
A::Address(steps_tile),
A::I64(count as i64),
A::I64(max_blocks() as i64),
A::I64(tile_reach as i64),
A::Address(scores),
],
)?;
push(
Launch::ScoreTail(ct),
vec![
A::Address(dead_h),
A::Address(iq_tile),
A::Address(steps_tile),
A::I64(max_blocks() as i64),
A::Address(scores),
],
)?;
}
push(
Launch::ScoreScan((count * max_blocks()) as u32),
vec![
A::Address(scores),
A::Address(steps_tile),
A::I32(count as i32),
A::I64(max_blocks() as i64),
A::Address(status),
A::U32(4),
],
)?;
push(
Launch::Topk(ct),
vec![
A::Address(scores),
A::Address(steps_tile),
A::I64(max_blocks() as i64),
A::I64(CAP as i64),
A::Address(ids_tile),
],
)?;
}
push(Launch::Round((n * 128) as u32), vec![A::Address(raw_h), A::I64((n * 128) as i64)])?;
push(
Launch::Scan((n * 128) as u32),
vec![A::Address(raw_h), A::I64((n * 128) as i64), A::Address(status), A::U32(5)],
)?;
let plan = self.run_plan((t, p0, decode), out[0], status, (positions, theta))?;
self.push_run_commands(&mut commands, &plan, gamma, out)?;
let k_bytes = encode(k)?;
let v_bytes = encode(v)?;
let mut host = HostStaging {
commands,
steps,
zero: vec![0u8; 64],
flags: vec![0u8; 64],
k_bytes,
v_bytes,
decode_positions,
};
self.execute_run(&plan, out, ws, &mut host)?;
self.check_run_flags(&host.flags)?;
self.check_selected_ids(out[3], p, n)
}
/// Runs the staged copies and launches under the context guard, then reads the status words back.
fn execute_run(
&mut self,
plan: &RunPlan,
out: [ffi::BufferHandle; 5],
ws: &mut NativeBatchWorkspace<'ctx>,
host: &mut HostStaging,
) -> Result<()> {
let context = self.context;
let blas = ws.blas()?;
let guard = match context.enter() {
Ok(guard) => guard,
Err(error) => {
self.failed = true;
ws.mark_failed();
context.poison();
context.retain_driver();
self.fail_run(ws);
return Err(error);
}
};
let operation = (|| {
context.driver.api.copy_from(status, &zero)?;
context.driver.api.copy_from(out[4], &steps)?;
context.driver.api.copy_from(out[0], &k_bytes)?;
context.driver.api.copy_from(out[1], &v_bytes)?;
if let Some(positions) = positions {
context.driver.api.copy_from(positions, &decode_positions)?;
}
// Pageable uploads/status have a real dependency before the nonblocking shared stream.
context.driver.api.synchronize()?;
let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?;
for (shape, args) in &mut commands {
module.launch(*shape, blas.stream(), args)?;
}
Ok(())
})();
let operation = self.submit_run(blas, plan, out, host);
let sync = blas.synchronize();
let read = if sync.is_ok() { context.driver.api.copy_to(status, &mut flags) } else { Ok(()) };
let read = if sync.is_ok() { context.driver.api.copy_to(plan.status, &mut host.flags) } else { Ok(()) };
let pop = guard.finish();
if operation.is_err() || sync.is_err() || read.is_err() || pop.is_err() {
self.failed = true;
ws.mark_failed();
context.poison();
context.retain_driver();
std::mem::forget((commands, steps, zero, flags, k_bytes, v_bytes, decode_positions));
self.fail_run(ws);
std::mem::forget(std::mem::take(host));
return combine(combine(combine(operation, sync), read), pop);
}
combine(combine(combine(operation, sync), read), pop)?;
for flag in flags.as_chunks::<4>().0 {
if u32::from_le_bytes(*flag) > 1 {
self.failed = true;
return Err(Error::InvalidDriverValue("QSA finite status"));
}
}
if flags[24..].iter().any(|x| *x != 0) {
self.failed = true;
return Err(Error::InvalidDriverValue("QSA unused status"));
}
if flags[..24].iter().any(|x| *x != 0) {
return Err(Error::NonFiniteMmqOutput("QSA prompt normalized/index/scores"));
}
let ids = self.read(out[3], n * CAP * 4)?;
for row in 0..n {
let width = (p + row + 1).min(CAP);
let mut last = None;
for i in 0..width {
let at = (row * CAP + i) * 4;
let id = i32::from_le_bytes(ids[at..at + 4].try_into().map_err(|_| Error::InvalidSize)?);
if id < 0 || id as usize > p + row || last.is_some_and(|old| old >= id) {
return Err(Error::InvalidDriverValue("QSA selected IDs"));
}
last = Some(id);
}
}
Ok(())
combine(combine(combine(operation, sync), read), pop)
}
}
@@ -0,0 +1,440 @@
//! STRA-338 size: the phases of `QsaPromptIndexWorkspace::run`, extracted without reordering any call.
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::Blas;
pub(super) type Commands = Vec<(Launch, Arguments)>;
/// Handles and scalars every launch of one `run` shares.
pub(super) struct RunPlan {
pub(super) t: u32,
pub(super) p0: u32,
pub(super) decode: bool,
pub(super) raw: ffi::BufferHandle,
pub(super) k: ffi::BufferHandle,
pub(super) iq: ffi::BufferHandle,
pub(super) pooled: ffi::BufferHandle,
pub(super) tail: ffi::BufferHandle,
pub(super) dead: ffi::BufferHandle,
pub(super) status: ffi::BufferHandle,
pub(super) positions: Option<ffi::BufferHandle>,
pub(super) theta: f32,
}
#[derive(Default)]
/// Host memory the asynchronous copies and launches read; leaked on failure while they may still be in flight.
pub(super) struct HostStaging {
pub(super) commands: Commands,
pub(super) steps: Vec<u8>,
pub(super) zero: Vec<u8>,
pub(super) flags: Vec<u8>,
pub(super) k_bytes: Vec<u8>,
pub(super) v_bytes: Vec<u8>,
pub(super) decode_positions: Vec<u8>,
}
struct ScoreTile {
count: usize,
reach: usize,
iq: ffi::BufferHandle,
steps: ffi::BufferHandle,
ids: ffi::BufferHandle,
}
pub(super) fn push_launch(commands: &mut Commands, shape: Launch, args: Vec<A>) -> Result<()> {
commands.push((shape, Arguments::for_launch(shape, args)?));
Ok(())
}
pub(super) fn run_theta() -> Result<f32> {
let theta = crate::qsa_index_ffi::theta();
if !theta.is_finite() || theta <= 0.0 {
return Err(Error::InvalidDriverValue("QSA theta"));
}
Ok(theta)
}
pub(super) fn step_bytes(p: usize, n: usize) -> Result<Vec<u8>> {
let mut steps = Vec::new();
steps.try_reserve_exact(n * 16).map_err(|_| Error::HostAllocation)?;
for row in 0..n {
let pos = p + row;
for x in [pos, pos + 1, (pos + 1) / 4, (pos + 1).min(CAP)] {
steps.extend((x as i32).to_le_bytes());
}
}
Ok(steps)
}
fn push_scan(commands: &mut Commands, plan: &RunPlan, buf: ffi::BufferHandle, count: usize, which: u32) -> Result<()> {
push_launch(
commands,
Launch::Scan(count as u32),
vec![A::Address(buf), A::I64(count as i64), A::Address(plan.status), A::U32(which)],
)
}
fn push_norm_rope(
commands: &mut Commands,
plan: &RunPlan,
(buf, gamma): (ffi::BufferHandle, ffi::BufferHandle),
(heads, dim, stride): (u32, i32, i64),
) -> Result<()> {
let theta = plan.theta;
if let Some(positions) = plan.positions {
let rms = vec![A::Address(buf), A::Address(gamma), A::Address(buf), A::I32(dim), A::F32(1e-6)];
push_launch(commands, Launch::DecodeRms(heads), rms)?;
let rope = vec![
A::Address(buf),
A::Address(buf),
A::I32(heads as i32),
A::I32(dim),
A::F32(theta),
A::Address(positions),
];
push_launch(commands, Launch::DecodeRope(heads), rope)?;
} else {
let rms = vec![A::Address(buf), A::Address(gamma), A::I64(dim as i64), A::I64(dim as i64), A::F32(1e-6)];
push_launch(commands, Launch::Rms(plan.t * heads), rms)?;
let rope = vec![
A::Address(buf),
A::I64(heads as i64),
A::I64(dim as i64),
A::I64(stride),
A::I64(plan.p0 as i64),
A::F32(theta),
];
push_launch(commands, Launch::Rope(plan.t * heads), rope)?;
}
Ok(())
}
impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
#[allow(clippy::too_many_arguments)]
pub(super) fn upload_run_inputs(
&mut self,
p: usize,
pooled: &[f32],
tail: &[f32],
dead: &[f32],
raw: &[f32],
qfull: &[f32],
iq: &[f32],
) -> Result<()> {
if !pooled.is_empty() {
self.upload(0, pooled)?;
}
// The current spare is genuine prior state even when this batch completes no block.
let spare = encode(dead)?;
let result = self.buffers[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(p / 4 * 128 * 4, &spare);
if result.is_err() {
self.failed = true;
}
result?;
self.upload(1, tail)?;
self.upload(2, dead)?;
for (i, x) in [(4, raw), (7, qfull), (8, iq)] {
self.upload(i, x)?;
}
Ok(())
}
/// The 24 per-head position words of a decode step and their device span.
pub(super) fn decode_position_words(&self, p0: u32, n: usize) -> Result<(Vec<u8>, ffi::BufferHandle)> {
let mut decode_positions = Vec::new();
decode_positions.try_reserve_exact(24 * 4).map_err(|_| Error::HostAllocation)?;
for _ in 0..24 {
decode_positions.extend((p0 as i32).to_le_bytes());
}
let b = self.buffers[4].as_ref().ok_or(Error::ContextPoisoned)?;
let full = self.handle(4, self.sizes[4])?;
let h = full.checked_subspan(b.len(), self.sizes[4] - 24 * 4, 24 * 4)?;
h.validate_projection_extent(24 * 4, 4)?;
if h.overlaps(24 * 4, self.handle(4, n * 128 * 4)?, n * 128 * 4) {
return Err(Error::OutputAliasesInput);
}
Ok((decode_positions, h))
}
pub(super) fn run_plan(
&self,
(t, p0, decode): (u32, u32, bool),
k: ffi::BufferHandle,
status: ffi::BufferHandle,
(positions, theta): (Option<ffi::BufferHandle>, f32),
) -> Result<RunPlan> {
let n = t as usize;
Ok(RunPlan {
t,
p0,
decode,
raw: self.handle(4, n * 128 * 4)?,
k,
iq: self.handle(8, n * 512 * 4)?,
pooled: self.handle(0, self.sizes[0])?,
tail: self.handle(1, self.sizes[1])?,
dead: self.handle(2, self.sizes[2])?,
status,
positions,
theta,
})
}
pub(super) fn push_run_commands(
&self,
commands: &mut Commands,
plan: &RunPlan,
gamma: [ffi::BufferHandle; 4],
out: [ffi::BufferHandle; 5],
) -> Result<()> {
let n = plan.t as usize;
push_norm_rope(commands, plan, (plan.k, gamma[1]), (2, 256, 512))?;
push_scan(commands, plan, plan.k, n * 512, 0)?;
let split = vec![A::Address(self.handle(7, n * 12288 * 4)?), A::Address(out[2]), A::I64(plan.t as i64)];
push_launch(commands, Launch::Split((n * 6144) as u32), split)?;
push_norm_rope(commands, plan, (out[2], gamma[0]), (24, 256, 6144))?;
push_scan(commands, plan, out[2], n * 6144, 1)?;
push_norm_rope(commands, plan, (plan.iq, gamma[2]), (4, 128, 512))?;
push_scan(commands, plan, plan.iq, n * 512, 2)?;
self.push_pool(commands, plan, gamma[3], out[4])?;
self.push_scores(commands, plan, out)?;
push_launch(commands, Launch::Round((n * 128) as u32), vec![A::Address(plan.raw), A::I64((n * 128) as i64)])?;
push_scan(commands, plan, plan.raw, n * 128, 5)
}
fn push_pool(
&self,
commands: &mut Commands,
plan: &RunPlan,
gamma: ffi::BufferHandle,
out4: ffi::BufferHandle,
) -> Result<()> {
if plan.decode {
self.push_pool_decode(commands, plan, gamma, out4)?;
} else {
self.push_pool_prompt(commands, plan, gamma)?;
}
let nb = (plan.p0 as usize + plan.t as usize) / 4;
for (h, count) in [(plan.pooled, (nb + 1) * 128), (plan.tail, 384), (plan.dead, 128)] {
push_scan(commands, plan, h, count, 3)?;
}
Ok(())
}
fn push_pool_decode(
&self,
commands: &mut Commands,
plan: &RunPlan,
gamma: ffi::BufferHandle,
out4: ffi::BufferHandle,
) -> Result<()> {
let args = vec![
A::Address(plan.raw),
A::Address(out4),
A::I32(0),
A::Address(gamma),
A::F32(1e-6),
A::Address(plan.tail),
A::Address(plan.dead),
A::Address(plan.pooled),
A::Address(self.handle(3, 4)?),
A::I32(crate::serving_context::geometry().cells() as i32),
A::F32(plan.theta),
];
push_launch(commands, Launch::DecodeAppend, args)
}
fn push_pool_prompt(&self, commands: &mut Commands, plan: &RunPlan, gamma: ffi::BufferHandle) -> Result<()> {
let (t, p0) = (plan.t, plan.p0);
let p = p0 as usize;
let end = p + t as usize;
if p == 0 {
let args = vec![
A::Address(plan.raw),
A::Address(gamma),
A::F32(1e-6),
A::Address(plan.dead),
A::Address(plan.pooled),
A::F32(plan.theta),
];
push_launch(commands, Launch::First, args)?;
}
let first = if p <= 3 { 0 } else { (p - 3).div_ceil(4) };
let hi = if end - 1 >= 3 { Some((end - 4) / 4) } else { None };
if let Some(hi) = hi.filter(|hi| *hi >= first) {
let args = vec![
A::Address(plan.raw),
A::I64(t as i64),
A::I64(p0 as i64),
A::I32(0),
A::Address(gamma),
A::F32(1e-6),
A::Address(plan.tail),
A::Address(plan.dead),
A::Address(plan.pooled),
A::Address(self.handle(3, 4)?),
A::I64(first as i64),
A::I64(hi as i64),
A::F32(plan.theta),
];
push_launch(commands, Launch::Blocks((hi - first + 1) as u32), args)?;
}
let tail = vec![A::Address(plan.raw), A::I64(t as i64), A::I64(p0 as i64), A::Address(plan.tail)];
push_launch(commands, Launch::Tail, tail)
}
fn push_scores(&self, commands: &mut Commands, plan: &RunPlan, out: [ffi::BufferHandle; 5]) -> Result<()> {
let n = plan.t as usize;
// Original prompt selection reuses one 256-row score tile. Every
// offset is checked against the actual whole producer allocation.
let tile_rows = if plan.decode { 1 } else { n.min(256) };
let scores = self.handle(9, tile_rows * max_blocks() * 4)?;
for first_row in (0..n).step_by(256) {
let count = (n - first_row).min(256);
let tile = ScoreTile {
count,
reach: (plan.p0 as usize + first_row + count) / 4 + 1,
iq: plan.iq.checked_subspan(n * 512 * 4, first_row * 512 * 4, count * 512 * 4)?,
steps: out[4].checked_subspan(n * 16, first_row * 16, count * 16)?,
ids: out[3].checked_subspan(n * CAP * 4, first_row * CAP * 4, count * CAP * 4)?,
};
push_tile_scores(commands, plan, scores, &tile)?;
push_tile_select(commands, plan, scores, &tile)?;
}
Ok(())
}
}
fn push_tile_scores(
commands: &mut Commands,
plan: &RunPlan,
scores: ffi::BufferHandle,
tile: &ScoreTile,
) -> Result<()> {
let ct = tile.count as u32;
if plan.decode {
let args = vec![
A::Address(plan.pooled),
A::Address(plan.dead),
A::Address(tile.iq),
A::Address(tile.steps),
A::I32(1),
A::I64(max_blocks() as i64),
A::Address(scores),
];
return push_launch(commands, Launch::DecodeScores, args);
}
let tc = vec![
A::Address(plan.pooled),
A::Address(tile.iq),
A::Address(tile.steps),
A::I64(tile.count as i64),
A::I64(max_blocks() as i64),
A::I64(tile.reach as i64),
A::Address(scores),
];
push_launch(commands, Launch::Tc { t: ct, reach: tile.reach as u32 }, tc)?;
let tail = vec![
A::Address(plan.dead),
A::Address(tile.iq),
A::Address(tile.steps),
A::I64(max_blocks() as i64),
A::Address(scores),
];
push_launch(commands, Launch::ScoreTail(ct), tail)
}
fn push_tile_select(
commands: &mut Commands,
plan: &RunPlan,
scores: ffi::BufferHandle,
tile: &ScoreTile,
) -> Result<()> {
let scan = vec![
A::Address(scores),
A::Address(tile.steps),
A::I32(tile.count as i32),
A::I64(max_blocks() as i64),
A::Address(plan.status),
A::U32(4),
];
push_launch(commands, Launch::ScoreScan((tile.count * max_blocks()) as u32), scan)?;
let topk = vec![
A::Address(scores),
A::Address(tile.steps),
A::I64(max_blocks() as i64),
A::I64(CAP as i64),
A::Address(tile.ids),
];
push_launch(commands, Launch::Topk(tile.count as u32), topk)
}
impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
/// Copies the staged host bytes up and launches every command on the shared stream.
pub(super) fn submit_run(
&self,
blas: &Blas,
plan: &RunPlan,
out: [ffi::BufferHandle; 5],
host: &mut HostStaging,
) -> Result<()> {
let api = &self.context.driver.api;
api.copy_from(plan.status, &host.zero)?;
api.copy_from(out[4], &host.steps)?;
api.copy_from(out[0], &host.k_bytes)?;
api.copy_from(out[1], &host.v_bytes)?;
if let Some(positions) = plan.positions {
api.copy_from(positions, &host.decode_positions)?;
}
// Pageable uploads/status have a real dependency before the nonblocking shared stream.
api.synchronize()?;
let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?;
for (shape, args) in &mut host.commands {
module.launch(*shape, blas.stream(), args)?;
}
Ok(())
}
/// Marks the workspace, the batch workspace and the context failed after a device error.
pub(super) fn fail_run(&mut self, ws: &mut NativeBatchWorkspace<'ctx>) {
self.failed = true;
ws.mark_failed();
self.context.poison();
self.context.retain_driver();
}
pub(super) fn check_run_flags(&mut self, flags: &[u8]) -> Result<()> {
for flag in flags.as_chunks::<4>().0 {
if u32::from_le_bytes(*flag) > 1 {
self.failed = true;
return Err(Error::InvalidDriverValue("QSA finite status"));
}
}
if flags[24..].iter().any(|x| *x != 0) {
self.failed = true;
return Err(Error::InvalidDriverValue("QSA unused status"));
}
if flags[..24].iter().any(|x| *x != 0) {
return Err(Error::NonFiniteMmqOutput("QSA prompt normalized/index/scores"));
}
Ok(())
}
pub(super) fn check_selected_ids(&mut self, ids_handle: ffi::BufferHandle, p: usize, n: usize) -> Result<()> {
let ids = self.read(ids_handle, n * CAP * 4)?;
for row in 0..n {
let width = (p + row + 1).min(CAP);
let mut last = None;
for i in 0..width {
let at = (row * CAP + i) * 4;
let id = i32::from_le_bytes(ids[at..at + 4].try_into().map_err(|_| Error::InvalidSize)?);
if id < 0 || id as usize > p + row || last.is_some_and(|old| old >= id) {
return Err(Error::InvalidDriverValue("QSA selected IDs"));
}
last = Some(id);
}
}
Ok(())
}
}