STRA-338 params r01: QSA attend, prompt index, decode index and prompt device take domain structs

Files:
crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/qsa_native.rs
This commit is contained in:
Pavlo Ratushnyi
2026-11-08 02:00:04 +01:00
parent a41c6a0d62
commit ad6d25da04
13 changed files with 163 additions and 120 deletions
@@ -5,11 +5,11 @@ use super::*;
use crate::qwen_forward::gr::ResidualReady;
use crate::qwen_forward::qsa_attention::QsaReady;
use crate::qwen_forward::qsa_attention::{
NativeAttended, NativePromptAttentionBatch, NativePromptAttentionBatch as Batch,
NativeAttended, NativePromptAttentionBatch, NativePromptAttentionBatch as Batch, PromptDevices,
};
use crate::qwen_forward::qsa_native_resources::NativeQsaResources;
use crate::qwen_forward::qsa_prefill_batch::NativeProjectionRow;
use crate::qwen_forward::qsa_prompt_index;
use crate::qwen_forward::qsa_prompt_index::{self, PromptChunkOwners, PromptIndexDevices};
use leleka_cuda_driver::{QsaPromptAttention, QsaPromptIndexWorkspace, QsaPromptKv, QsaPromptStage};
/// The index workspace, stage, attention and KV owners of the native QSA prompt.
@@ -96,10 +96,13 @@ fn qsa_native_complete<'source, 'lease, 'own, 'ctx>(
let prior = chunk.prompt_native_qsa_prior(layer, kv)?;
let mut workspace = cache.native_batch_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?;
let owner = index.as_mut().ok_or(Error::IdentityMismatch)?;
let index = qsa_prompt_index::prepare(binding, cache, chunk, layer, &prior, native, owner, &mut workspace)?;
let owners = PromptChunkOwners { binding, cache, chunk };
let index_devices = PromptIndexDevices { owner, workspace: &mut workspace };
let index = qsa_prompt_index::prepare(owners, layer, &prior, native, index_devices)?;
let stage = stage.as_mut().ok_or(Error::IdentityMismatch)?;
let attention = prompt_attention.as_mut().ok_or(Error::IdentityMismatch)?;
let completed = Batch::complete(binding, cache, chunk, layer, index, &prior, kv, stage, attention, &mut workspace)?;
let devices = PromptDevices { kv, stage, attention, workspace: &mut workspace };
let completed = Batch::complete(owners, layer, index, &prior, devices)?;
drop(workspace);
Ok(completed)
}
@@ -3,8 +3,8 @@
use super::contract::{Error, LayerId, Result, Stage, TokenLayer};
use super::dense_weight_cache::DenseWeightCache;
use super::qsa_index::{
QsaPrepared, QsaSelectedCache, admit_budget, allocate, download, driver_error, project, project_cached_out,
release, upload, upload_bytes, validate_values,
QsaAttendBuffers, QsaPrepared, QsaSelectedCache, admit_budget, allocate, download, driver_error, project,
project_cached_out, release, upload, upload_bytes, validate_values,
};
use super::session::QwenStepTxn;
use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding, QsaMatrixRole};
@@ -107,6 +107,8 @@ mod impl_qsaready;
use impl_qsaready::decode_cached;
mod decode_selected_cached_fn;
#[allow(unused_imports)]
use decode_selected_cached_fn::SelectedKvBytes;
#[allow(unused_imports)]
use decode_selected_cached_fn::attend_retained;
#[allow(unused_imports)]
use decode_selected_cached_fn::attention_driver_error;
@@ -121,3 +123,5 @@ use decode_selected_cached_fn::upload_retained_bytes;
#[allow(unused_imports)]
use decode_selected_cached_fn::upload_retained_f32;
mod impl_nativeattended;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) use impl_nativeattended::PromptDevices;
@@ -14,7 +14,8 @@ pub(super) fn decode_selected_cached(
let context = cache.retained_context(binding, context)?;
let failed = cache.transport_failure_flag(binding, context)?;
let (mut q, mut y) = (None, None);
let result = attend_selected(binding, prepared, context, selected, &failed, (&mut q, &mut y));
let retained = RetainedAttend { query: &mut q, output: &mut y, failed: &failed };
let result = attend_selected(binding, prepared, context, selected, retained);
let cleanup = release_retained([q]);
let values = settle_retained(result, cleanup, &mut y, &failed)?;
let attended = QsaAttended { context, buffer: y, values, failed };
@@ -26,20 +27,27 @@ pub(super) fn decode_selected_cached(
validate_values(&output, 2560)?;
Ok(QsaReady { identity: prepared.identity(), binding: binding.identity(), output })
}
/// The retained query and output buffers of one selected-cache attend pass and the shared failure fence they settle
/// against.
struct RetainedAttend<'a, 'ctx> {
query: &'a mut Option<DeviceBuffer<'ctx>>,
output: &'a mut Option<DeviceBuffer<'ctx>>,
failed: &'a Cell<bool>,
}
/// The selected cache attends the uploaded query into `y`; the output is read back whole.
fn attend_selected<'ctx>(
binding: &ModelBinding,
prepared: &QsaPrepared,
context: &'ctx Context<'ctx>,
selected: &mut QsaSelectedCache<'_>,
failed: &Cell<bool>,
(q, y): (&mut Option<DeviceBuffer<'ctx>>, &mut Option<DeviceBuffer<'ctx>>),
retained: RetainedAttend<'_, 'ctx>,
) -> Result<Box<[f32]>> {
let RetainedAttend { query: q, output: y, failed } = retained;
validate_values(prepared.q(), Q)?;
*q = Some(upload_retained_f32(context, prepared.q(), failed)?);
*y = Some(allocate(context, Q)?);
let (query, output) = (q.as_ref().ok_or(Error::CudaExecution)?, y.as_mut().ok_or(Error::CudaExecution)?);
selected.attend(&binding.identity(), context, prepared, query, output)?;
selected.attend(&binding.identity(), context, prepared, QsaAttendBuffers { query, output })?;
// Full original finite boundary remains before gating can mask an invalid value.
download(y.as_ref().ok_or(Error::CudaExecution)?, Q)
}
@@ -63,6 +71,13 @@ fn settle_retained<T>(
output_cleanup?;
Err(Error::CudaExecution)
}
/// The canonical FP16 key and value bytes of the `width` selected cells one QSA attention pass reads.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct SelectedKvBytes<'a> {
pub(in crate::qwen_forward) keys: &'a [u8],
pub(in crate::qwen_forward) values: &'a [u8],
pub(in crate::qwen_forward) width: u32,
}
#[derive(Default)]
struct AttendBuffers<'ctx> {
q: Option<DeviceBuffer<'ctx>>,
@@ -89,10 +104,10 @@ impl<'ctx> AttendBuffers<'ctx> {
&mut self,
context: &'ctx Context<'ctx>,
query: &[f32],
(keys, values): (&[u8], &[u8]),
width: u32,
kv: SelectedKvBytes<'_>,
failed: &Cell<bool>,
) -> Result<Box<[f32]>> {
let SelectedKvBytes { keys, values, width } = kv;
self.upload(context, query, (keys, values), failed)?;
let (q, k, v) = (self.q.as_ref(), self.k.as_ref(), self.v.as_ref());
let (q, k, v) =
@@ -108,17 +123,15 @@ impl<'ctx> AttendBuffers<'ctx> {
pub(super) fn attend_retained<'ctx>(
context: &'ctx Context<'ctx>,
query: &[f32],
keys: &[u8],
values: &[u8],
width: u32,
kv: SelectedKvBytes<'_>,
failed: Rc<Cell<bool>>,
) -> Result<QsaAttended<'ctx>> {
if failed.get() {
return Err(Error::CudaExecution);
}
check_attend(query, keys, values, width)?;
check_attend(query, kv.keys, kv.values, kv.width)?;
let mut buffers = AttendBuffers::default();
let result = buffers.launch(context, query, (keys, values), width, &failed);
let result = buffers.launch(context, query, kv, &failed);
let cleanup = release_retained([buffers.q.take(), buffers.k.take(), buffers.v.take()]);
let read = settle_retained(result, cleanup, &mut buffers.y, &failed)?;
Ok(QsaAttended { context, buffer: buffers.y, values: read, failed })
@@ -2,6 +2,8 @@
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use super::super::qsa_index::QsaPending;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use super::super::qsa_prompt_index::PromptChunkOwners;
#[allow(unused_imports)]
use super::*;
@@ -95,26 +97,20 @@ impl NativeAttended<'_, '_> {
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
impl<'source, 'lease, 'ctx> NativePromptAttentionBatch<'source, 'lease, 'ctx> {
#[allow(clippy::too_many_arguments)]
pub(in super::super) fn complete(
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
chunk: &super::super::session::chunk::QwenChunkTxn<'_, '_>,
owners: PromptChunkOwners<'_, 'ctx, '_, '_>,
layer: LayerId,
index: super::super::qsa_prompt_index::PromptIndexBatch<'source, 'lease, 'ctx>,
prior: &super::super::qsa_index::QsaPrior,
kv: &mut leleka_cuda_driver::QsaPromptKv<'ctx>,
stage: &mut leleka_cuda_driver::QsaPromptStage<'ctx>,
attention: &mut leleka_cuda_driver::QsaPromptAttention<'ctx>,
workspace: &mut leleka_cuda_driver::NativeBatchWorkspace<'ctx>,
mut devices: PromptDevices<'_, 'ctx>,
) -> Result<Self> {
let PromptChunkOwners { binding, cache, chunk } = owners;
let (context, origin) = Self::owner(binding, cache, chunk)?;
chunk.validate_prompt_qsa_prior(layer, prior)?;
let snapshot = prior.native_snapshot(kv)?.clone();
let snapshot = prior.native_snapshot(devices.kv)?.clone();
let t = index.rows();
let mut devices = PromptDevices { kv, stage, attention, workspace };
let append = devices.append(&index, binding, cache, chunk, &snapshot)?;
let values = devices.attend(&index, binding, cache, chunk, &append)?;
let append = devices.append(&index, owners, &snapshot)?;
let values = devices.attend(&index, owners, &append)?;
validate_values(&values, t * Q)?;
chunk.validate_prompt_qsa_prior(layer, prior)?;
let provider = cache.qsa(binding, layer.get())?.weights.clone();
@@ -228,11 +224,11 @@ type RowWords = (Box<[f32]>, Box<[f32]>);
/// The prompt KV, its stage, the attention and the workspace of one native QSA layer.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
struct PromptDevices<'a, 'ctx> {
kv: &'a mut leleka_cuda_driver::QsaPromptKv<'ctx>,
stage: &'a mut leleka_cuda_driver::QsaPromptStage<'ctx>,
attention: &'a mut leleka_cuda_driver::QsaPromptAttention<'ctx>,
workspace: &'a mut leleka_cuda_driver::NativeBatchWorkspace<'ctx>,
pub(in crate::qwen_forward) struct PromptDevices<'a, 'ctx> {
pub(in crate::qwen_forward) kv: &'a mut leleka_cuda_driver::QsaPromptKv<'ctx>,
pub(in crate::qwen_forward) stage: &'a mut leleka_cuda_driver::QsaPromptStage<'ctx>,
pub(in crate::qwen_forward) attention: &'a mut leleka_cuda_driver::QsaPromptAttention<'ctx>,
pub(in crate::qwen_forward) workspace: &'a mut leleka_cuda_driver::NativeBatchWorkspace<'ctx>,
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
impl<'ctx> PromptDevices<'_, 'ctx> {
@@ -240,11 +236,10 @@ impl<'ctx> PromptDevices<'_, 'ctx> {
fn append(
&mut self,
index: &super::super::qsa_prompt_index::PromptIndexBatch<'_, '_, 'ctx>,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
chunk: &super::super::session::chunk::QwenChunkTxn<'_, '_>,
owners: PromptChunkOwners<'_, 'ctx, '_, '_>,
snapshot: &leleka_cuda_driver::QsaKvSnapshot,
) -> Result<leleka_cuda_driver::CompletedQsaKvAppend> {
let PromptChunkOwners { binding, cache, chunk } = owners;
let t = index.rows();
let append = index.with_completed_before_causal(binding, cache, chunk, |k, v, _, _, _| {
let inputs = leleka_cuda_driver::QsaKvInputs::new(k, v, t).map_err(attention_driver_error)?;
@@ -264,11 +259,10 @@ impl<'ctx> PromptDevices<'_, 'ctx> {
fn attend(
&mut self,
index: &super::super::qsa_prompt_index::PromptIndexBatch<'_, '_, 'ctx>,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
chunk: &super::super::session::chunk::QwenChunkTxn<'_, '_>,
owners: PromptChunkOwners<'_, 'ctx, '_, '_>,
append: &leleka_cuda_driver::CompletedQsaKvAppend,
) -> Result<Box<[f32]>> {
let PromptChunkOwners { binding, cache, chunk } = owners;
let t = index.rows();
index.with_completed_before_causal(binding, cache, chunk, |_, _, q, ids, steps| {
let inputs =
@@ -3,9 +3,10 @@
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use super::super::{
qsa_decode_attention::{NativeDecodeAttentionRow, NativeDecodeDevices, complete},
qsa_decode_index::QsaDecodeIndex,
qsa_decode_index::{DecodeStepOwners, QsaDecodeIndex},
qsa_index::QsaPrior,
qsa_native_resources::NativeQsaResources,
qsa_prompt_index::PromptIndexDevices,
};
#[allow(unused_imports)]
use super::*;
@@ -60,7 +61,9 @@ impl QsaAttentionStage {
let kv = kv.get_mut(slot).ok_or(Error::InvalidLayer)?;
let prior = txn.native_qsa_prior(layer, kv)?;
let index = index.as_mut().ok_or(Error::IdentityMismatch)?;
let selected = QsaDecodeIndex::prepare(binding, cache, txn, layer, input, &prior, index, workspace)?;
let owners = DecodeStepOwners { binding, cache, txn };
let devices = PromptIndexDevices { owner: index, workspace: &mut *workspace };
let selected = QsaDecodeIndex::prepare(owners, layer, input, &prior, devices)?;
let devices = NativeDecodeDevices::bind(decode, kv, stage, gate, workspace)?;
let completed = complete(binding, cache, txn, layer, input, &prior, selected, devices)?;
Ok((prior, completed))
@@ -88,7 +91,7 @@ impl QsaAttentionStage {
let context = txn.cuda_context()?;
admit_budget(context)?;
if let Some(cache) = cache {
return decode_cached(binding, &prepared, context, cache, &k, &v, width);
return decode_cached(binding, &prepared, context, cache, SelectedKvBytes { keys: &k, values: &v, width });
}
Self::decode_host(binding, &prepared, context, (&k, &v), width)
}
@@ -197,13 +200,11 @@ pub(super) fn decode_cached(
prepared: &QsaPrepared,
context: &Context<'_>,
cache: &DenseWeightCache<'_>,
keys: &[u8],
values: &[u8],
width: u32,
kv: SelectedKvBytes<'_>,
) -> Result<QsaReady> {
let context = cache.retained_context(binding, context)?;
let failed = cache.transport_failure_flag(binding, context)?;
let attended = attend_retained(context, prepared.q(), keys, values, width, failed)?;
let attended = attend_retained(context, prepared.q(), kv, failed)?;
let gated = gate_retained(context, attended, prepared.gate())?;
let result = project_cached_out(context, binding, prepared.weights(), &gated, cache);
let cleanup = gated.close();
@@ -41,12 +41,11 @@ type Legacy = (Box<[f32]>, Box<[f32]>, Box<[f32]>);
fn original_transfer_chain(
context: &Context<'_>,
query: &[f32],
keys: &[u8],
values: &[u8],
kv: SelectedKvBytes<'_>,
gate: &[f32],
width: u32,
matrix: &DeviceBuffer<'_>,
) -> Legacy {
let SelectedKvBytes { keys, values, width } = kv;
let q = upload(context, query).unwrap();
let k = upload_bytes(context, keys).unwrap();
let v = upload_bytes(context, values).unwrap();
@@ -107,9 +106,10 @@ fn prove_pair(context: &Context<'_>, matrix: &DeviceBuffer<'_>, failed: &Rc<Cell
let query_bits: Vec<u32> = query.iter().map(|v| v.to_bits()).collect();
let gate_bits: Vec<u32> = gate.iter().map(|v| v.to_bits()).collect();
let (keys, values) = half_kv(width as usize, zero);
let legacy = original_transfer_chain(context, &query, &keys, &values, &gate, width, matrix);
let kv = SelectedKvBytes { keys: &keys, values: &values, width };
let legacy = original_transfer_chain(context, &query, kv, &gate, matrix);
let charged = context.allocated_bytes();
let attended = attend_retained(context, &query, &keys, &values, width, failed.clone()).unwrap();
let attended = attend_retained(context, &query, kv, failed.clone()).unwrap();
exact(&attended.values, &legacy.0);
assert_eq!(context.allocated_bytes(), charged + Q * 4);
let gated = gate_retained(context, attended, &gate).unwrap();
@@ -128,6 +128,17 @@ fn prove_pair(context: &Context<'_>, matrix: &DeviceBuffer<'_>, failed: &Rc<Cell
println!("QSA_RETAINED PAIR width={width} zero={zero} exact_words=14848");
}
/// The retained attend of one selected cell; the refusal cases share this call shape.
fn attend_one_cell<'ctx>(
context: &'ctx Context<'ctx>,
query: &[f32],
keys: &[u8],
values: &[u8],
failed: &Rc<Cell<bool>>,
) -> Result<QsaAttended<'ctx>> {
attend_retained(context, query, SelectedKvBytes { keys, values, width: 1 }, failed.clone())
}
/// The finite one-cell inputs the refusal cases start from.
struct RefusalInputs {
query: Vec<f32>,
@@ -146,14 +157,11 @@ fn prove_attend_refusals(context: &Context<'_>, failed: &Rc<Cell<bool>>, inputs:
let RefusalInputs { query, keys, values, .. } = inputs;
for width in [0, 2052] {
assert_eq!(
attend_retained(context, query, keys, values, width, failed.clone()).err(),
attend_retained(context, query, SelectedKvBytes { keys, values, width }, failed.clone()).err(),
Some(Error::InvalidDimension)
);
}
assert_eq!(
attend_retained(context, &query[..Q - 1], keys, values, 1, failed.clone()).err(),
Some(Error::InvalidDimension)
);
assert_eq!(attend_one_cell(context, &query[..Q - 1], keys, values, failed).err(), Some(Error::InvalidDimension));
prove_finite_refusals(context, failed, inputs);
}
@@ -162,22 +170,19 @@ fn prove_finite_refusals(context: &Context<'_>, failed: &Rc<Cell<bool>>, inputs:
let RefusalInputs { query, keys, values, .. } = inputs;
let mut bad_query = query.clone();
bad_query[Q - 1] = f32::from_bits(0x7fc00001);
assert_eq!(attend_retained(context, &bad_query, keys, values, 1, failed.clone()).err(), Some(Error::NonFinite));
assert_eq!(
attend_retained(context, query, &keys[..1022], values, 1, failed.clone()).err(),
Some(Error::InvalidDimension)
);
assert_eq!(attend_one_cell(context, &bad_query, keys, values, failed).err(), Some(Error::NonFinite));
assert_eq!(attend_one_cell(context, query, &keys[..1022], values, failed).err(), Some(Error::InvalidDimension));
let mut bad_keys = keys.clone();
bad_keys[1022..].copy_from_slice(&0x7c00u16.to_le_bytes());
assert_eq!(attend_retained(context, query, &bad_keys, values, 1, failed.clone()).err(), Some(Error::NonFinite));
assert_eq!(attend_one_cell(context, query, &bad_keys, values, failed).err(), Some(Error::NonFinite));
let mut bad_values = values.clone();
bad_values[1022..].copy_from_slice(&0x7e01u16.to_le_bytes());
assert_eq!(attend_retained(context, query, keys, &bad_values, 1, failed.clone()).err(), Some(Error::NonFinite));
assert_eq!(attend_one_cell(context, query, keys, &bad_values, failed).err(), Some(Error::NonFinite));
// All operands are finite, but the original F32 dot overflows. The actual
// retained attention's full D2H rejects before a gate can mask the failure.
let overflowing_keys = 0x7bffu16.to_le_bytes().repeat(512);
assert_eq!(
attend_retained(context, &vec![f32::MAX; Q], &0x7bffu16.to_le_bytes().repeat(512), values, 1, failed.clone())
.err(),
attend_one_cell(context, &vec![f32::MAX; Q], &overflowing_keys, values, failed).err(),
Some(Error::NonFinite)
);
assert_eq!(context.allocated_bytes(), 0);
@@ -190,11 +195,11 @@ fn prove_gate_refusals(context: &Context<'_>, foreign: &Context<'_>, failed: &Rc
bad_gate[Q - 1] = f32::NAN;
for malformed in [&bad_gate[..], &gate[..Q - 1]] {
let expected = if malformed.len() == Q { Error::NonFinite } else { Error::InvalidDimension };
let attended = attend_retained(context, query, keys, values, 1, failed.clone()).unwrap();
let attended = attend_one_cell(context, query, keys, values, failed).unwrap();
assert_eq!(gate_retained(context, attended, malformed).err(), Some(expected));
assert_eq!(context.allocated_bytes(), 0);
}
let attended = attend_retained(context, query, keys, values, 1, failed.clone()).unwrap();
let attended = attend_one_cell(context, query, keys, values, failed).unwrap();
assert_eq!(gate_retained(foreign, attended, gate).err(), Some(Error::IdentityMismatch));
assert_eq!(context.allocated_bytes(), 0);
assert_eq!(foreign.allocated_bytes(), 0);
@@ -202,7 +207,7 @@ fn prove_gate_refusals(context: &Context<'_>, foreign: &Context<'_>, failed: &Rc
fn prove_out_refusals(context: &Context<'_>, foreign: &Context<'_>, failed: &Rc<Cell<bool>>, inputs: &RefusalInputs) {
let RefusalInputs { query, gate, keys, values } = inputs;
let attended = attend_retained(context, query, keys, values, 1, failed.clone()).unwrap();
let attended = attend_one_cell(context, query, keys, values, failed).unwrap();
let gated = gate_retained(context, attended, gate).unwrap();
assert_eq!(gated.buffer(foreign).err(), Some(Error::IdentityMismatch));
let malformed = upload_bytes(context, &[0; 2]).unwrap();
@@ -238,7 +243,7 @@ fn prove_sticky_failure(
) {
let RefusalInputs { query, keys, values, .. } = inputs;
failed.set(true);
assert_eq!(attend_retained(context, query, keys, values, 1, failed.clone()).err(), Some(Error::CudaExecution));
assert_eq!(attend_one_cell(context, query, keys, values, failed).err(), Some(Error::CudaExecution));
assert_eq!(gated.buffer(context).err(), Some(Error::CudaExecution));
assert_eq!(
super::super::qsa_index::project_out_numeric(context, &matrix, QsaMatrixKind::Bf16, &gated, failed).err(),
@@ -230,9 +230,9 @@ impl<'ctx> QsaAttentionLease<'_, '_, 'ctx> {
selected: &mut QsaSelectedCache<'_>,
) -> Result<Box<[f32]>> {
let prepared = self.prepared;
self.slot
.buffers
.attend_by(prepared.q(), |q, y| selected.attend(&binding.identity(), context, prepared, q, y))?;
self.slot.buffers.attend_by(prepared.q(), |query, output| {
selected.attend(&binding.identity(), context, prepared, QsaAttendBuffers { query, output })
})?;
self.slot.buffers.gate(prepared.gate())?;
// Out source/cache acquisition is deliberately AFTER both finite boundaries.
let output = self.project_out(binding, context, cache)?;
@@ -11,19 +11,16 @@ fn bits(a: &[f32], b: &[f32]) {
}
}
type Products = (Box<[f32]>, Box<[f32]>, Box<[f32]>);
#[allow(clippy::too_many_arguments)] // Literal original-first component input tuple.
fn original(
context: &Context<'_>,
query: &[f32],
keys: &[u8],
values: &[u8],
kv: SelectedKvBytes<'_>,
gate: &[f32],
width: u32,
matrix: &DeviceBuffer<'_>,
) -> Result<Products> {
// Exact pre-existing retained producer FIRST, including original finite boundaries.
let failed = Rc::new(Cell::new(false));
let attended = attend_retained(context, query, keys, values, width, failed.clone())?;
let attended = attend_retained(context, query, kv, failed.clone())?;
let a = attended.values.clone();
let gated = gate_retained(context, attended, gate)?;
let g = gated.values().to_vec().into_boxed_slice();
@@ -123,7 +120,8 @@ impl<'a, 'c> Rig<'a, 'c> {
}
fn prove_case(&self, case: &Case) -> usize {
let (context, matrix) = (self.context, self.matrix);
let old = original(context, &case.query, &case.keys, &case.values, &case.gate, case.width, matrix).unwrap();
let kv = SelectedKvBytes { keys: &case.keys, values: &case.values, width: case.width };
let old = original(context, &case.query, kv, &case.gate, matrix).unwrap();
let k = upload_bytes(context, &case.keys).unwrap();
let v = upload_bytes(context, &case.values).unwrap();
let mut slot = self.buffers.borrow_mut();
@@ -162,7 +160,8 @@ impl<'a, 'c> Rig<'a, 'c> {
let (query, keys, values) = (&case.query, &case.keys, &case.values);
let mut bad_gate = case.gate.clone();
bad_gate[Q - 1] = invalid;
assert!(matches!(original(context, query, keys, values, &bad_gate, width, matrix), Err(Error::NonFinite)));
let kv = SelectedKvBytes { keys, values, width };
assert!(matches!(original(context, query, kv, &bad_gate, matrix), Err(Error::NonFinite)));
assert!(matches!(slot.gate(&bad_gate), Err(Error::NonFinite)));
slot.reset();
}
@@ -172,10 +171,8 @@ impl<'a, 'c> Rig<'a, 'c> {
let (query, keys, values) = (&case.query, &case.keys, &case.values);
let mut bad_query = query.clone();
bad_query[Q - 1] = invalid;
assert!(matches!(
original(context, &bad_query, keys, values, &case.gate, width, matrix),
Err(Error::NonFinite)
));
let kv = SelectedKvBytes { keys, values, width };
assert!(matches!(original(context, &bad_query, kv, &case.gate, matrix), Err(Error::NonFinite)));
assert!(matches!(
slot.attend_by(&bad_query, |_, _| panic!("query must refuse before CUDA callback")),
Err(Error::NonFinite)
@@ -5,12 +5,12 @@ use super::{
dense_weight_cache::{DenseWeightCache, QsaResident},
gr::ResidualReady,
qsa_index::{QsaPrior, driver_error, project, validate_values},
qsa_prompt_index::PromptIndexDevices,
session::QwenStepTxn,
};
use crate::model_binding::qwen4exp_input::{BindingIdentity, GrRole, ModelBinding, QsaMatrixRole, QsaWeights};
use leleka_cuda_driver::{
Context, DeviceBuffer, NativeBatchWorkspace, QsaChunkRows, QsaIndexPrior, QsaPromptIndexPrefix,
QsaPromptIndexWorkspace, QsaPromptSelection,
Context, DeviceBuffer, QsaChunkRows, QsaIndexPrior, QsaPromptIndexPrefix, QsaPromptSelection,
};
use std::rc::Rc;
fn driver(error: leleka_cuda_driver::Error) -> Error {
@@ -19,6 +19,13 @@ fn driver(error: leleka_cuda_driver::Error) -> Error {
other => driver_error(other),
}
}
/// The model binding, dense weight cache and step transaction a decode index is built and checked against.
#[derive(Clone, Copy)]
pub(super) struct DecodeStepOwners<'a, 'ctx, 'session, 'driver> {
pub(super) binding: &'a ModelBinding,
pub(super) cache: &'a DenseWeightCache<'ctx>,
pub(super) txn: &'a QwenStepTxn<'session, 'driver>,
}
pub(super) struct QsaDecodeIndex<'source, 'lease, 'ctx> {
binding: BindingIdentity,
context: &'ctx Context<'ctx>,
@@ -31,24 +38,21 @@ pub(super) struct QsaDecodeIndex<'source, 'lease, 'ctx> {
selected: QsaPromptSelection<'lease, 'ctx>,
}
impl<'source, 'lease, 'ctx> QsaDecodeIndex<'source, 'lease, 'ctx> {
#[allow(clippy::too_many_arguments)] // Actual current transaction, immutable prior and two model owners.
pub(super) fn prepare(
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
owners: DecodeStepOwners<'_, 'ctx, '_, '_>,
layer: LayerId,
input: &'source ResidualReady,
prior: &QsaPrior,
owner: &'lease mut QsaPromptIndexWorkspace<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
devices: PromptIndexDevices<'lease, '_, 'ctx>,
) -> Result<Self> {
let DecodeStepOwners { binding, cache, txn } = owners;
Self::admit_step(binding, txn, layer, input, prior)?;
let context = cache.retained_context(binding, txn.cuda_context()?)?;
let entry = Self::checked_entry(cache, binding, layer)?;
let txn_owner = txn.residual_handoff_owner()?;
let rows = DecodeRows::project(context, binding, entry, input, cache)?;
let gate = rows.gate()?;
let selected = Self::select(owner, workspace, (txn, prior), cache, entry, &rows)?;
let selected = Self::select(devices, (txn, prior), cache, entry, &rows)?;
let result = Self {
binding: binding.identity(),
context,
@@ -106,13 +110,13 @@ impl<'source, 'lease, 'ctx> QsaDecodeIndex<'source, 'lease, 'ctx> {
}
/// The index append and the block selection of the step's position on the prompt index workspace.
fn select(
owner: &'lease mut QsaPromptIndexWorkspace<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
devices: PromptIndexDevices<'lease, '_, 'ctx>,
(txn, prior): (&QwenStepTxn<'_, '_>, &QsaPrior),
cache: &DenseWeightCache<'ctx>,
entry: &QsaResident,
rows: &DecodeRows,
) -> Result<QsaPromptSelection<'lease, 'ctx>> {
let PromptIndexDevices { owner, workspace } = devices;
let (pooled, tail, dead) = prior.native_index_image()?;
let p = u32::try_from(txn.position().get()).map_err(|_| Error::InvalidPosition)?;
let gamma = cache.qsa_norms(entry)?;
@@ -18,7 +18,7 @@ mod index_resident;
pub(super) use index_resident::QsaIndexKeyCache;
#[path = "qsa_selected_cache.rs"]
mod selected_cache;
pub(super) use selected_cache::QsaSelectedCache;
pub(super) use selected_cache::{QsaAttendBuffers, QsaSelectedCache};
#[path = "qsa_input_scratch.rs"]
mod input_scratch;
pub(super) use input_scratch::{QsaInputLease, QsaInputScratch};
@@ -2,12 +2,14 @@
//! snapshots/index prefixes are the actual completed driver products; no host
//! residual or query/selection certificate is fabricated.
use super::super::dense_weight_cache::QsaResident;
use super::super::qsa_attention::PromptDevices;
use super::super::qsa_prompt_index::PromptChunkOwners;
use super::super::session::{TargetStepOrigin, chunk::QwenChunkTxn};
use super::*;
use leleka_cuda_driver::{
CompletedQsaKvAppend, NativeBatchWorkspace, OriginalDeviceBlock, OriginalDeviceGrRead, OriginalQsaDeviceSelection,
OriginalQsaPromptDevice, OriginalQsaPromptWeights, QsaChunkPrior, QsaIndexPrior, QsaKvAppendTarget, QsaNativeKind,
QsaNativeWeight, QsaPromptAttention, QsaPromptIndexState, QsaPromptKv, QsaPromptStage,
QsaNativeWeight, QsaPromptIndexState, QsaPromptKv,
};
const ROLES: [QsaMatrixRole; 6] = [
QsaMatrixRole::K,
@@ -223,17 +225,13 @@ impl<'lease, 'arena, 'loan, 'ctx> PromptDeviceQsaSelection<'lease, 'arena, 'loan
let (out, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?;
Ok((context, out, kind))
}
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn complete(
self,
model: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
chunk: &QwenChunkTxn<'_, '_>,
workspace: &mut NativeBatchWorkspace<'ctx>,
kv: &mut QsaPromptKv<'ctx>,
stage: &mut QsaPromptStage<'ctx>,
attention: &mut QsaPromptAttention<'ctx>,
owners: PromptChunkOwners<'_, 'ctx, '_, '_>,
devices: PromptDevices<'_, 'ctx>,
) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, PromptDeviceQsaState<'ctx>)> {
let PromptChunkOwners { binding: model, cache, chunk } = owners;
let PromptDevices { kv, stage, attention, workspace } = devices;
let (ctx, out, kind) = self.check_inputs(model, cache, chunk)?;
let Self { binding, origin, context, layer, prior, provider, identities, selected } = self;
let snapshot = prior.native_snapshot(kv)?;
@@ -24,6 +24,18 @@ fn driver(e: leleka_cuda_driver::Error) -> Error {
other => super::qsa_index::driver_error(other),
}
}
/// The model binding, dense weight cache and chunk transaction a prompt chunk's QSA batch is built and checked against.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct PromptChunkOwners<'a, 'ctx, 'session, 'driver> {
pub(in crate::qwen_forward) binding: &'a ModelBinding,
pub(in crate::qwen_forward) cache: &'a DenseWeightCache<'ctx>,
pub(in crate::qwen_forward) chunk: &'a QwenChunkTxn<'session, 'driver>,
}
/// The index workspace a batch leases and the native batch workspace its append and select run on.
pub(in crate::qwen_forward) struct PromptIndexDevices<'lease, 'a, 'ctx> {
pub(in crate::qwen_forward) owner: &'lease mut QsaPromptIndexWorkspace<'ctx>,
pub(in crate::qwen_forward) workspace: &'a mut NativeBatchWorkspace<'ctx>,
}
pub(super) struct PromptIndexBatch<'source, 'lease, 'ctx> {
binding: BindingIdentity,
origin: TargetStepOrigin,
@@ -37,6 +49,7 @@ pub(super) struct PromptIndexBatch<'source, 'lease, 'ctx> {
}
/// Host images of one prompt chunk, filled row by row from the native projections.
struct PromptHost {
rows: usize,
raw: Vec<f32>,
k: Vec<f32>,
v: Vec<f32>,
@@ -46,8 +59,15 @@ struct PromptHost {
}
impl PromptHost {
fn reserve(t: usize) -> Result<Self> {
let mut host =
Self { raw: Vec::new(), k: Vec::new(), v: Vec::new(), qfull: Vec::new(), iq: Vec::new(), gate: Vec::new() };
let mut host = Self {
rows: t,
raw: Vec::new(),
k: Vec::new(),
v: Vec::new(),
qfull: Vec::new(),
iq: Vec::new(),
gate: Vec::new(),
};
for (x, n) in [
(&mut host.raw, t * 128),
(&mut host.k, t * 512),
@@ -94,15 +114,16 @@ impl PromptHost {
}
Ok(())
}
/// Appends and selects the chunk that starts at the prior's next position.
fn append_select<'lease, 'ctx>(
&self,
owner: &'lease mut QsaPromptIndexWorkspace<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
devices: PromptIndexDevices<'lease, '_, 'ctx>,
cache: &DenseWeightCache<'ctx>,
entry: &QsaResident,
prior: &QsaPrior,
(first, t): (u64, usize),
) -> Result<QsaPromptSelection<'lease, 'ctx>> {
let PromptIndexDevices { owner, workspace } = devices;
let (first, t) = (prior.next_position(), self.rows);
let (pooled, tail, dead) = prior.native_index_image()?;
let gamma = cache.qsa_norms(entry)?;
let prior = QsaIndexPrior { pooled: &pooled, tail: &tail, dead: &dead };
@@ -202,21 +223,18 @@ fn gather_prompt<'source, 'ctx>(
host.validate(t)?;
Ok((sources, host))
}
#[allow(clippy::too_many_arguments)] // Actual whole chunk/current prior and admitted fixed owners.
pub(super) fn prepare<'source, 'lease, 'ctx>(
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
chunk: &QwenChunkTxn<'_, '_>,
owners: PromptChunkOwners<'_, 'ctx, '_, '_>,
layer: LayerId,
prior: &QsaPrior,
rows: &mut [NativeProjectionRow<'source, 'ctx>],
owner: &'lease mut QsaPromptIndexWorkspace<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
devices: PromptIndexDevices<'lease, '_, 'ctx>,
) -> Result<PromptIndexBatch<'source, 'lease, 'ctx>> {
let PromptChunkOwners { binding, cache, chunk } = owners;
let (context, entry, origin, first) =
index_guards(binding, cache, chunk, (layer, prior), (rows, owner.capacity()))?;
index_guards(binding, cache, chunk, (layer, prior), (rows, devices.owner.capacity()))?;
let (sources, host) = gather_prompt(rows, binding, cache, chunk, (layer, first))?;
let selected = host.append_select(owner, workspace, cache, entry, prior, (first, rows.len()))?;
let selected = host.append_select(devices, cache, entry, prior)?;
chunk.validate_prompt_qsa_prior(layer, prior)?;
cache.retained_context(binding, context)?;
origin.validate(chunk.original_session()?)?;
@@ -153,6 +153,12 @@ fn install_misses(
Ok(Plan { next, misses, k, v, selected })
}
/// The uploaded query a selected-cache attend pass reads and the output buffer it writes.
pub(in crate::qwen_forward) struct QsaAttendBuffers<'a, 'ctx> {
pub(in crate::qwen_forward) query: &'a DeviceBuffer<'ctx>,
pub(in crate::qwen_forward) output: &'a mut DeviceBuffer<'ctx>,
}
pub(in crate::qwen_forward) struct QsaSelectedCache<'ctx> {
binding: BindingIdentity,
context: &'ctx Context<'ctx>,
@@ -252,9 +258,9 @@ impl<'ctx> QsaSelectedCache<'ctx> {
binding: &BindingIdentity,
context: &Context<'_>,
prepared: &QsaPrepared,
query: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
buffers: QsaAttendBuffers<'_, '_>,
) -> Result<()> {
let QsaAttendBuffers { query, output } = buffers;
let (layer, slot) = self.admit_attend(binding, context, prepared)?;
let plan = plan(&self.layers[slot], &prepared.candidate, &prepared.ids)?;
let workspace = self.workspace.as_mut().ok_or(Error::CudaExecution)?;