STRA-338 size: cuda-driver qsa_prompt_device_index: run_original_arena reuses the run phases (fn_lines 349 -> 31)

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 13:37:44 +01:00
parent 1fdb1011cc
commit 79f49258ae
3 changed files with 56 additions and 350 deletions
+16 -327
View File
@@ -1,4 +1,5 @@
//! Private real-arena continuation of the exact old prompt program.
use super::run_phases::{HostStaging, run_theta, step_bytes};
use super::*;
impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
#[allow(clippy::too_many_arguments)]
@@ -19,337 +20,25 @@ 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)?;
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_state(p, pooled, tail, dead)?;
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 k_h = out[0];
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(qfull_h), 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 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();
return Err(error);
}
};
let operation = (|| {
context.driver.api.copy_from(status, &zero)?;
context.driver.api.copy_from(out[4], &steps)?;
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 sync = blas.synchronize();
let read = if sync.is_ok() { context.driver.api.copy_to(status, &mut 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, decode_positions));
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(())
let plan = self.arena_plan((t, p0, decode), (raw_h, iq_h, out[0]), status, (positions, theta))?;
self.push_run_commands(&mut commands, &plan, Some(qfull_h), gamma, out)?;
let mut host =
HostStaging { commands, steps, zero: vec![0u8; 64], flags: vec![0u8; 64], kv: None, decode_positions };
self.execute_run(&plan, out, ws, &mut host)?;
self.check_run_flags(&host.flags)?;
self.check_selected_ids(out[3], p, n)
}
pub(super) fn final_state_original_arena(
&mut self,
@@ -38,25 +38,18 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
(Vec::new(), None)
};
let plan = self.run_plan((t, p0, decode), out[0], status, (positions, theta))?;
self.push_run_commands(&mut commands, &plan, gamma, out)?;
self.push_run_commands(&mut commands, &plan, None, 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,
};
let kv = Some([k_bytes, v_bytes]);
let mut host = HostStaging { commands, steps, zero: vec![0u8; 64], flags: vec![0u8; 64], kv, 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(
pub(super) fn execute_run(
&mut self,
plan: &RunPlan,
out: [ffi::BufferHandle; 5],
@@ -29,8 +29,8 @@ pub(super) struct HostStaging {
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>,
/// K and V bytes copied to the output buffers; absent when the caller already wrote them.
pub(super) kv: Option<[Vec<u8>; 2]>,
pub(super) decode_positions: Vec<u8>,
}
@@ -122,6 +122,14 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
qfull: &[f32],
iq: &[f32],
) -> Result<()> {
self.upload_run_state(p, pooled, tail, dead)?;
for (i, x) in [(4, raw), (7, qfull), (8, iq)] {
self.upload(i, x)?;
}
Ok(())
}
pub(super) fn upload_run_state(&mut self, p: usize, pooled: &[f32], tail: &[f32], dead: &[f32]) -> Result<()> {
if !pooled.is_empty() {
self.upload(0, pooled)?;
}
@@ -133,11 +141,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
}
result?;
self.upload(1, tail)?;
self.upload(2, dead)?;
for (i, x) in [(4, raw), (7, qfull), (8, iq)] {
self.upload(i, x)?;
}
Ok(())
self.upload(2, dead)
}
/// The 24 per-head position words of a decode step and their device span.
@@ -165,13 +169,26 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
(positions, theta): (Option<ffi::BufferHandle>, f32),
) -> Result<RunPlan> {
let n = t as usize;
let raw = self.handle(4, n * 128 * 4)?;
let iq = self.handle(8, n * 512 * 4)?;
self.arena_plan((t, p0, decode), (raw, iq, k), status, (positions, theta))
}
/// The plan over caller-provided raw and index-query handles.
pub(super) fn arena_plan(
&self,
(t, p0, decode): (u32, u32, bool),
(raw, iq, k): (ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle),
status: ffi::BufferHandle,
(positions, theta): (Option<ffi::BufferHandle>, f32),
) -> Result<RunPlan> {
Ok(RunPlan {
t,
p0,
decode,
raw: self.handle(4, n * 128 * 4)?,
raw,
k,
iq: self.handle(8, n * 512 * 4)?,
iq,
pooled: self.handle(0, self.sizes[0])?,
tail: self.handle(1, self.sizes[1])?,
dead: self.handle(2, self.sizes[2])?,
@@ -185,13 +202,18 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
&self,
commands: &mut Commands,
plan: &RunPlan,
qfull: Option<ffi::BufferHandle>,
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)];
let qfull = match qfull {
Some(handle) => handle,
None => self.handle(7, n * 12288 * 4)?,
};
let split = vec![A::Address(qfull), 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)?;
@@ -382,8 +404,10 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
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([k_bytes, v_bytes]) = &host.kv {
api.copy_from(out[0], k_bytes)?;
api.copy_from(out[1], v_bytes)?;
}
if let Some(positions) = plan.positions {
api.copy_from(positions, &host.decode_positions)?;
}