STRA-338 params h03: QSA native batch, prompt attention, index, device and resident owners take domain structs (LaunchGeometry, QsaAttendedKv, QsaIndexPrior, QsaChunkRows, ArenaRows, ...)

This commit is contained in:
Pavlo Ratushnyi
2026-11-08 01:01:58 +01:00
parent 4b04c24981
commit 05b134c3b0
57 changed files with 633 additions and 383 deletions
+1 -1
View File
@@ -17,7 +17,7 @@
//! `cargo test -p leleka-cuda-driver --features cuda-driver --lib -- --ignored kv_stream_gpu`
use crate::qsa_prompt_attention_ffi::{Arg, Arguments, Module};
use crate::qsa_prompt_host_ffi::MappedAllocation;
use crate::qsa_prompt_resolver::Resolver;
use crate::qsa_prompt_resolver::{PoolAddresses, Resolver, SelectedRows};
use crate::{Context, DeviceBuffer, Driver, NativeBatchWorkspace, Result, combine};
use leleka_experimental_ref::{f16::f16_from_f32, kv_q8};
@@ -45,7 +45,12 @@ pub(super) fn launch(
) -> Result<()> {
let mut a = Arguments::new(args)?;
let g = c.enter()?;
let op = m.launch(index, grid, block, 0, w.blas()?.stream(), &mut a);
let op = m.launch(
index,
crate::qsa_prompt_attention_ffi::LaunchGeometry::new(grid, block, 0),
w.blas()?.stream(),
&mut a,
);
let sync = w.blas()?.synchronize();
combine(combine(op, sync), g.finish())
}
@@ -230,7 +230,14 @@ impl<'c> Stream<'c> {
let named = self.attention.load_call(&mut self.rng, n, near);
let (ids, steps) = (addr(&self.attention.ids), addr(&self.attention.steps));
let table = addr(&self.pools.table);
self.resolver.resolve(&mut self.w, table, ids, steps, n, self.host, self.res_addr).expect("resolve");
self.resolver
.resolve(
&mut self.w,
table,
SelectedRows { ids, steps, row_count: n },
PoolAddresses { host: self.host, resident: self.res_addr },
)
.expect("resolve");
self.counts.calls += 1;
self.check_resident(call, &named);
self.compare_attention(call, n);
@@ -116,7 +116,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
) -> Result<()> {
let [k, v] = p.kv;
let guard = Arguments::new(vec![Arg::U64(k), Arg::U64(v), Arg::I32((p.t * 512) as i32), Arg::U64(p.sa)])?;
stage.run(workspace, 0, [(p.t * 512).div_ceil(256) as u32, 1, 1], 256, guard)?;
stage.run(workspace, 0, LaunchGeometry::new([(p.t * 512).div_ceil(256) as u32, 1, 1], 256, 0), guard)?;
if stage.flags()? != 0 {
return Err(Error::InvalidQ8Activation);
}
@@ -143,8 +143,8 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
self.owner.current = None;
self.owner.mapped_current = None;
stage.run(workspace, 1, [p.t as u32, 2, 8], 64, args)?;
stage.run(workspace, 2, [1, 1, 1], 256, scales)?;
stage.run(workspace, 1, LaunchGeometry::new([p.t as u32, 2, 8], 64, 0), args)?;
stage.run(workspace, 2, LaunchGeometry::new([1, 1, 1], 256, 0), scales)?;
if stage.flags()? != 0 {
return Err(Error::InvalidQ8Activation);
}
@@ -127,10 +127,9 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
prefix: &OriginalQsaMappedPrefix,
ids: &DeviceBuffer<'_>,
steps: &DeviceBuffer<'_>,
t: usize,
inputs: &crate::QsaAttentionInputs<'_, '_>,
) -> Result<([u64; 4], u64, usize)> {
let (ids, steps, t) = (inputs.ids, inputs.steps, inputs.t);
self.validate_prefix(prefix)?;
w.validate_context(self.owner.context)?;
if !(1..=3).contains(&t) {
@@ -156,7 +155,8 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
self.resolver_ready = true;
}
let resolver = self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?;
let result = resolver.resolve(w, table, ids, steps, t, host, resident);
let result =
resolver.resolve(w, table, SelectedRows { ids, steps, row_count: t }, PoolAddresses { host, resident });
if result.is_err() && self.owner.context.is_poisoned() {
self.failed = true;
}
@@ -30,6 +30,21 @@ pub struct QsaNativeProjections {
pub index_k: Box<[f32]>,
pub index_q: Box<[f32]>,
}
/// The five input-projection weights (K, V, Q, index-K, index-Q) and the quantization of the first three.
pub struct QsaInputWeights<'a, 'b> {
pub weights: [&'a DeviceBuffer<'b>; 5],
pub kinds: [QsaNativeKind; 3],
}
/// The Out projection input: the attended rows and their gates, `t * 6144` values each.
pub struct QsaGatedAttention<'a> {
pub attended: &'a [f32],
pub gates: &'a [f32],
}
/// A weight buffer and its quantization.
pub struct QsaNativeWeight<'a, 'b> {
pub buffer: &'a DeviceBuffer<'b>,
pub kind: QsaNativeKind,
}
pub struct QsaNativeBatchWorkspace<'ctx> {
capacity: usize,
sizes: [usize; 8],
@@ -4,17 +4,15 @@
use super::*;
impl<'ctx> QsaNativeBatchWorkspace<'ctx> {
#[allow(clippy::too_many_arguments)] // Closed role shapes, not arbitrary GEMM.
// Closed role shapes, not arbitrary GEMM.
pub(super) fn project(
&mut self,
t: usize,
n: usize,
k: usize,
weight: ffi::BufferHandle,
kind: Option<QsaNativeKind>,
out_gate: bool,
shape: ProjectionShape,
role: ProjectionWeight,
ws: &mut NativeBatchWorkspace<'ctx>,
) -> Result<Box<[f32]>> {
let ProjectionShape { token_count: t, output_width: n, input_width: k } = shape;
let ProjectionWeight { handle: weight, kind, is_gated_out: out_gate } = role;
let blas = ws.blas()?;
let context = self.context;
let io = self.project_io((t, n, k))?;
@@ -145,14 +143,15 @@ impl<'ctx> QsaNativeBatchWorkspace<'ctx> {
}
Ok(())
}
/// The five whole-batch input projections (K, V, Q, index-K, index-Q) of `mixed`.
pub fn project_inputs(
&mut self,
t: usize,
mixed: &[f32],
weights: [&DeviceBuffer<'_>; 5],
kinds: [QsaNativeKind; 3],
inputs: QsaInputWeights<'_, '_>,
ws: &mut NativeBatchWorkspace<'ctx>,
) -> Result<QsaNativeProjections> {
let QsaInputWeights { weights, kinds } = inputs;
self.admit(t, &weights, ws)?;
if mixed.len() != t * 2560 {
return Err(Error::InvalidQwenShape);
@@ -187,22 +186,26 @@ impl<'ctx> QsaNativeBatchWorkspace<'ctx> {
kinds: [QsaNativeKind; 3],
ws: &mut NativeBatchWorkspace<'ctx>,
) -> Result<QsaNativeProjections> {
let k = self.project(t, 512, 2560, handles[0], Some(kinds[0]), false, ws)?;
let v = self.project(t, 512, 2560, handles[1], Some(kinds[1]), false, ws)?;
let q = self.project(t, 12288, 2560, handles[2], Some(kinds[2]), false, ws)?;
let index_k = self.project(t, 128, 2560, handles[3], None, false, ws)?;
let index_q = self.project(t, 512, 2560, handles[4], None, false, ws)?;
let k =
self.project(ProjectionShape::inputs(t, 512), ProjectionWeight::input(handles[0], Some(kinds[0])), ws)?;
let v =
self.project(ProjectionShape::inputs(t, 512), ProjectionWeight::input(handles[1], Some(kinds[1])), ws)?;
let q =
self.project(ProjectionShape::inputs(t, 12288), ProjectionWeight::input(handles[2], Some(kinds[2])), ws)?;
let index_k = self.project(ProjectionShape::inputs(t, 128), ProjectionWeight::input(handles[3], None), ws)?;
let index_q = self.project(ProjectionShape::inputs(t, 512), ProjectionWeight::input(handles[4], None), ws)?;
Ok(QsaNativeProjections { k, v, q, index_k, index_q })
}
/// The gated Out projection of the attended rows.
pub fn project_out(
&mut self,
t: usize,
attended: &[f32],
gates: &[f32],
weight: &DeviceBuffer<'_>,
kind: QsaNativeKind,
rows: QsaGatedAttention<'_>,
out: QsaNativeWeight<'_, '_>,
ws: &mut NativeBatchWorkspace<'ctx>,
) -> Result<Box<[f32]>> {
let QsaGatedAttention { attended, gates } = rows;
let QsaNativeWeight { buffer: weight, kind } = out;
self.admit(t, &[weight], ws)?;
if attended.len() != t * 6144 || gates.len() != t * 6144 {
return Err(Error::InvalidQwenShape);
@@ -213,7 +216,7 @@ impl<'ctx> QsaNativeBatchWorkspace<'ctx> {
let w = self.weight(weight, 2560, 6144, Some(kind))?;
self.upload(1, attended)?;
self.upload(2, gates)?;
self.project(t, 2560, 6144, w, Some(kind), true, ws)
self.project(ProjectionShape::new(t, 2560, 6144), ProjectionWeight::out(w, kind), ws)
}
pub fn close(mut self) -> Result<()> {
self.close_inner()
@@ -248,6 +251,44 @@ impl Drop for QsaNativeBatchWorkspace<'_> {
}
}
/// The shape of one projection: `t` rows of `k` inputs to `n` outputs.
#[derive(Clone, Copy)]
pub(super) struct ProjectionShape {
token_count: usize,
output_width: usize,
input_width: usize,
}
impl ProjectionShape {
/// A projection of `token_count` rows of `input_width` values to `output_width` values.
fn new(token_count: usize, output_width: usize, input_width: usize) -> Self {
Self { token_count, output_width, input_width }
}
/// An input projection of the 2560-wide mixed activations.
fn inputs(token_count: usize, output_width: usize) -> Self {
Self { token_count, output_width, input_width: 2560 }
}
}
/// The weight of one projection, its quantization (`None`: BF16) and whether it is the gated Out projection.
#[derive(Clone, Copy)]
pub(super) struct ProjectionWeight {
handle: ffi::BufferHandle,
kind: Option<QsaNativeKind>,
is_gated_out: bool,
}
impl ProjectionWeight {
/// One of the five input projections (`kind` `None`: BF16 index weights).
fn input(handle: ffi::BufferHandle, kind: Option<QsaNativeKind>) -> Self {
Self { handle, kind, is_gated_out: false }
}
/// The gated Out projection.
fn out(handle: ffi::BufferHandle, kind: QsaNativeKind) -> Self {
Self { handle, kind: Some(kind), is_gated_out: true }
}
}
/// The device spans one projection reads and writes: activations, packed halves, output, F16 scratch and the status.
struct ProjectIo {
x: ffi::BufferHandle,
+12 -13
View File
@@ -1,7 +1,7 @@
//! Literal Original INT8 split-K decode/target-MTP attention, T1..3 (actual target/MTP miss-list bound).
//! Completion attests real full scans and a drained actual stream, not row provenance.
use crate::qsa_prompt_attention::QsaAttentionInputs;
use crate::qsa_prompt_attention_ffi::{Arg, Arguments, Module};
use crate::qsa_prompt_attention_ffi::{Arg, Arguments, LaunchGeometry, Module};
use crate::qsa_prompt_kv::{QsaKvSnapshot, QsaPromptKv, checked};
use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine};
pub const QSA_NATIVE_DECODE_BYTES: usize = 53_899_268; //52,326,400B scratch +1,572,864B output +4B status
@@ -88,25 +88,24 @@ impl<'ctx> QsaNativeDecode<'ctx> {
fn launch_pass(
&self,
w: &NativeBatchWorkspace<'ctx>,
(index, grid, block, shared): (usize, [u32; 3], u32, u32),
(index, geometry): (usize, LaunchGeometry),
a: &mut Arguments,
) -> Result<()> {
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(index, grid, block, shared, w.blas()?.stream(), a)
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(index, geometry, w.blas()?.stream(), a)
}
/// Runs kernel `index` of the decode module on the workspace stream under the failure bookkeeping of the decode.
fn run(
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
index: usize,
grid: [u32; 3],
block: u32,
shared: u32,
geometry: LaunchGeometry,
mut a: Arguments,
) -> Result<()> {
self.validate()?;
w.validate_context(self.context)?;
let g = self.enter_or_fail(w)?;
let dependency = self.context.driver.api.synchronize();
let op = dependency.and_then(|()| self.launch_pass(w, (index, grid, block, shared), &mut a));
let op = dependency.and_then(|()| self.launch_pass(w, (index, geometry), &mut a));
let sync = w.blas()?.synchronize();
let pop = g.finish();
if sync.is_err() || pop.is_err() {
@@ -129,14 +128,14 @@ impl<'ctx> QsaNativeDecode<'ctx> {
snapshot: &'loan QsaKvSnapshot,
inputs: &QsaAttentionInputs<'_, '_>,
) -> Result<QsaNativeDecodeCompletion<'loan, 'ctx>> {
let (ids, steps, t) = (inputs.ids, inputs.steps, inputs.t);
let t = inputs.t;
self.validate()?;
w.validate_context(self.context)?;
kv.validate_context(self.context)?;
kv.validate_snapshot(snapshot)?;
let handles = self.admit_inputs(w, inputs, |b| kv.reject_alias(b))?;
let (status, out) = self.guard_pass(w, handles, (t, snapshot.next_position()))?;
let (pools, table, _) = kv.resolved_addresses(w, snapshot, ids, steps, t)?;
let (pools, table, _) = kv.resolved_addresses(w, snapshot, inputs)?;
self.attention_passes(w, (pools, table), handles, (status, out, t))?;
Ok(QsaNativeDecodeCompletion { owner: self, _kv: kv, _snapshot: snapshot, t })
}
@@ -203,7 +202,7 @@ impl<'ctx> QsaNativeDecode<'ctx> {
Arg::I32(end as i32),
Arg::U64(status),
])?;
self.run(w, 0, [64, 1, 1], 256, 0, guard)?;
self.run(w, 0, LaunchGeometry::new([64, 1, 1], 256, 0), guard)?;
let flags = self.flags()?;
if flags & 2 != 0 {
return Err(Error::InvalidQwenShape);
@@ -244,11 +243,11 @@ impl<'ctx> QsaNativeDecode<'ctx> {
chunk.extend(pools.map(Arg::U64));
chunk.extend([Arg::U64(table), Arg::U64(ih), Arg::U64(sh), Arg::I32(2), Arg::I32(4), Arg::F32(1.0 / 16.0)]);
chunk.extend([Arg::U64(pa), Arg::U64(pm), Arg::U64(pl), Arg::I32(33), Arg::I32(2051), Arg::I64(204400)]);
self.run(w, 1, [33, 2, t as u32], 256, 0, Arguments::new(chunk)?)?;
self.run(w, 1, LaunchGeometry::new([33, 2, t as u32], 256, 0), Arguments::new(chunk)?)?;
let merge = vec![Arg::U64(pa), Arg::U64(pm), Arg::U64(pl), Arg::I32(33), Arg::U64(out), Arg::I64(204400)];
self.run(w, 2, [24, t as u32, 1], 256, 0, Arguments::new(merge)?)?;
self.run(w, 2, LaunchGeometry::new([24, t as u32, 1], 256, 0), Arguments::new(merge)?)?;
let scan = Arguments::new(vec![Arg::U64(out), Arg::I32((t * 6144) as i32), Arg::U64(status)])?;
self.run(w, 3, [64, 1, 1], 256, 0, scan)?;
self.run(w, 3, LaunchGeometry::new([64, 1, 1], 256, 0), scan)?;
if self.flags()? != 0 {
return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention"));
}
+7 -2
View File
@@ -1,6 +1,6 @@
//! Literal selected Original decode F32 sigmoid/multiply, not the DOUBLE fallback
//! or prompt FP16 gate. The caller retains actual full finite readbacks.
use crate::qsa_prompt_attention_ffi::{Arg, Arguments, Module};
use crate::qsa_prompt_attention_ffi::{Arg, Arguments, LaunchGeometry, Module};
use crate::qsa_prompt_kv::checked;
use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine};
@@ -72,7 +72,12 @@ impl<'ctx> QsaNativeGate<'ctx> {
self.settle_launch(workspace, (launch, sync, pop), arguments)
}
fn launch_gate(&self, stream: usize, arguments: &mut Arguments) -> Result<()> {
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(0, [24, 1, 1], 256, 0, stream, arguments)
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(
0,
LaunchGeometry::new([24, 1, 1], 256, 0),
stream,
arguments,
)
}
/// All three operands are this context's whole 6144-word owners and none aliases the workspace or another operand.
fn admit_operands(
@@ -1,6 +1,6 @@
//! Literal Original selected INT8 v2 MMA/exp2 prompt attention, admitted T1..8192.
//! Completion attests real full scans and a drained actual stream, not row provenance.
use crate::qsa_prompt_attention_ffi::{Arg, Arguments, Module};
use crate::qsa_prompt_attention_ffi::{Arg, Arguments, LaunchGeometry, Module};
use crate::qsa_prompt_attention_select::{
DeviceCaps, PoolPresence, PromptAttnKernel, SelectSwitches, Shapes, VARIANT_ENTRIES, select,
};
@@ -13,6 +13,13 @@ pub struct QsaAttentionInputs<'loan, 'buffers> {
pub(crate) steps: &'loan DeviceBuffer<'buffers>,
pub(crate) t: usize,
}
/// The prompt KV one attention pass reads: the stage owning the current pools, the KV, and the snapshot fixing its
/// extent. They travel together because the attention addresses the pools through all three.
pub struct QsaAttendedKv<'loan, 'kv, 'ctx> {
pub stage: &'loan QsaPromptStage<'ctx>,
pub kv: &'kv QsaPromptKv<'ctx>,
pub snapshot: &'loan QsaKvSnapshot,
}
pub const QSA_PROMPT_ATTENTION_BYTES: usize = 1_572_868; //64*6144 F32 +4B status
pub struct QsaPromptAttention<'ctx> {
capacity: usize,
@@ -39,6 +46,7 @@ mod device_attention;
#[path = "qsa_resident_attention.rs"]
mod resident_attention;
pub(crate) use resident_attention::OriginalQsaAttendedKv;
pub use resident_attention::OriginalQsaResidentAttention;
mod impl_drop_for_qsapromptattention;
@@ -12,6 +12,20 @@ pub(super) struct KernelPlan {
pub(super) shared: u32,
}
/// The module (default or variants) and the entry index inside it that one kernel launch runs.
#[derive(Clone, Copy)]
pub(super) struct KernelEntry {
pub(super) is_variants_module: bool,
pub(super) index: usize,
}
impl KernelPlan {
/// The launch target of entry `index` of this plan's module.
pub(super) fn entry(&self, index: usize) -> KernelEntry {
KernelEntry { is_variants_module: self.variants, index }
}
}
/// 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],
@@ -24,12 +38,9 @@ pub(super) struct AttnPasses {
/// `run_in` or `run_resident`: they differ in their validation and in the failure bookkeeping.
pub(super) type Runner<'ctx> = fn(
&mut QsaPromptAttention<'ctx>,
bool,
KernelEntry,
&mut NativeBatchWorkspace<'ctx>,
usize,
[u32; 3],
u32,
u32,
LaunchGeometry,
Arguments,
) -> Result<()>;
@@ -82,36 +82,27 @@ impl<'ctx> QsaPromptAttention<'ctx> {
/// 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,
entry: KernelEntry,
w: &NativeBatchWorkspace<'ctx>,
(index, grid, block, shared): (usize, [u32; 3], u32, u32),
geometry: LaunchGeometry,
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,
)
let module = if entry.is_variants_module { self.variants.as_ref() } else { self.module.as_ref() };
module.ok_or(Error::ContextPoisoned)?.launch(entry.index, geometry, w.blas()?.stream(), a)
}
#[allow(clippy::too_many_arguments)]
/// Runs one launch of the attention module under the failure bookkeeping of the prompt (non-resident) owner.
pub(in super::super) fn run_in(
&mut self,
variants: bool,
entry: KernelEntry,
w: &mut NativeBatchWorkspace<'ctx>,
index: usize,
grid: [u32; 3],
block: u32,
shared: u32,
geometry: LaunchGeometry,
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 op = dependency.and_then(|()| self.launch_variant(entry, w, geometry, &mut a));
let sync = w.blas()?.synchronize();
let pop = g.finish();
if sync.is_err() || pop.is_err() {
@@ -130,12 +121,10 @@ impl<'ctx> QsaPromptAttention<'ctx> {
pub fn attend<'loan>(
&'loan mut self,
w: &mut NativeBatchWorkspace<'ctx>,
stage: &'loan QsaPromptStage<'ctx>,
kv: &QsaPromptKv<'ctx>,
snapshot: &'loan QsaKvSnapshot,
kv: QsaAttendedKv<'loan, '_, 'ctx>,
inputs: &QsaAttentionInputs<'_, '_>,
) -> Result<QsaPromptAttentionCompletion<'loan, 'ctx>> {
self.attend_kernel(PromptAttnKernel::Int8V2, w, stage, kv, snapshot, inputs)
self.attend_kernel(PromptAttnKernel::Int8V2, w, kv, 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.
@@ -143,9 +132,7 @@ impl<'ctx> QsaPromptAttention<'ctx> {
pub fn attend_selected<'loan>(
&'loan mut self,
w: &mut NativeBatchWorkspace<'ctx>,
stage: &'loan QsaPromptStage<'ctx>,
kv: &QsaPromptKv<'ctx>,
snapshot: &'loan QsaKvSnapshot,
kv: QsaAttendedKv<'loan, '_, 'ctx>,
inputs: &QsaAttentionInputs<'_, '_>,
switches: SelectSwitches,
) -> Result<QsaPromptAttentionCompletion<'loan, 'ctx>> {
@@ -153,7 +140,7 @@ impl<'ctx> QsaPromptAttention<'ctx> {
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)
self.attend_kernel(kernel, w, kv, 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.
@@ -8,11 +8,10 @@ impl<'ctx> QsaPromptAttention<'ctx> {
&'loan mut self,
kernel: PromptAttnKernel,
w: &mut NativeBatchWorkspace<'ctx>,
stage: &'loan QsaPromptStage<'ctx>,
kv: &QsaPromptKv<'ctx>,
snapshot: &'loan QsaKvSnapshot,
attended: QsaAttendedKv<'loan, '_, 'ctx>,
inputs: &QsaAttentionInputs<'_, '_>,
) -> Result<QsaPromptAttentionCompletion<'loan, 'ctx>> {
let QsaAttendedKv { stage, kv, snapshot } = attended;
let plan = self.ensure_plan(kernel)?;
let t = inputs.t;
self.validate_stage(w, stage)?;
@@ -128,15 +127,16 @@ impl<'ctx> QsaPromptAttention<'ctx> {
run: Runner<'ctx>,
) -> Result<()> {
let [qh, ih, sh, out, status] = p.addrs;
let (v, t) = (plan.variants, p.t);
let t = 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 attention = LaunchGeometry::new([t as u32, 2, 1], 128, plan.shared);
run(self, plan.entry(plan.attn_ix), w, attention, 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)?;
run(self, plan.entry(plan.scan_ix), w, LaunchGeometry::new([guard_grid(t), 1, 1], 256, 0), scan)?;
if self.flags()? != 0 {
return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention"));
}
@@ -162,7 +162,7 @@ impl<'ctx> QsaPromptAttention<'ctx> {
end,
Arg::U64(status),
])?;
run(self, plan.variants, w, plan.guard_ix, [guard_grid(t), 1, 1], 256, 0, guard)?;
run(self, plan.entry(plan.guard_ix), w, LaunchGeometry::new([guard_grid(t), 1, 1], 256, 0), guard)?;
let flags = self.flags()?;
if flags & 2 != 0 {
return Err(Error::InvalidQwenShape);
@@ -8,6 +8,20 @@ pub(crate) enum Arg {
I64(i64),
F32(f32),
}
/// Grid, block size and dynamic shared memory of one kernel launch: the launch extent the kernel runs with.
#[derive(Clone, Copy)]
pub(crate) struct LaunchGeometry {
pub(crate) grid: [u32; 3],
pub(crate) block: u32,
pub(crate) shared_bytes: u32,
}
impl LaunchGeometry {
/// The launch extent `grid` blocks of `block` threads with `shared_bytes` of dynamic shared memory.
#[inline]
pub(crate) const fn new(grid: [u32; 3], block: u32, shared_bytes: u32) -> Self {
Self { grid, block, shared_bytes }
}
}
pub(crate) struct Arguments {
values: Box<[Arg]>,
pointers: Vec<*mut c_void>,
@@ -153,12 +167,11 @@ mod enabled {
pub(crate) fn launch(
&self,
index: usize,
grid: [u32; 3],
block: u32,
shared: u32,
geometry: LaunchGeometry,
stream: usize,
args: &mut Arguments,
) -> Result<()> {
let LaunchGeometry { grid, block, shared_bytes: shared } = geometry;
if grid.contains(&0)
|| !matches!(block, 64 | 128 | 256 | 1024)
|| !matches!(shared, 0 | 45584 | 37904 | 46096 | 54288)
@@ -254,7 +267,7 @@ impl Module {
pub(crate) fn caps(&self) -> [u32; 3] {
[0; 3]
}
pub(crate) fn launch(&self, _: usize, _: [u32; 3], _: u32, _: u32, _: usize, _: &mut Arguments) -> Result<()> {
pub(crate) fn launch(&self, _: usize, _: LaunchGeometry, _: usize, _: &mut Arguments) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn close(self) -> Result<()> {
+31 -3
View File
@@ -5,8 +5,8 @@ use crate::original_prefill_arena::OriginalPromptSpan as S;
use crate::original_prefill_layout::PrefillPhase;
use crate::ple_batch_ffi::{BatchArg as B, KernelArguments, KernelModule};
use crate::{
CompletedQsaKvAppend, OriginalDeviceBlock, OriginalDeviceGrRead, QsaKvSnapshot, QsaNativeKind, QsaNativePacking,
QsaPromptAttention, QsaPromptKv, QsaPromptStage,
CompletedQsaKvAppend, OriginalDeviceBlock, OriginalDeviceGrRead, QsaAttendedKv, QsaKvSnapshot, QsaNativeKind,
QsaNativePacking, QsaNativeWeight, QsaPromptAttention, QsaPromptKv, QsaPromptStage,
};
const SCRATCH: usize = 64 << 20;
const GATE_PTX: &[u8] = concat!(include_str!("qsa_prompt_device_gate.ptx"), "\0").as_bytes();
@@ -31,6 +31,32 @@ pub struct OriginalQsaPromptWeights<'w, 'ctx> {
pub kinds: [QsaNativeKind; 4],
pub norms: [&'w DeviceBuffer<'ctx>; 4],
}
/// The index image before a chunk and the position the chunk starts at.
#[derive(Clone, Copy)]
pub struct QsaChunkPrior<'a> {
pub first_position: u32,
pub image: QsaIndexPrior<'a>,
}
/// The KV and the stage one chunk append writes, with the snapshot it extends.
pub struct QsaKvAppendTarget<'a, 'ctx> {
pub kv: &'a mut QsaPromptKv<'ctx>,
pub stage: &'a mut QsaPromptStage<'ctx>,
pub prior: &'a QsaKvSnapshot,
}
/// The weight of one native projection: its span, quantization (`None`: BF16) and `output_width x input_width` shape.
#[derive(Clone, Copy)]
struct ProjectionWeight {
handle: ffi::BufferHandle,
kind: Option<QsaNativeKind>,
output_width: usize,
input_width: usize,
}
/// The activation span a native projection reads and the span it writes.
#[derive(Clone, Copy)]
struct ProjectionSpans {
input: ffi::BufferHandle,
output: ffi::BufferHandle,
}
pub struct OriginalQsaDeviceSelection<'lease, 'arena, 'loan, 'ctx> {
owner: &'lease mut OriginalQsaPromptDevice<'ctx>,
read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>,
@@ -41,7 +67,9 @@ pub struct OriginalQsaDeviceSelection<'lease, 'arena, 'loan, 'ctx> {
#[path = "qsa_resident_device.rs"]
mod resident_device;
pub(crate) use resident_device::kv_stage_spans_of;
pub use resident_device::{OriginalQsaResidentPromptDevice, OriginalQsaResidentSelection};
pub use resident_device::{
OriginalQsaResidentAppendTarget, OriginalQsaResidentPromptDevice, OriginalQsaResidentSelection,
};
#[path = "qsa_prompt_device/impl_context.rs"]
mod impl_context;
@@ -273,7 +273,8 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
for (i, name, n) in [(0, "Kc", 512), (1, "Vc", 512), (2, "Qf", 12288), (3, "idx_raw", 128), (4, "q_idx", 512)] {
let kind = if i < 3 { Some(kinds[i]) } else { None };
let out = arena_span(read, name, n * 4)?;
self.project(read, ws, w[i], kind, n, 2560, if i < 3 { half } else { high }, out)?;
let weight = ProjectionWeight { handle: w[i], kind, output_width: n, input_width: 2560 };
self.project(read, ws, weight, ProjectionSpans { input: if i < 3 { half } else { high }, output: out })?;
}
Ok(())
}
@@ -353,6 +354,7 @@ impl<'lease, 'arena, 'loan, 'ctx> OriginalQsaDeviceSelection<'lease, 'arena, 'lo
(kind, half): (QsaNativeKind, ffi::BufferHandle),
) -> Result<()> {
let block = common(&self.read, S::Block, 10240)?;
self.owner.project(&self.read, ws, weight, Some(kind), 2560, 6144, half, block)
let weight = ProjectionWeight { handle: weight, kind: Some(kind), output_width: 2560, input_width: 6144 };
self.owner.project(&self.read, ws, weight, ProjectionSpans { input: half, output: block })
}
}
@@ -5,17 +5,16 @@ use super::project_phases::{ProjectArgs, Projection};
use super::*;
impl<'ctx> OriginalQsaPromptDevice<'ctx> {
/// One native projection of the chunk rows of `read` through `weight` (dequantized to F16 first when quantized).
pub(super) fn project(
&mut self,
read: &OriginalDeviceGrRead<'_, '_, '_>,
ws: &mut NativeBatchWorkspace<'ctx>,
weight: ffi::BufferHandle,
kind: Option<QsaNativeKind>,
n: usize,
k: usize,
x: ffi::BufferHandle,
output: ffi::BufferHandle,
weight: ProjectionWeight,
spans: ProjectionSpans,
) -> Result<()> {
let ProjectionWeight { handle: weight, kind, output_width: n, input_width: k } = weight;
let ProjectionSpans { input: x, output } = spans;
let t = read.rows();
let status = self.index.as_ref().ok_or(Error::ContextPoisoned)?.handle(10, 64)?;
let scratch = self.scratch_span(n * k)?;
@@ -25,24 +24,26 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
let args = ProjectArgs::new(read, &job, with_low)?;
self.run_projection(ws, &job, args)
}
#[allow(clippy::too_many_arguments)]
/// Projects the chunk rows of `read`, runs the prompt index over them after the `prior` image and keeps the
/// selection pending until it is completed.
pub fn prepare<'lease, 'arena, 'loan>(
&'lease mut self,
read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>,
ws: &mut NativeBatchWorkspace<'ctx>,
p0: u32,
pooled: &[f32],
tail: &[f32],
dead: &[f32],
prior: QsaChunkPrior<'_>,
weights: OriginalQsaPromptWeights<'_, 'ctx>,
) -> Result<OriginalQsaDeviceSelection<'lease, 'arena, 'loan, 'ctx>> {
let QsaChunkPrior { first_position: p0, image } = prior;
let QsaIndexPrior { pooled, tail, dead } = image;
let (t, p) = (read.rows(), p0 as usize);
Self::check_prior(t, p, [pooled, tail, dead])?;
let (w, gamma) = self.admit(&read, &weights, ws)?;
self.project_prior(&read, ws, &weights.kinds, w)?;
let (out, [raw, qfull, iq]) = self.index_spans(&read, t)?;
let index = self.index.as_mut().ok_or(Error::ContextPoisoned)?;
index.run_original_arena(p0, t as u32, pooled, tail, dead, raw, qfull, iq, gamma, out, ws, false)?;
let rows =
ArenaRows { first_position: p0, row_count: t as u32, raw_scores: raw, full_query: qfull, index_query: iq };
index.run_original_arena(image, rows, IndexProgramSpans { norm_weights: gamma, outputs: out }, ws)?;
let state = index.final_state_original_arena(p, t, tail, raw)?;
Ok(OriginalQsaDeviceSelection { owner: self, read, p0, state })
}
@@ -52,17 +52,15 @@ impl<'lease, 'arena, 'loan, 'ctx> OriginalQsaDeviceSelection<'lease, 'arena, 'lo
}
/// Full INT8 append, MMA/exp2 attention, literal strided Qf gate, native
/// FP16 Out. Only actual completed source/causal runtime may publish state.
#[allow(clippy::too_many_arguments)]
pub fn complete(
mut self,
ws: &mut NativeBatchWorkspace<'ctx>,
kv: &mut QsaPromptKv<'ctx>,
stage: &mut QsaPromptStage<'ctx>,
prior: &QsaKvSnapshot,
target: QsaKvAppendTarget<'_, 'ctx>,
attention: &mut QsaPromptAttention<'ctx>,
out_weight: &DeviceBuffer<'ctx>,
out_kind: QsaNativeKind,
out: QsaNativeWeight<'_, 'ctx>,
) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, QsaPromptIndexState, CompletedQsaKvAppend)> {
let QsaKvAppendTarget { kv, stage, prior } = target;
let QsaNativeWeight { buffer: out_weight, kind: out_kind } = out;
self.validate(self.owner.context)?;
let t = self.rows();
let bytes = 2560 * (6144 / 256) * native_block(out_kind);
@@ -72,7 +70,8 @@ impl<'lease, 'arena, 'loan, 'ctx> OriginalQsaDeviceSelection<'lease, 'arena, 'lo
ws.reject_alias(weight, bytes)?;
self.check_out_weight_clear(weight, bytes)?;
let appended = kv.append_original_arena(ws, stage, prior, &self)?;
attention.attend_original_arena(ws, stage, kv, appended.final_snapshot(), &self)?;
let attended = QsaAttendedKv { stage, kv, snapshot: appended.final_snapshot() };
attention.attend_original_arena(ws, attended, &self)?;
let half = self.owner.run_gate(ws, t, &self.read)?;
self.project_out(ws, weight, (out_kind, half))?;
Ok((self.read.from_completed_block(), self.state, appended))
@@ -5,11 +5,10 @@ impl<'ctx> QsaPromptAttention<'ctx> {
pub(crate) fn attend_original_arena(
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
stage: &QsaPromptStage<'ctx>,
kv: &QsaPromptKv<'ctx>,
snapshot: &QsaKvSnapshot,
attended: QsaAttendedKv<'_, '_, 'ctx>,
inputs: &crate::qsa_prompt_index::OriginalQsaDeviceSelection<'_, '_, '_, 'ctx>,
) -> Result<()> {
let QsaAttendedKv { stage, kv, snapshot } = attended;
let t = inputs.rows();
// Original qsa_prompt_attn_batch choice over the resident INT8 pools: v2 on every sm_80+ card unless the
// STRATA_PROMPT_ATTN_V1 debug arm was requested through `set_switches`.
@@ -2,26 +2,19 @@
use super::run_phases::HostStaging;
use super::*;
impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
#[allow(clippy::too_many_arguments)]
/// Runs the prompt (non-decode) index program over device rows that are already in the arena.
pub(super) fn run_original_arena(
&mut self,
p0: u32,
t: u32,
pooled: &[f32],
tail: &[f32],
dead: &[f32],
raw_h: ffi::BufferHandle,
qfull_h: ffi::BufferHandle,
iq_h: ffi::BufferHandle,
gamma: [ffi::BufferHandle; 4],
out: [ffi::BufferHandle; 5],
prior: QsaIndexPrior<'_>,
rows: ArenaRows,
spans: IndexProgramSpans,
ws: &mut NativeBatchWorkspace<'ctx>,
decode: bool,
) -> Result<()> {
let (t, p0, out) = (rows.row_count, rows.first_position, spans.outputs);
let (n, p) = (t as usize, p0 as usize);
self.upload_run_state(p, pooled, tail, dead)?;
let mut prepared = self.prepare_run((t, p0, decode), Some((raw_h, iq_h)), out[0])?;
self.push_run_commands(&mut prepared.commands, &prepared.plan, Some(qfull_h), gamma, out)?;
self.upload_run_state(p, prior.pooled, prior.tail, prior.dead)?;
let mut prepared = self.prepare_run((t, p0, false), Some((rows.raw_scores, rows.index_query)), out[0])?;
self.push_run_commands(&mut prepared.commands, &prepared.plan, Some(rows.full_query), spans)?;
let (mut host, plan) = HostStaging::new(prepared, None);
self.execute_run(&plan, out, ws, &mut host)?;
self.check_run_flags(&host.flags)?;
+16 -4
View File
@@ -46,17 +46,27 @@ pub struct QsaPromptSelection<'lease, 'ctx> {
state: QsaPromptIndexState,
}
mod index_rows;
#[allow(unused_imports)]
use index_rows::SelectRequest;
pub(crate) use index_rows::{ArenaRows, IndexProgramSpans};
pub use index_rows::{QsaChunkRows, QsaIndexPrior};
#[path = "qsa_prompt_device_index.rs"]
mod device_index;
#[path = "qsa_prompt_device.rs"]
mod prompt_device;
pub(crate) use prompt_device::kv_stage_spans_of;
pub use prompt_device::{OriginalQsaDeviceSelection, OriginalQsaPromptDevice, OriginalQsaPromptWeights};
pub use prompt_device::{
OriginalQsaDeviceSelection, OriginalQsaPromptDevice, OriginalQsaPromptWeights, QsaChunkPrior, QsaKvAppendTarget,
};
#[path = "qsa_resident_index.rs"]
mod resident_index;
pub use resident_index::{OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex};
pub use resident_index::{
OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex, ResidentContinuation,
};
#[path = "qsa_resident_index_program.rs"]
mod resident_program;
@@ -64,10 +74,12 @@ mod resident_program;
#[allow(unsafe_code)]
pub(crate) mod resident_transfer;
pub use prompt_device::{OriginalQsaResidentPromptDevice, OriginalQsaResidentSelection};
pub use prompt_device::{
OriginalQsaResidentAppendTarget, OriginalQsaResidentPromptDevice, OriginalQsaResidentSelection,
};
#[path = "qsa_resident_scalar_index.rs"]
mod resident_scalar_index;
pub use resident_scalar_index::{OriginalQsaResidentScalarIndex, OriginalQsaResidentScalarSelection};
pub use resident_scalar_index::{OriginalQsaResidentScalarIndex, OriginalQsaResidentScalarSelection, ScalarStepRows};
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub use resident_index::verification_commit::{OriginalVerifyQsaJournal, OriginalVerifyRope};
@@ -142,43 +142,26 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
}
Ok(())
}
#[allow(clippy::too_many_arguments)] // Closed original fixed QSA geometry and genuine prior image.
/// Appends `rows` to the index after the closed original fixed QSA geometry and the genuine `prior` image, and
/// selects the blocks of every row.
pub fn append_select<'lease>(
&'lease mut self,
p0: u32,
t: u32,
prior_pooled: &[f32],
prior_tail: &[f32],
prior_dead: &[f32],
raw: &[f32],
k: &[f32],
v: &[f32],
qfull: &[f32],
index_q: &[f32],
prior: QsaIndexPrior<'_>,
rows: QsaChunkRows<'_>,
weights: [&DeviceBuffer<'_>; 4],
ws: &mut NativeBatchWorkspace<'ctx>,
) -> Result<QsaPromptSelection<'lease, 'ctx>> {
let inputs = [prior_pooled, prior_tail, prior_dead, raw, k, v, qfull, index_q];
self.append_select_inner((p0, t), inputs, weights, ws, false)
self.append_select_inner(SelectRequest { prior, rows, is_decode: false }, weights, ws)
}
/// T1 Original decode index: scalar native append and FP32 warp scores.
#[allow(clippy::too_many_arguments)]
/// T1 Original decode index: scalar native append and FP32 warp scores; `rows` must hold exactly one row.
pub fn append_select_decode<'lease>(
&'lease mut self,
p0: u32,
prior_pooled: &[f32],
prior_tail: &[f32],
prior_dead: &[f32],
raw: &[f32],
k: &[f32],
v: &[f32],
qfull: &[f32],
index_q: &[f32],
prior: QsaIndexPrior<'_>,
rows: QsaChunkRows<'_>,
weights: [&DeviceBuffer<'_>; 4],
ws: &mut NativeBatchWorkspace<'ctx>,
) -> Result<QsaPromptSelection<'lease, 'ctx>> {
let inputs = [prior_pooled, prior_tail, prior_dead, raw, k, v, qfull, index_q];
self.append_select_inner((p0, 1), inputs, weights, ws, true)
self.append_select_inner(SelectRequest { prior, rows, is_decode: true }, weights, ws)
}
}
@@ -6,20 +6,21 @@ use super::*;
impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
pub(super) fn append_select_inner<'lease>(
&'lease mut self,
(p0, t): (u32, u32),
inputs: [&[f32]; 8],
request: SelectRequest<'_>,
weights: [&DeviceBuffer<'_>; 4],
ws: &mut NativeBatchWorkspace<'ctx>,
decode: bool,
) -> Result<QsaPromptSelection<'lease, 'ctx>> {
self.check_select_inputs((p0, t, decode), inputs)?;
let (p0, t) = (request.rows.first_position, request.rows.row_count);
self.check_select_inputs(&request)?;
let gamma = self.weights(weights, ws)?;
let (outputs, handles) = self.admit_outputs(t as usize, gamma, ws)?;
let operation = self.run_selected((p0, t, decode), inputs, (gamma, handles), ws);
self.finish_select(operation, outputs, (p0, t), inputs[1])
let operation = self.run(&request, IndexProgramSpans { norm_weights: gamma, outputs: handles }, ws);
self.finish_select(operation, outputs, (p0, t), request.prior.tail)
}
/// Checks the geometry, the lengths of the prior image and rows and that every input value is finite.
fn check_select_inputs(&self, (p0, t, decode): (u32, u32, bool), inputs: [&[f32]; 8]) -> Result<()> {
fn check_select_inputs(&self, request: &SelectRequest<'_>) -> Result<()> {
let (p0, t, decode) = (request.rows.first_position, request.rows.row_count, request.is_decode);
let inputs = request.inputs();
if decode && t != 1 {
return Err(Error::InvalidQwenShape);
}
@@ -120,17 +121,6 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn run_selected(
&mut self,
(p0, t, decode): (u32, u32, bool),
inputs: [&[f32]; 8],
(gamma, handles): ([ffi::BufferHandle; 4], [ffi::BufferHandle; 5]),
ws: &mut NativeBatchWorkspace<'ctx>,
) -> Result<()> {
let [pooled, tail, dead, raw, k, v, qfull, index_q] = inputs;
self.run(p0, t, pooled, tail, dead, raw, k, v, qfull, index_q, gamma, handles, ws, decode)
}
/// Reads the final state back; any failure releases (or, on a poisoned context, leaks) the outputs.
fn finish_select<'lease>(
&'lease mut self,
@@ -5,29 +5,21 @@ use super::run_phases::{HostStaging, RunPlan};
use super::*;
impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
#[allow(clippy::too_many_arguments)]
/// Uploads the prior image and the rows of `request`, runs the index program over them and checks the status
/// words and the selected IDs.
pub(super) fn run(
&mut self,
p0: u32,
t: u32,
pooled: &[f32],
tail: &[f32],
dead: &[f32],
raw: &[f32],
k: &[f32],
v: &[f32],
qfull: &[f32],
iq: &[f32],
gamma: [ffi::BufferHandle; 4],
out: [ffi::BufferHandle; 5],
request: &SelectRequest<'_>,
spans: IndexProgramSpans,
ws: &mut NativeBatchWorkspace<'ctx>,
decode: bool,
) -> Result<()> {
let SelectRequest { prior, rows, is_decode: decode } = *request;
let (t, p0, out) = (rows.row_count, rows.first_position, spans.outputs);
let (n, p) = (t as usize, p0 as usize);
self.upload_run_inputs(p, pooled, tail, dead, raw, qfull, iq)?;
self.upload_run_inputs(prior, &rows)?;
let mut prepared = self.prepare_run((t, p0, decode), None, out[0])?;
self.push_run_commands(&mut prepared.commands, &prepared.plan, None, gamma, out)?;
let kv = Some([encode(k)?, encode(v)?]);
self.push_run_commands(&mut prepared.commands, &prepared.plan, None, spans)?;
let kv = Some([encode(rows.keys)?, encode(rows.values)?]);
let (mut host, plan) = HostStaging::new(prepared, kv);
self.execute_run(&plan, out, ws, &mut host)?;
self.check_run_flags(&host.flags)?;
@@ -0,0 +1,70 @@
//! The row sets one QSA index append works on: the host image before it, the host rows it appends, the device rows of
//! the arena path and the spans the index program writes. They replace long positional argument lists.
use super::*;
/// The host image of the index before a chunk: the pooled block keys, the tail and the spare (`dead`) rows.
#[derive(Clone, Copy)]
pub struct QsaIndexPrior<'a> {
pub pooled: &'a [f32],
pub tail: &'a [f32],
pub dead: &'a [f32],
}
/// The host rows a chunk appends at `first_position`: the raw index scores, K, V, full Q and index query values of
/// `row_count` tokens. The position and the count travel with the rows because the lengths are checked against them.
#[derive(Clone, Copy)]
pub struct QsaChunkRows<'a> {
pub first_position: u32,
pub row_count: u32,
pub raw_scores: &'a [f32],
pub keys: &'a [f32],
pub values: &'a [f32],
pub full_query: &'a [f32],
pub index_query: &'a [f32],
}
/// The device rows the arena index path reads: the first position, the row count and the spans of the raw index
/// scores, the full query and the index query that the projections already wrote.
#[derive(Clone, Copy)]
pub(crate) struct ArenaRows {
pub(crate) first_position: u32,
pub(crate) row_count: u32,
pub(crate) raw_scores: ffi::BufferHandle,
pub(crate) full_query: ffi::BufferHandle,
pub(crate) index_query: ffi::BufferHandle,
}
/// The spans the index program touches besides its input rows: the four norm weights it reads and the five outputs
/// (K, V, Q, selected IDs, steps) it writes.
#[derive(Clone, Copy)]
pub(crate) struct IndexProgramSpans {
pub(crate) norm_weights: [ffi::BufferHandle; 4],
pub(crate) outputs: [ffi::BufferHandle; 5],
}
/// One index append as the select path runs it: the image before it, the rows it appends and whether it is the T1
/// decode step (one row, scalar append and FP32 warp scores).
#[derive(Clone, Copy)]
pub(super) struct SelectRequest<'a> {
pub(super) prior: QsaIndexPrior<'a>,
pub(super) rows: QsaChunkRows<'a>,
pub(super) is_decode: bool,
}
impl<'a> SelectRequest<'a> {
/// The prior image and the row values in the order the length and finiteness checks walk them.
pub(super) fn inputs(&self) -> [&'a [f32]; 8] {
let (prior, rows) = (self.prior, self.rows);
[
prior.pooled,
prior.tail,
prior.dead,
rows.raw_scores,
rows.keys,
rows.values,
rows.full_query,
rows.index_query,
]
}
}
@@ -76,19 +76,10 @@ pub(super) fn step_bytes(p: usize, n: usize) -> Result<Vec<u8>> {
}
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<()> {
self.upload_run_state(p, pooled, tail, dead)?;
for (i, x) in [(4, raw), (7, qfull), (8, iq)] {
/// Uploads the prior image at the position of `rows`, then their raw scores, full query and index query.
pub(super) fn upload_run_inputs(&mut self, prior: QsaIndexPrior<'_>, rows: &QsaChunkRows<'_>) -> Result<()> {
self.upload_run_state(rows.first_position as usize, prior.pooled, prior.tail, prior.dead)?;
for (i, x) in [(4, rows.raw_scores), (7, rows.full_query), (8, rows.index_query)] {
self.upload(i, x)?;
}
Ok(())
@@ -196,9 +187,9 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
commands: &mut Commands,
plan: &RunPlan,
qfull: Option<ffi::BufferHandle>,
gamma: [ffi::BufferHandle; 4],
out: [ffi::BufferHandle; 5],
spans: IndexProgramSpans,
) -> Result<()> {
let IndexProgramSpans { norm_weights: gamma, outputs: out } = spans;
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)?;
+2 -2
View File
@@ -1,8 +1,8 @@
//! Genuine Original INT8 KV: page4, two heads, 256 dimensions, four F16 scales.
//! Immutable snapshots are completed byte ownership, never a runtime causal certificate.
use crate::qsa_prompt_attention_ffi::{Arg, Arguments, Module};
use crate::qsa_prompt_attention_ffi::{Arg, Arguments, LaunchGeometry, Module};
use crate::qsa_prompt_host_ffi::MappedAllocation;
use crate::qsa_prompt_resolver::Resolver;
use crate::qsa_prompt_resolver::{PoolAddresses, Resolver, SelectedRows};
use crate::serving_context::geometry;
use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine};
use std::rc::Rc;
@@ -107,24 +107,24 @@ impl<'ctx> QsaPromptStage<'ctx> {
fn launch_pass(
&self,
w: &NativeBatchWorkspace<'ctx>,
(index, grid, block): (usize, [u32; 3], u32),
(index, geometry): (usize, LaunchGeometry),
a: &mut Arguments,
) -> Result<()> {
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(index, grid, block, 0, w.blas()?.stream(), a)
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(index, geometry, w.blas()?.stream(), a)
}
/// Runs kernel `index` of the stage module on the workspace stream; any failure marks the owners failed.
pub(super) fn run(
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
index: usize,
grid: [u32; 3],
block: u32,
geometry: LaunchGeometry,
mut a: Arguments,
) -> Result<()> {
self.validate(self.context)?;
w.validate_context(self.context)?;
let g = self.context.enter()?;
let dependency = self.context.driver.api.synchronize();
let op = dependency.and_then(|()| self.launch_pass(w, (index, grid, block), &mut a));
let op = dependency.and_then(|()| self.launch_pass(w, (index, geometry), &mut a));
let sync = w.blas()?.synchronize();
let pop = g.finish();
if sync.is_err() || pop.is_err() {
@@ -153,7 +153,7 @@ impl<'ctx> QsaPromptKv<'ctx> {
) -> Result<()> {
let (sa, rp, sp, hp) = self.append_addresses(stage)?;
let guard = Arguments::new(vec![Arg::U64(k), Arg::U64(v), Arg::I32((t * 512) as i32), Arg::U64(sa)])?;
stage.run(workspace, 0, [(t * 512).div_ceil(256) as u32, 1, 1], 256, guard)?;
stage.run(workspace, 0, LaunchGeometry::new([(t * 512).div_ceil(256) as u32, 1, 1], 256, 0), guard)?;
if stage.flags()? != 0 {
return Err(Error::InvalidQ8Activation);
}
@@ -188,8 +188,8 @@ impl<'ctx> QsaPromptKv<'ctx> {
stage.current = None;
self.current = None;
self.mapped_current = None;
stage.run(workspace, 1, [t as u32, 2, 8], 64, args)?;
stage.run(workspace, 2, [1, 1, 1], 256, scales)?;
stage.run(workspace, 1, LaunchGeometry::new([t as u32, 2, 8], 64, 0), args)?;
stage.run(workspace, 2, LaunchGeometry::new([1, 1, 1], 256, 0), scales)?;
if stage.flags()? != 0 {
return Err(Error::InvalidQ8Activation);
}
@@ -168,16 +168,20 @@ impl<'ctx> QsaPromptKv<'ctx> {
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
s: &QsaKvSnapshot,
ids: &DeviceBuffer<'_>,
steps: &DeviceBuffer<'_>,
t: usize,
inputs: &crate::QsaAttentionInputs<'_, '_>,
) -> Result<([u64; 4], u64, usize)> {
let (ids, steps) = self.admit_selection(s, (ids, steps), t)?;
let t = inputs.t;
let (ids, steps) = self.admit_selection(s, (inputs.ids, inputs.steps), t)?;
self.restore(w, s)?;
let host = self.host_addresses()?;
let resident = self.pools.addresses()?;
let table = self.pools.table()?;
self.resolver.as_mut().ok_or(Error::ContextPoisoned)?.resolve(w, table, ids, steps, t, host, resident)?;
self.resolver.as_mut().ok_or(Error::ContextPoisoned)?.resolve(
w,
table,
SelectedRows { ids, steps, row_count: t },
PoolAddresses { host, resident },
)?;
Ok((resident, table, s.0.end))
}
/// `s` belongs to this owner and the 1..=3 query rows' IDs and steps have their exact sizes; returns their
+26 -14
View File
@@ -1,6 +1,6 @@
//! Literal Original clock state and mapped-host miss copy. No selectable policy or public address.
//! The resident page count (`n_slots`, `--kv-resident` / 4) is fixed per owner at construction.
use crate::qsa_prompt_attention_ffi::{Arg, Arguments, Module};
use crate::qsa_prompt_attention_ffi::{Arg, Arguments, LaunchGeometry, Module};
use crate::qsa_prompt_kv::checked;
use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine};
use leleka_context::geometry::{RESOLVE_BLOCK, stream_map_bytes};
@@ -32,6 +32,19 @@ pub struct KvStreamCounters {
/// A call named more blocks than the window holds (never with a legal window; the attention masks them).
pub overflow: bool,
}
/// The device addresses of the selected block IDs and steps of the `row_count` query rows a resolve pass looks up.
#[derive(Clone, Copy)]
pub(crate) struct SelectedRows {
pub(crate) ids: u64,
pub(crate) steps: u64,
pub(crate) row_count: usize,
}
/// The host (pinned) and resident (VRAM) KV pool addresses a resolve pass copies missed pages between.
#[derive(Clone, Copy)]
pub(crate) struct PoolAddresses {
pub(crate) host: [u64; 4],
pub(crate) resident: [u64; 4],
}
pub(crate) struct Resolver<'ctx> {
context: &'ctx Context<'ctx>,
slots: [Option<DeviceBuffer<'ctx>>; 5],
@@ -125,18 +138,18 @@ impl<'ctx> Resolver<'ctx> {
}
Ok(v)
}
/// Runs kernel `i` of the resolver module on the workspace stream; any failure marks the owners failed.
fn run(
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
i: usize,
grid: [u32; 3],
block: u32,
geometry: LaunchGeometry,
mut a: Arguments,
) -> Result<()> {
self.validate()?;
w.validate_context(self.context)?;
let g = self.context.enter()?;
let op = self.launch_synced(w, (i, grid, block), &mut a);
let op = self.launch_synced(w, (i, geometry), &mut a);
let sync = w.blas()?.synchronize();
let pop = g.finish();
self.settle_run(w, a, (&op, &sync, &pop));
@@ -146,11 +159,11 @@ impl<'ctx> Resolver<'ctx> {
fn launch_synced(
&self,
w: &NativeBatchWorkspace<'ctx>,
(i, grid, block): (usize, [u32; 3], u32),
(i, geometry): (usize, LaunchGeometry),
a: &mut Arguments,
) -> Result<()> {
self.context.driver.api.synchronize().and_then(|()| {
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(i, grid, block, 0, w.blas()?.stream(), a)
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(i, geometry, w.blas()?.stream(), a)
})
}
/// Keeps the arguments alive when the stream or context state is unknown and marks the owners failed on any error.
@@ -179,7 +192,7 @@ impl<'ctx> Resolver<'ctx> {
values.push(Arg::I64(pages as i64));
values.push(Arg::I64(self.n_slots as i64));
let a = Arguments::new(values)?;
self.run(w, 0, [128, 1, 1], 256, a)?;
self.run(w, 0, LaunchGeometry::new([128, 1, 1], 256, 0), a)?;
self.epoch = 0;
Ok(())
}
@@ -204,19 +217,18 @@ impl<'ctx> Resolver<'ctx> {
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
table: u64,
ids: u64,
steps: u64,
t: usize,
host: [u64; 4],
resident: [u64; 4],
selection: SelectedRows,
pools: PoolAddresses,
) -> Result<()> {
let SelectedRows { ids, steps, row_count: t } = selection;
let PoolAddresses { host, resident } = pools;
if !(1..=3).contains(&t) || t * BLOCKS_PER_QUERY > self.n_slots {
return Err(Error::InvalidQwenShape);
}
let epoch = self.epoch.checked_add(1).ok_or(Error::InvalidQwenShape)?;
let (a, copy) = self.resolve_arguments(table, (ids, steps, t), (host, resident))?;
self.run(w, 1, [1, 1, 1], 1024, a)?;
self.run(w, 2, [96, 1, 1], 128, copy)?;
self.run(w, 1, LaunchGeometry::new([1, 1, 1], 1024, 0), a)?;
self.run(w, 2, LaunchGeometry::new([96, 1, 1], 128, 0), copy)?;
self.epoch = epoch;
Ok(())
}
@@ -1,15 +1,21 @@
//! Same literal attention on the real selected query/IDs/steps/attn arena.
use super::impl_qsapromptattention::{AttnPasses, admit_budget};
use super::impl_qsapromptattention::{AttnPasses, KernelEntry, admit_budget};
use super::*;
/// The resident prompt KV one attention pass reads: the transport stage, the mapped journal and the prefix fixing its
/// extent. They travel together because the attention addresses the pools through all three.
pub(crate) struct OriginalQsaAttendedKv<'a, 'ctx> {
pub(crate) stage: &'a crate::qsa_prompt_kv::OriginalQsaResidentTransport<'ctx>,
pub(crate) kv: &'a crate::qsa_prompt_kv::OriginalQsaMappedJournal<'ctx>,
pub(crate) snapshot: &'a crate::qsa_prompt_kv::OriginalQsaMappedPrefix,
}
impl<'ctx> QsaPromptAttention<'ctx> {
pub(crate) fn attend_resident_arena(
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
stage: &crate::qsa_prompt_kv::OriginalQsaResidentTransport<'ctx>,
kv: &crate::qsa_prompt_kv::OriginalQsaMappedJournal<'ctx>,
snapshot: &crate::qsa_prompt_kv::OriginalQsaMappedPrefix,
attended: OriginalQsaAttendedKv<'_, 'ctx>,
inputs: &crate::qsa_prompt_index::OriginalQsaResidentSelection<'_, '_, '_, '_, '_, 'ctx>,
) -> Result<()> {
let OriginalQsaAttendedKv { stage, kv, snapshot } = attended;
let t = inputs.rows();
// Original qsa_prompt_attn_batch kernel choice (see qsa_prompt_attention_select): v2 unless the debug arm.
let kernel = self.selected_kernel()?;
@@ -70,12 +76,10 @@ impl<'ctx> OriginalQsaResidentAttention<'ctx> {
pub(crate) fn attend_resident_arena(
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
stage: &crate::qsa_prompt_kv::OriginalQsaResidentTransport<'ctx>,
kv: &crate::qsa_prompt_kv::OriginalQsaMappedJournal<'ctx>,
snapshot: &crate::qsa_prompt_kv::OriginalQsaMappedPrefix,
attended: OriginalQsaAttendedKv<'_, 'ctx>,
inputs: &crate::qsa_prompt_index::OriginalQsaResidentSelection<'_, '_, '_, '_, '_, 'ctx>,
) -> Result<()> {
self.inner.attend_resident_arena(w, stage, kv, snapshot, inputs)
self.inner.attend_resident_arena(w, attended, inputs)
}
}
impl<'ctx> QsaPromptAttention<'ctx> {
@@ -111,22 +115,19 @@ impl<'ctx> QsaPromptAttention<'ctx> {
e
})
}
#[allow(clippy::too_many_arguments)]
/// Runs one launch of the attention module under the failure bookkeeping of the resident owner.
fn run_resident(
&mut self,
variants: bool,
entry: KernelEntry,
w: &mut NativeBatchWorkspace<'ctx>,
index: usize,
grid: [u32; 3],
block: u32,
shared: u32,
geometry: LaunchGeometry,
mut a: Arguments,
) -> Result<()> {
self.validate_resident()?;
w.validate_context(self.context)?;
let g = self.enter_or_fail(w)?;
let dependency = self.context.driver.api.synchronize();
let op = dependency.and_then(|()| self.launch_variant(variants, w, (index, grid, block, shared), &mut a));
let op = dependency.and_then(|()| self.launch_variant(entry, w, geometry, &mut a));
let sync = w.blas()?.synchronize();
let pop = g.finish();
if sync.is_err() || pop.is_err() {
@@ -16,14 +16,14 @@ impl<'ctx> QsaNativeDecode<'ctx> {
snapshot: &'loan OriginalQsaMappedPrefix,
inputs: &QsaAttentionInputs<'_, '_>,
) -> Result<OriginalQsaResidentDecodeCompletion<'loan, 'ctx>> {
let (ids, steps, t) = (inputs.ids, inputs.steps, inputs.t);
let t = inputs.t;
self.validate()?;
w.validate_context(self.context)?;
kv.validate_context(self.context)?;
kv.validate_prefix(snapshot)?;
let handles = self.admit_inputs(w, inputs, |b| kv.reject_alias(b))?;
let (status, out) = self.guard_pass(w, handles, (t, snapshot.next_position()))?;
let (pools, table, _) = kv.resolved_addresses(w, snapshot, ids, steps, t)?;
let (pools, table, _) = kv.resolved_addresses(w, snapshot, inputs)?;
self.attention_passes(w, (pools, table), handles, (status, out, t))?;
Ok(OriginalQsaResidentDecodeCompletion { owner: self, _kv: kv, _snapshot: snapshot, t })
}
@@ -1,9 +1,17 @@
//! Real-arena resident continuation. No host state image or fake pending state.
use super::*;
use crate::qsa_prompt_index::{OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex};
use crate::qsa_prompt_index::{
OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex, ResidentContinuation,
};
use crate::qsa_prompt_kv::{
OriginalQsaMappedAppend, OriginalQsaMappedJournal, OriginalQsaMappedPrefix, OriginalQsaResidentTransport,
};
/// The mapped journal and the transport stage one resident chunk append writes, with the prefix it extends.
pub struct OriginalQsaResidentAppendTarget<'a, 'ctx> {
pub kv: &'a mut OriginalQsaMappedJournal<'ctx>,
pub stage: &'a mut OriginalQsaResidentTransport<'ctx>,
pub prior: &'a OriginalQsaMappedPrefix,
}
pub struct OriginalQsaResidentSelection<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> {
owner: &'lease mut OriginalQsaPromptDevice<'ctx>,
read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>,
@@ -11,13 +11,20 @@ struct ResidentSpans {
qfull: ffi::BufferHandle,
iq: ffi::BufferHandle,
}
/// One resident index run: the first position, the row count and the norm weights.
/// One resident index run: the first position, the row count, the norm weights, the spans and the clock of the
/// command profile (`None` when it is off).
struct ResidentJob {
p: usize,
p0: u32,
t: usize,
gamma: [ffi::BufferHandle; 4],
spans: ResidentSpans,
mark: Option<std::time::Instant>,
}
/// What a failed resident run must undo: the checkpoint to restore and the raw rows that were retained for it.
struct ResidentRollback<'a, 'ctx> {
start: &'a OriginalQsaIndexCheckpoint<'ctx>,
raw_rows: DeviceBuffer<'ctx>,
}
/// Charge the time since `mark` to the `index` entry of the QSA command profile and restart the clock (a no-op when
/// profiling is off, when `mark` is `None`).
@@ -38,26 +45,33 @@ impl ResidentJob {
resident.in_flight = true;
resident.unpublished = true;
let (s, t) = (&self.spans, self.t as u32);
resident.placed(index, |w| w.run_resident_arena(self.p0, t, s.raw, s.qfull, s.iq, self.gamma, s.out, ws, false))
let rows = ArenaRows {
first_position: self.p0,
row_count: t,
raw_scores: s.raw,
full_query: s.qfull,
index_query: s.iq,
};
let spans = IndexProgramSpans { norm_weights: self.gamma, outputs: s.out };
resident.placed(index, |w| w.run_resident_arena(rows, spans, ws, false))
}
}
impl<'ctx> OriginalQsaPromptDevice<'ctx> {
#[allow(clippy::too_many_arguments)]
pub(super) fn prepare_resident<'lease, 'index, 'weights, 'arena, 'loan>(
&'lease mut self,
read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>,
ws: &mut NativeBatchWorkspace<'ctx>,
resident: &'index mut OriginalQsaResidentIndex<'ctx>,
prior: &OriginalQsaIndexCheckpoint<'ctx>,
from: ResidentContinuation<'index, '_, 'ctx>,
weights: OriginalQsaPromptWeights<'weights, 'ctx>,
) -> Result<OriginalQsaResidentSelection<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>> {
let ResidentContinuation { resident, prior } = from;
let (p, p0, t) = self.resident_bounds(&read, resident, prior)?;
let start = resident.checkpoint(ws)?;
let raw_rows = self.context.allocate(t * 512)?;
let (w, gamma) = self.admit(&read, &weights, ws)?;
let mut mark = self.project_resident(&read, ws, &w, &weights)?;
let job = ResidentJob { p, p0, t, gamma, spans: self.run_spans(&read, t)? };
let raw_rows = self.run_resident(resident, ws, &job, (&start, raw_rows), &mut mark)?;
let mark = self.project_resident(&read, ws, &w, &weights)?;
let mut job = ResidentJob { p, p0, t, gamma, spans: self.run_spans(&read, t)?, mark };
let raw_rows = self.run_resident(resident, ws, &mut job, ResidentRollback { start: &start, raw_rows })?;
let gamma = weights.norms[3];
let batch = OriginalQsaIndexBatch { owner: resident, start, raw: Some(raw_rows), gamma, rows: t };
Ok(OriginalQsaResidentSelection { owner: self, read, p0, batch })
@@ -122,7 +136,8 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
for (i, name, n) in [(0, "Kc", 512), (1, "Vc", 512), (2, "Qf", 12288), (3, "idx_raw", 128), (4, "q_idx", 512)] {
let kind = if i < 3 { Some(weights.kinds[i]) } else { None };
let x = if i < 3 { half } else { high };
self.project(read, ws, w[i], kind, n, 2560, x, arena_span(read, name, n * 4)?)?;
let weight = ProjectionWeight { handle: w[i], kind, output_width: n, input_width: 2560 };
self.project(read, ws, weight, ProjectionSpans { input: x, output: arena_span(read, name, n * 4)? })?;
lap(&mut mark, i + 1, ["proj K", "proj V", "proj Q", "proj idxK", "proj idxQ"][i]);
}
Ok(mark)
@@ -154,13 +169,13 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
&mut self,
resident: &mut OriginalQsaResidentIndex<'ctx>,
ws: &mut NativeBatchWorkspace<'ctx>,
job: &ResidentJob,
(start, raw_rows): (&OriginalQsaIndexCheckpoint<'ctx>, DeviceBuffer<'ctx>),
mark: &mut Option<std::time::Instant>,
job: &mut ResidentJob,
rollback: ResidentRollback<'_, 'ctx>,
) -> Result<DeviceBuffer<'ctx>> {
let ResidentRollback { start, raw_rows } = rollback;
let index = self.index.as_mut().ok_or(Error::ContextPoisoned)?;
let operation = job.run_index(resident, index, ws);
lap(mark, 6, "index+norm+rope run");
lap(&mut job.mark, 6, "index+norm+rope run");
let copied = match operation {
Ok(()) => {
let retained = raw_rows.handle.ok_or(Error::ContextPoisoned)?;
@@ -169,9 +184,9 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
Err(primary) => Err(primary),
};
if let Err(primary) = copied {
return self.abort_resident(resident, ws, start, raw_rows, primary);
return self.abort_resident(resident, ws, ResidentRollback { start, raw_rows }, primary);
}
lap(mark, 7, "copy raw rows");
lap(&mut job.mark, 7, "copy raw rows");
resident.provisional_end(job.p + job.t);
Ok(raw_rows)
}
@@ -180,10 +195,10 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
&self,
resident: &mut OriginalQsaResidentIndex<'ctx>,
ws: &mut NativeBatchWorkspace<'ctx>,
start: &OriginalQsaIndexCheckpoint<'ctx>,
raw_rows: DeviceBuffer<'ctx>,
rollback: ResidentRollback<'_, 'ctx>,
primary: Error,
) -> Result<T> {
let ResidentRollback { start, raw_rows } = rollback;
let cleanup = resident.restore_private(ws, start);
if cleanup.is_ok() {
resident.in_flight = false;
@@ -4,6 +4,7 @@
use super::impl_originalqsapromptdevice::lap;
#[allow(unused_imports)]
use super::*;
use crate::qsa_prompt_attention::OriginalQsaAttendedKv;
impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
OriginalQsaResidentSelection<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
@@ -23,25 +24,21 @@ impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
}
/// Full INT8 append, MMA/exp2 attention, literal strided Qf gate, native
/// FP16 Out. Only actual completed source/causal runtime may publish state.
#[allow(clippy::too_many_arguments)]
pub fn complete(
mut self,
ws: &mut NativeBatchWorkspace<'ctx>,
kv: &mut OriginalQsaMappedJournal<'ctx>,
stage: &mut OriginalQsaResidentTransport<'ctx>,
prior: &OriginalQsaMappedPrefix,
mut target: OriginalQsaResidentAppendTarget<'_, 'ctx>,
attention: &mut crate::qsa_prompt_attention::OriginalQsaResidentAttention<'ctx>,
out_weight: &DeviceBuffer<'ctx>,
out_kind: QsaNativeKind,
out: QsaNativeWeight<'_, 'ctx>,
) -> Result<(
OriginalDeviceBlock<'arena, 'loan, 'ctx>,
OriginalQsaIndexBatch<'index, 'weights, 'ctx>,
OriginalQsaMappedAppend,
)> {
match self.complete_inner(ws, kv, stage, prior, attention, out_weight, out_kind) {
match self.complete_inner(ws, &mut target, attention, out) {
Ok(appended) => Ok((self.read.from_completed_block(), self.batch, appended)),
Err(primary) => {
let kv_restore = kv.rollback(ws, prior);
let kv_restore = target.kv.rollback(ws, target.prior);
let index_restore = match self.owner.index.as_mut() {
Some(w) => self.batch.abort(ws, w).map(|_| ()),
None => Err(Error::ContextPoisoned),
@@ -50,17 +47,15 @@ impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
}
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn complete_inner(
&mut self,
ws: &mut NativeBatchWorkspace<'ctx>,
kv: &mut OriginalQsaMappedJournal<'ctx>,
stage: &mut OriginalQsaResidentTransport<'ctx>,
prior: &OriginalQsaMappedPrefix,
target: &mut OriginalQsaResidentAppendTarget<'_, 'ctx>,
attention: &mut crate::qsa_prompt_attention::OriginalQsaResidentAttention<'ctx>,
out_weight: &DeviceBuffer<'ctx>,
out_kind: QsaNativeKind,
out: QsaNativeWeight<'_, 'ctx>,
) -> Result<OriginalQsaMappedAppend> {
let QsaNativeWeight { buffer: out_weight, kind: out_kind } = out;
let OriginalQsaResidentAppendTarget { kv, stage, prior } = target;
self.validate(self.owner.context)?;
let bytes = 2560 * (6144 / 256) * native_block(out_kind);
let weight = self.owner.own(out_weight, bytes, 2)?;
@@ -71,12 +66,14 @@ impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
let mut mark = crate::command_profile::enabled().then(std::time::Instant::now);
let appended = kv.append_resident_arena(ws, stage, prior, &self)?;
lap(&mut mark, 11, "kv append");
attention.attend_resident_arena(ws, stage, kv, appended.final_prefix(), &self)?;
let attended = OriginalQsaAttendedKv { stage, kv, snapshot: appended.final_prefix() };
attention.attend_resident_arena(ws, attended, &self)?;
lap(&mut mark, 12, "attend");
let half = self.run_gate(ws)?;
lap(&mut mark, 13, "gate");
let block = common(&self.read, S::Block, 10240)?;
self.owner.project(&self.read, ws, weight, Some(out_kind), 2560, 6144, half, block)?;
let weight = ProjectionWeight { handle: weight, kind: Some(out_kind), output_width: 2560, input_width: 6144 };
self.owner.project(&self.read, ws, weight, ProjectionSpans { input: half, output: block })?;
lap(&mut mark, 14, "proj out");
Ok(appended)
}
@@ -181,16 +178,15 @@ impl<'ctx> OriginalQsaResidentPromptDevice<'ctx> {
pub fn is_failed(&self) -> bool {
self.inner.is_failed()
}
#[allow(clippy::too_many_arguments)]
/// Projects the chunk rows of `read` and runs the resident index program over them from `from`.
pub fn prepare<'lease, 'index, 'weights, 'arena, 'loan>(
&'lease mut self,
read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>,
ws: &mut NativeBatchWorkspace<'ctx>,
resident: &'index mut OriginalQsaResidentIndex<'ctx>,
prior: &OriginalQsaIndexCheckpoint<'ctx>,
from: ResidentContinuation<'index, '_, 'ctx>,
weights: OriginalQsaPromptWeights<'weights, 'ctx>,
) -> Result<OriginalQsaResidentSelection<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>> {
self.inner.prepare_resident(read, ws, resident, prior, weights)
self.inner.prepare_resident(read, ws, from, weights)
}
pub fn commit_prefix<'index, 'weights>(
&mut self,
@@ -37,6 +37,11 @@ pub struct OriginalQsaResidentIndex<'ctx> {
pub(super) unpublished: bool,
pool: Rc<RefCell<Vec<DeviceBuffer<'ctx>>>>,
}
/// What one resident chunk continues from: the live index and the checkpoint it must stand at.
pub struct ResidentContinuation<'index, 'prior, 'ctx> {
pub resident: &'index mut OriginalQsaResidentIndex<'ctx>,
pub prior: &'prior OriginalQsaIndexCheckpoint<'ctx>,
}
/// Actual pending index batch. Forgetting it leaves owner in-flight/refusing new
/// use; dropping without an explicit replay likewise refuses publication.
pub struct OriginalQsaIndexBatch<'index, 'weights, 'ctx> {
@@ -52,7 +52,8 @@ impl<'index, 'weights, 'ctx> OriginalQsaIndexBatch<'index, 'weights, 'ctx> {
let raw = self.raw.as_ref().ok_or(Error::ContextPoisoned)?;
let rh = raw.handle.ok_or(Error::ContextPoisoned)?;
let gh = self.gamma.handle.ok_or(Error::ContextPoisoned)?;
self.owner.placed(workspace, |w| w.replay_resident_prefix(self.start.next_position(), accepted, rh, gh, ws))
let keys = crate::qsa_prompt_index::resident_program::ReplayKeySpans { raw: rh, gamma: gh };
self.owner.placed(workspace, |w| w.replay_resident_prefix(self.start.next_position(), accepted, keys, ws))
}
pub fn abort(
&mut self,
@@ -8,7 +8,8 @@ mod impl_qsapromptindexworkspace;
mod impl_qsapromptindexworkspace_2;
#[path = "qsa_resident_index_program/impl_qsapromptindexworkspace_3.rs"]
mod impl_qsapromptindexworkspace_3;
pub(super) use impl_qsapromptindexworkspace_2::ReplayKeySpans;
#[allow(unused_imports)]
use impl_qsapromptindexworkspace_2::launch_label;
#[allow(unused_imports)]
use impl_qsapromptindexworkspace_3::{ArenaCall, ArenaIo, ArenaPlan, LateLaunch};
use impl_qsapromptindexworkspace_3::{ArenaCall, ArenaIo, ArenaPlan, LateLaunch, LateQueue};
@@ -4,20 +4,24 @@
use super::*;
impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
#[allow(clippy::too_many_arguments)]
/// Runs the index program over device rows already in the arena (`is_decode`: the T1 decode step).
pub(in super::super) fn run_resident_arena(
&mut self,
p0: u32,
t: u32,
raw_h: ffi::BufferHandle,
qfull_h: ffi::BufferHandle,
iq_h: ffi::BufferHandle,
gamma: [ffi::BufferHandle; 4],
out: [ffi::BufferHandle; 5],
rows: ArenaRows,
spans: IndexProgramSpans,
ws: &mut NativeBatchWorkspace<'ctx>,
decode: bool,
is_decode: bool,
) -> Result<()> {
let call = ArenaCall { p0, t, raw: raw_h, qfull: qfull_h, iq: iq_h, gamma, out, decode };
let call = ArenaCall {
p0: rows.first_position,
t: rows.row_count,
raw: rows.raw_scores,
qfull: rows.full_query,
iq: rows.index_query,
gamma: spans.norm_weights,
out: spans.outputs,
decode: is_decode,
};
self.run_arena(call, ws)
}
fn run_arena(&mut self, call: ArenaCall, ws: &mut NativeBatchWorkspace<'ctx>) -> Result<()> {
@@ -113,9 +117,9 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
let timed = crate::command_profile::enabled();
self.ensure_late(!plan.late.is_empty())?;
let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?;
let mut next = 0usize;
let mut late = LateQueue { launches: &mut plan.late, next: 0 };
for (i, (shape, args)) in plan.commands.iter_mut().enumerate() {
self.run_late(blas, &mut plan.late, &mut next, i, timed)?;
self.run_late(blas, &mut late, i, timed)?;
let started = std::time::Instant::now();
module.launch(*shape, blas.stream(), args)?;
if timed {
@@ -124,7 +128,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
crate::command_profile::add("qsa-index", i, l, started.elapsed());
}
}
self.run_late(blas, &mut plan.late, &mut next, usize::MAX, timed)
self.run_late(blas, &mut late, usize::MAX, timed)
}
fn upload_arena(&self, io: &ArenaIo, uploads: [&[u8]; 3]) -> Result<()> {
let [zero, steps, decode_positions] = uploads;
@@ -147,14 +151,13 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
fn run_late(
&self,
blas: &crate::ple_batch_ffi::Blas,
late: &mut [LateLaunch],
next: &mut usize,
late: &mut LateQueue<'_>,
upto: usize,
timed: bool,
) -> Result<()> {
while *next < late.len() && late[*next].0 <= upto {
while late.next < late.launches.len() && late.launches[late.next].0 <= upto {
let started = std::time::Instant::now();
let (_, grid, entry, block, args) = &mut late[*next];
let (_, grid, entry, block, args) = &mut late.launches[late.next];
self.late.as_ref().ok_or(Error::ContextPoisoned)?.launch(*entry, *grid, *block, blas.stream(), args)?;
if timed {
blas.synchronize()?;
@@ -162,7 +165,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
let label = late_label(*entry, topk);
crate::command_profile::add("qsa-index", if topk { 22 } else { 21 }, label, started.elapsed());
}
*next += 1;
late.next += 1;
}
Ok(())
}
@@ -68,15 +68,22 @@ fn replay_append(io: &ReplayIo, key: ffi::BufferHandle, pos: ffi::BufferHandle,
],
)
}
/// The spans a prefix replay re-appends from: the raw key rows of the accepted rows and the key norm weight.
#[derive(Clone, Copy)]
pub(in super::super) struct ReplayKeySpans {
pub(in super::super) raw: ffi::BufferHandle,
pub(in super::super) gamma: ffi::BufferHandle,
}
impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
/// Re-appends the `t` accepted rows from position `p0` to the resident index image.
pub(in super::super) fn replay_resident_prefix(
&mut self,
p0: usize,
t: usize,
raw: ffi::BufferHandle,
gamma: ffi::BufferHandle,
keys: ReplayKeySpans,
ws: &mut NativeBatchWorkspace<'ctx>,
) -> Result<()> {
let ReplayKeySpans { raw, gamma } = keys;
self.check_replay(p0, t, (raw, gamma), ws)?;
let [status, pooled, tail, dead, bp] = self.replay_handles()?;
let step = self.upload_steps(p0, t)?;
@@ -7,6 +7,19 @@ use super::*;
/// A launch of `qsa_late.cu`: (position in `commands` it runs before, grid, entry, block, arguments).
pub(super) type LateLaunch = (usize, u32, usize, u32, crate::ple_batch_ffi::KernelArguments);
/// The deferred `qsa_late.cu` launches and how many of them have run: they interleave with the recorded commands.
pub(super) struct LateQueue<'a> {
pub(super) launches: &'a mut [LateLaunch],
pub(super) next: usize,
}
/// The rotary parameters of a decode step: the angle base and the device span of the per-head position words.
#[derive(Clone, Copy)]
struct DecodeRope {
theta: f32,
positions: ffi::BufferHandle,
}
/// The arguments of `run_resident_arena`.
#[derive(Clone, Copy)]
pub(super) struct ArenaCall {
@@ -83,18 +96,18 @@ impl ArenaPlan {
shape: [i64; 3],
) -> Result<()> {
match io.positions {
Some(positions) => self.norm_rope_decode(io.theta, data, gamma, positions, shape),
Some(positions) => self.norm_rope_decode(DecodeRope { theta: io.theta, positions }, data, gamma, shape),
None => self.norm_rope_prompt(io, data, gamma, shape),
}
}
fn norm_rope_decode(
&mut self,
theta: f32,
rope: DecodeRope,
data: ffi::BufferHandle,
gamma: ffi::BufferHandle,
positions: ffi::BufferHandle,
shape: [i64; 3],
) -> Result<()> {
let DecodeRope { theta, positions } = rope;
let [heads, width, _] = shape;
let (d, g, w) = (A::Address(data), A::Address(gamma), width as i32);
self.push(Launch::DecodeRms(heads as u32), vec![d, g, A::Address(data), A::I32(w), A::F32(1e-6)])?;
@@ -83,15 +83,16 @@ pub struct OriginalQsaResidentScalarSelection<'lease, 'index, 'weights, 'ctx> {
outputs: [Option<DeviceBuffer<'ctx>>; 5],
batch: Option<OriginalQsaIndexBatch<'index, 'weights, 'ctx>>,
}
/// The host projection inputs of one scalar step.
struct ScalarInputs<'a> {
raw: &'a [f32],
k: &'a [f32],
v: &'a [f32],
qfull: &'a [f32],
index_q: &'a [f32],
/// The host projection rows of one scalar decode step: raw index scores, K, V, full Q and the index query.
#[derive(Clone, Copy)]
pub struct ScalarStepRows<'a> {
pub raw: &'a [f32],
pub k: &'a [f32],
pub v: &'a [f32],
pub qfull: &'a [f32],
pub index_q: &'a [f32],
}
impl ScalarInputs<'_> {
impl ScalarStepRows<'_> {
fn check(&self) -> Result<()> {
let Self { raw, k, v, qfull, index_q } = *self;
if raw.len() != 128 || k.len() != 512 || v.len() != 512 || qfull.len() != 12288 || index_q.len() != 512 {
@@ -169,20 +170,16 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> {
pub fn is_failed(&self) -> bool {
self.workspace.is_failed()
}
#[allow(clippy::too_many_arguments)]
/// Appends one decode row to the live index from `rows` and selects its blocks.
pub fn prepare<'lease, 'index, 'weights>(
&'lease mut self,
resident: &'index mut OriginalQsaResidentIndex<'ctx>,
prior: &OriginalQsaIndexCheckpoint<'ctx>,
raw: &[f32],
k: &[f32],
v: &[f32],
qfull: &[f32],
index_q: &[f32],
from: ResidentContinuation<'index, '_, 'ctx>,
rows: ScalarStepRows<'_>,
weights: [&'weights DeviceBuffer<'ctx>; 4],
ws: &mut NativeBatchWorkspace<'ctx>,
) -> Result<OriginalQsaResidentScalarSelection<'lease, 'index, 'weights, 'ctx>> {
let (inputs, context) = (ScalarInputs { raw, k, v, qfull, index_q }, self.workspace.context);
let ResidentContinuation { resident, prior } = from;
let (inputs, context) = (rows, self.workspace.context);
let p = Self::check_scalar(resident, prior, context, &inputs)?;
let gamma = resident.placed(&mut self.workspace, |w| w.weights(weights, ws))?;
let start = resident.checkpoint(ws)?;
@@ -201,7 +198,7 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> {
resident: &OriginalQsaResidentIndex<'ctx>,
prior: &OriginalQsaIndexCheckpoint<'ctx>,
context: &'ctx Context<'ctx>,
inputs: &ScalarInputs<'_>,
inputs: &ScalarStepRows<'_>,
) -> Result<usize> {
resident.validate_checkpoint(prior)?;
let p = prior.next_position();
@@ -230,7 +227,7 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> {
fn stage_outputs(
&mut self,
context: &'ctx Context<'ctx>,
inputs: &ScalarInputs<'_>,
inputs: &ScalarStepRows<'_>,
) -> Result<(Outputs<'ctx>, [ffi::BufferHandle; 5])> {
let mut outputs: Outputs<'ctx> = std::array::from_fn(|_| None);
if let Err(primary) = self.fill_outputs(context, &mut outputs, inputs) {
@@ -247,7 +244,7 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> {
&mut self,
context: &'ctx Context<'ctx>,
outputs: &mut Outputs<'ctx>,
inputs: &ScalarInputs<'_>,
inputs: &ScalarStepRows<'_>,
) -> Result<()> {
for (i, n) in output_sizes().into_iter().enumerate() {
outputs[i] = Some(context.allocate(n)?)
@@ -274,7 +271,14 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> {
let operation = resident.placed(&mut self.workspace, |workspace| {
check_outputs(workspace, ws, &gamma, &handles)?;
let (raw, qfull, iq) = (workspace.handle(4, 512)?, workspace.handle(7, 49152)?, workspace.handle(8, 2048)?);
workspace.run_resident_arena(p as u32, 1, raw, qfull, iq, gamma, handles, ws, true)
let rows = ArenaRows {
first_position: p as u32,
row_count: 1,
raw_scores: raw,
full_query: qfull,
index_query: iq,
};
workspace.run_resident_arena(rows, IndexProgramSpans { norm_weights: gamma, outputs: handles }, ws, true)
});
if let Err(primary) = operation {
return Ok(Err(primary));
@@ -103,12 +103,12 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
}
Ok(())
}
/// Runs kernel `index` of the transport module on the workspace stream; any failure marks the owners failed.
pub(crate) fn run(
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
index: usize,
grid: [u32; 3],
block: u32,
geometry: LaunchGeometry,
mut a: Arguments,
) -> Result<()> {
self.validate(self.context)?;
@@ -118,7 +118,7 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
self.fail_run(w);
e
})?;
let op = c.driver.api.synchronize().and_then(|()| self.launch_run(w, (index, grid, block), &mut a));
let op = c.driver.api.synchronize().and_then(|()| self.launch_run(w, (index, geometry), &mut a));
let sync = w.blas()?.synchronize();
let pop = g.finish();
if op.is_err() || sync.is_err() || pop.is_err() {
@@ -132,10 +132,10 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
fn launch_run(
&self,
w: &mut NativeBatchWorkspace<'ctx>,
(index, grid, block): (usize, [u32; 3], u32),
(index, geometry): (usize, LaunchGeometry),
a: &mut Arguments,
) -> Result<()> {
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(index, grid, block, 0, w.blas()?.stream(), a)
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(index, geometry, w.blas()?.stream(), a)
}
fn fail_run(&mut self, w: &mut NativeBatchWorkspace<'ctx>) {
self.failed = true;
+5 -3
View File
@@ -107,15 +107,17 @@ pub use qsa_native_batch::{
QSA_NATIVE_BATCH_BYTES, QsaNativeBatchWorkspace, QsaNativeKind, QsaNativePacking, QsaNativeProjections,
};
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub use qsa_native_batch::{QsaGatedAttention, QsaInputWeights, QsaNativeWeight};
pub use qsa_native_decode::{QSA_NATIVE_DECODE_BYTES, QsaNativeDecode, QsaNativeDecodeCompletion};
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub use qsa_prompt_attention::{
QSA_PROMPT_ATTENTION_BYTES, QsaAttentionInputs, QsaPromptAttention, QsaPromptAttentionCompletion,
QSA_PROMPT_ATTENTION_BYTES, QsaAttendedKv, QsaAttentionInputs, QsaPromptAttention, QsaPromptAttentionCompletion,
};
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub use qsa_prompt_index::{
OriginalQsaDeviceSelection, OriginalQsaPromptDevice, OriginalQsaPromptWeights, QSA_PROMPT_INDEX_BYTES,
QsaPromptIndexPrefix, QsaPromptIndexState, QsaPromptIndexWorkspace, QsaPromptSelection,
OriginalQsaDeviceSelection, OriginalQsaPromptDevice, OriginalQsaPromptWeights, OriginalQsaResidentAppendTarget,
QSA_PROMPT_INDEX_BYTES, QsaChunkPrior, QsaChunkRows, QsaIndexPrior, QsaKvAppendTarget, QsaPromptIndexPrefix,
QsaPromptIndexState, QsaPromptIndexWorkspace, QsaPromptSelection, ResidentContinuation, ScalarStepRows,
};
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub use qsa_prompt_kv::{
@@ -273,10 +273,9 @@ impl<'ctx> PromptDevices<'_, 'ctx> {
index.with_completed_before_causal(binding, cache, chunk, |_, _, q, ids, steps| {
let inputs =
leleka_cuda_driver::QsaAttentionInputs::new(q, ids, steps, t).map_err(attention_driver_error)?;
let completed = self
.attention
.attend(self.workspace, self.stage, self.kv, append.final_snapshot(), &inputs)
.map_err(attention_driver_error)?;
let attended =
leleka_cuda_driver::QsaAttendedKv { stage: self.stage, kv: self.kv, snapshot: append.final_snapshot() };
let completed = self.attention.attend(self.workspace, attended, &inputs).map_err(attention_driver_error)?;
if completed.rows() != t {
return Err(Error::IdentityMismatch);
}
@@ -9,7 +9,8 @@ use super::{
};
use crate::model_binding::qwen4exp_input::{BindingIdentity, GrRole, ModelBinding, QsaMatrixRole, QsaWeights};
use leleka_cuda_driver::{
Context, DeviceBuffer, NativeBatchWorkspace, QsaPromptIndexPrefix, QsaPromptIndexWorkspace, QsaPromptSelection,
Context, DeviceBuffer, NativeBatchWorkspace, QsaChunkRows, QsaIndexPrior, QsaPromptIndexPrefix,
QsaPromptIndexWorkspace, QsaPromptSelection,
};
use std::rc::Rc;
fn driver(error: leleka_cuda_driver::Error) -> Error {
@@ -116,7 +117,17 @@ impl<'source, 'lease, 'ctx> QsaDecodeIndex<'source, 'lease, 'ctx> {
let p = u32::try_from(txn.position().get()).map_err(|_| Error::InvalidPosition)?;
let gamma = cache.qsa_norms(entry)?;
let DecodeRows { raw, k, v, qfull, iq } = rows;
owner.append_select_decode(p, &pooled, &tail, &dead, raw, k, v, qfull, iq, gamma, workspace).map_err(driver)
let prior = QsaIndexPrior { pooled: &pooled, tail: &tail, dead: &dead };
let rows = QsaChunkRows {
first_position: p,
row_count: 1,
raw_scores: raw,
keys: k,
values: v,
full_query: qfull,
index_query: iq,
};
owner.append_select_decode(prior, rows, gamma, workspace).map_err(driver)
}
/// The index is closed again when it does not validate against the step it was made for.
fn checked(
@@ -11,7 +11,10 @@ use super::{
use crate::model_binding::qwen4exp_input::{
BindingIdentity, GrRole, ModelBinding, QsaMatrixKind, QsaMatrixRole, QsaWeights,
};
use leleka_cuda_driver::{Context, DeviceBuffer, NativeBatchWorkspace, QsaNativeBatchWorkspace, QsaNativeKind};
use leleka_cuda_driver::{
Context, DeviceBuffer, NativeBatchWorkspace, QsaGatedAttention, QsaInputWeights, QsaNativeBatchWorkspace,
QsaNativeKind, QsaNativeWeight,
};
use std::rc::Rc;
const ROLES: [QsaMatrixRole; 5] =
[QsaMatrixRole::K, QsaMatrixRole::V, QsaMatrixRole::Q, QsaMatrixRole::IndexK, QsaMatrixRole::IndexQ];
@@ -127,7 +127,8 @@ pub(super) fn project_rows<'ctx>(
return Err(Error::InvalidDimension);
}
let (weight, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?;
let output = owner.project_out(t, attended, gates, weight, native(kind)?, workspace).map_err(native_error)?;
let out = QsaNativeWeight { buffer: weight, kind: native(kind)? };
let output = owner.project_out(t, QsaGatedAttention { attended, gates }, out, workspace).map_err(native_error)?;
validate_values(&output, t * 2560)?;
Ok(output)
}
@@ -236,7 +236,8 @@ pub(super) fn project_batches<'ctx>(
let (weights, kinds) = retained_matrices(cache, entry)?;
let mixed = concat_mixed(inputs)?;
let kinds = [native(kinds[0])?, native(kinds[1])?, native(kinds[2])?];
let output = owner.project_inputs(t, &mixed, weights, kinds, workspace).map_err(native_error)?;
let output =
owner.project_inputs(t, &mixed, QsaInputWeights { weights, kinds }, workspace).map_err(native_error)?;
let batches = [output.k, output.v, output.q, output.index_k, output.index_q];
check_batches(&batches, t)?;
Ok(batches)
@@ -6,8 +6,8 @@ use super::super::session::{TargetStepOrigin, chunk::QwenChunkTxn};
use super::*;
use leleka_cuda_driver::{
CompletedQsaKvAppend, NativeBatchWorkspace, OriginalDeviceBlock, OriginalDeviceGrRead, OriginalQsaDeviceSelection,
OriginalQsaPromptDevice, OriginalQsaPromptWeights, QsaNativeKind, QsaPromptAttention, QsaPromptIndexState,
QsaPromptKv, QsaPromptStage,
OriginalQsaPromptDevice, OriginalQsaPromptWeights, QsaChunkPrior, QsaIndexPrior, QsaKvAppendTarget, QsaNativeKind,
QsaNativeWeight, QsaPromptAttention, QsaPromptIndexState, QsaPromptKv, QsaPromptStage,
};
const ROLES: [QsaMatrixRole; 6] = [
QsaMatrixRole::K,
@@ -151,8 +151,14 @@ fn prompt_select<'lease, 'arena, 'loan, 'ctx>(
let norms = cache.qsa_norms(entry)?;
let start = u32::try_from(first).map_err(|_| Error::InvalidPosition)?;
let kinds = [native(kk)?, native(vk)?, native(qk)?, native(ok)?];
let image = QsaIndexPrior { pooled: &pooled, tail: &tail, dead: &dead };
producer
.prepare(read, workspace, start, &pooled, &tail, &dead, OriginalQsaPromptWeights { projections, kinds, norms })
.prepare(
read,
workspace,
QsaChunkPrior { first_position: start, image },
OriginalQsaPromptWeights { projections, kinds, norms },
)
.map_err(device_error)
}
#[allow(clippy::too_many_arguments)]
@@ -231,8 +237,9 @@ impl<'lease, 'arena, 'loan, 'ctx> PromptDeviceQsaSelection<'lease, 'arena, 'loan
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)?;
let (block, index, appended) =
selected.complete(workspace, kv, stage, snapshot, attention, out, native(kind)?).map_err(device_error)?;
let target = QsaKvAppendTarget { kv, stage, prior: snapshot };
let out = QsaNativeWeight { buffer: out, kind: native(kind)? };
let (block, index, appended) = selected.complete(workspace, target, attention, out).map_err(device_error)?;
let state =
PromptDeviceQsaState { binding, origin, context, layer, prior, provider, identities, index, kv: appended };
state.recheck(model, cache, chunk, ctx)?;
@@ -14,8 +14,8 @@ use super::{
};
use crate::model_binding::qwen4exp_input::{BindingIdentity, GrRole, ModelBinding, QsaMatrixRole, QsaWeights};
use leleka_cuda_driver::{
Context, DeviceBuffer, NativeBatchWorkspace, QsaPromptIndexPrefix, QsaPromptIndexState, QsaPromptIndexWorkspace,
QsaPromptSelection,
Context, DeviceBuffer, NativeBatchWorkspace, QsaChunkRows, QsaIndexPrior, QsaPromptIndexPrefix,
QsaPromptIndexState, QsaPromptIndexWorkspace, QsaPromptSelection,
};
use std::rc::Rc;
fn driver(e: leleka_cuda_driver::Error) -> Error {
@@ -105,22 +105,17 @@ impl PromptHost {
) -> Result<QsaPromptSelection<'lease, 'ctx>> {
let (pooled, tail, dead) = prior.native_index_image()?;
let gamma = cache.qsa_norms(entry)?;
owner
.append_select(
u32::try_from(first).map_err(|_| Error::InvalidPosition)?,
t as u32,
&pooled,
&tail,
&dead,
&self.raw,
&self.k,
&self.v,
&self.qfull,
&self.iq,
gamma,
workspace,
)
.map_err(driver)
let prior = QsaIndexPrior { pooled: &pooled, tail: &tail, dead: &dead };
let rows = QsaChunkRows {
first_position: u32::try_from(first).map_err(|_| Error::InvalidPosition)?,
row_count: t as u32,
raw_scores: &self.raw,
keys: &self.k,
values: &self.v,
full_query: &self.qfull,
index_query: &self.iq,
};
owner.append_select(prior, rows, gamma, workspace).map_err(driver)
}
}
/// All original producer/row guards precede role consumption or CUDA writes.
@@ -4,7 +4,10 @@
//! stores all twelve actual seals before joint target/draft publication.
use super::super::super::{input::InputReady, session::QwenSession};
use super::*;
use leleka_cuda_driver::{OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex};
use leleka_cuda_driver::{
OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentAppendTarget, OriginalQsaResidentIndex,
QsaNativeWeight, ResidentContinuation,
};
use leleka_cuda_driver::{
OriginalQsaMappedAppend, OriginalQsaMappedJournal, OriginalQsaMappedPrefix, OriginalQsaResidentTransport,
};
@@ -127,7 +127,8 @@ impl<'ctx> ResidentQsaLayer<'ctx> {
let (origin, layer, identities) = self.begin_prepare(binding, cache, session, inputs, prior, &read)?;
let entry = cache.qsa(binding, layer.get())?;
let weights = resident_weights(cache, entry)?;
let selected = producer.prepare(read, ws, &mut self.index, &prior.0.index, weights).map_err(device_error)?;
let from = ResidentContinuation { resident: &mut self.index, prior: &prior.0.index };
let selected = producer.prepare(read, ws, from, weights).map_err(device_error)?;
origin.validate(session)?;
cache.validate(binding)?;
Ok(ResidentQsaSelection {
@@ -192,8 +192,9 @@ impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, ResidentQsaCompleted<'index, 'weights, 'ctx>)> {
let (ctx, out, kind) = self.check_inputs(model, cache, session)?;
let Self { binding, origin, context, layer, prior, provider, identities, selected, kv } = self;
let target = OriginalQsaResidentAppendTarget { kv, stage, prior: &prior.0.kv };
let (block, index, appended) =
selected.complete(ws, kv, stage, &prior.0.kv, attention, out, kind).map_err(device_error)?;
selected.complete(ws, target, attention, QsaNativeWeight { buffer: out, kind }).map_err(device_error)?;
origin.validate(session)?;
cache.validate(model)?;
cache.retained_context(model, ctx)?;
@@ -4,7 +4,7 @@ use super::impl_residentqsalayer::mint;
use super::*;
use leleka_cuda_driver::{
OriginalQsaResidentScalarIndex, OriginalQsaResidentScalarSelection, QsaAttentionInputs, QsaNativeDecode,
QsaNativeGate,
QsaNativeGate, ResidentContinuation, ScalarStepRows,
};
use std::cell::Cell;
pub(in crate::qwen_forward) struct ResidentQsaScalar<'source, 'lease, 'index, 'weights, 'ctx> {
@@ -34,7 +34,12 @@ impl ScalarHost {
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)
.prepare(
ResidentContinuation { resident, prior },
ScalarStepRows { raw: &self.raw, k: &self.k, v: &self.v, qfull: &self.qfull, index_q: &self.iq },
norms,
workspace,
)
.map_err(driver)
}
}