STRA-338 size2 cd7: qsa_resident_* functions cut into helpers

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 22:00:21 +01:00
parent a337119255
commit a007ffcc33
8 changed files with 753 additions and 511 deletions
@@ -3,6 +3,43 @@
#[allow(unused_imports)]
use super::*;
/// The spans the resident index program reads and writes for one chunk.
struct ResidentSpans {
out: [ffi::BufferHandle; 5],
raw: ffi::BufferHandle,
qfull: ffi::BufferHandle,
iq: ffi::BufferHandle,
}
/// One resident index run: the first position, the row count and the norm weights.
struct ResidentJob {
p: usize,
p0: u32,
t: usize,
gamma: [ffi::BufferHandle; 4],
spans: ResidentSpans,
}
/// 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`).
pub(super) fn lap(mark: &mut Option<std::time::Instant>, index: usize, label: &'static str) {
if let Some(at) = mark {
crate::command_profile::add("qsa", index, label, at.elapsed());
*at = std::time::Instant::now();
}
}
impl ResidentJob {
/// Run the index program in the resident image; the owner stays in flight and unpublished.
fn run_index<'ctx>(
&self,
resident: &mut OriginalQsaResidentIndex<'ctx>,
index: &mut QsaPromptIndexWorkspace<'ctx>,
ws: &mut NativeBatchWorkspace<'ctx>,
) -> Result<()> {
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))
}
}
impl<'ctx> OriginalQsaPromptDevice<'ctx> {
#[allow(clippy::too_many_arguments)]
pub(super) fn prepare_resident<'lease, 'index, 'weights, 'arena, 'loan>(
@@ -13,6 +50,25 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
prior: &OriginalQsaIndexCheckpoint<'ctx>,
weights: OriginalQsaPromptWeights<'weights, 'ctx>,
) -> Result<OriginalQsaResidentSelection<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>> {
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 gamma = weights.norms[3];
let batch = OriginalQsaIndexBatch { owner: resident, start, raw: Some(raw_rows), gamma, rows: t };
Ok(OriginalQsaResidentSelection { owner: self, read, p0, batch })
}
/// The first position `p`, its `u32` form and the row count `t` of a resident chunk, once the index, the chunk and the
/// device budget admit it.
fn resident_bounds(
&self,
read: &OriginalDeviceGrRead<'_, '_, 'ctx>,
resident: &OriginalQsaResidentIndex<'ctx>,
prior: &OriginalQsaIndexCheckpoint<'ctx>,
) -> Result<(usize, u32, usize)> {
resident.validate_checkpoint(prior)?;
if resident.in_flight
|| resident.unpublished
@@ -30,94 +86,99 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
if p.checked_add(t).is_none_or(|end| end > crate::serving_context::geometry().cells()) {
return Err(Error::InvalidQwenShape);
}
self.admit_budget(t)?;
Ok((p, p0, t))
}
fn admit_budget(&self, t: usize) -> Result<()> {
let needed = (t * 512).checked_add(2564 + RESERVE).ok_or(Error::BudgetExceeded)?;
if self.context.allocated_bytes().checked_add(needed).is_none_or(|x| x > self.context.budget_bytes())
|| self.context.memory_info()?.0 < needed
{
return Err(Error::BudgetExceeded);
}
let start = resident.checkpoint(ws)?;
let raw_rows = self.context.allocate(t * 512)?;
let (w, gamma) = self.admit(&read, &weights, ws)?;
let half = common(&read, S::MixedHalf, 5120)?;
let high = common(&read, S::MixedHigh, 5120)?;
let timed = crate::command_profile::enabled();
let mut mark = std::time::Instant::now();
Ok(())
}
/// The five projections of a resident chunk; the clock of the command profile (`None` when it is off) after them.
fn project_resident(
&mut self,
read: &OriginalDeviceGrRead<'_, '_, 'ctx>,
ws: &mut NativeBatchWorkspace<'ctx>,
w: &[ffi::BufferHandle; 6],
weights: &OriginalQsaPromptWeights<'_, 'ctx>,
) -> Result<Option<std::time::Instant>> {
let half = common(read, S::MixedHalf, 5120)?;
let high = common(read, S::MixedHigh, 5120)?;
let mut mark = crate::command_profile::enabled().then(std::time::Instant::now);
for (i, name, n) in [(0, "Kc", 512), (1, "Vc", 512), (2, "Qf", 12288), (3, "idx_raw", 128), (4, "q_idx", 512)] {
self.project(
&read,
ws,
w[i],
if i < 3 { Some(weights.kinds[i]) } else { None },
n,
2560,
if i < 3 { half } else { high },
arena_span(&read, name, n * 4)?,
)?;
if timed {
crate::command_profile::add(
"qsa",
i + 1,
["proj K", "proj V", "proj Q", "proj idxK", "proj idxQ"][i],
mark.elapsed(),
);
mark = std::time::Instant::now();
}
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)?)?;
lap(&mut mark, i + 1, ["proj K", "proj V", "proj Q", "proj idxK", "proj idxQ"][i]);
}
Ok(mark)
}
fn run_spans(&self, read: &OriginalDeviceGrRead<'_, '_, 'ctx>, t: usize) -> Result<ResidentSpans> {
let steps = self
.own(self.steps.as_ref().ok_or(Error::ContextPoisoned)?, self.capacity * 16, 4)?
.checked_subspan(self.capacity * 16, 0, t * 16)?;
let out = [
arena_span(&read, "Kc", 2048)?,
arena_span(&read, "Vc", 2048)?,
arena_span(&read, "q", 24576)?,
arena_span(&read, "sel_ids", CAP * 4)?,
arena_span(read, "Kc", 2048)?,
arena_span(read, "Vc", 2048)?,
arena_span(read, "q", 24576)?,
arena_span(read, "sel_ids", CAP * 4)?,
steps,
];
let raw = arena_span(&read, "idx_raw", 512)?;
let qfull = arena_span(&read, "Qf", 49152)?;
let iq = arena_span(&read, "q_idx", 2048)?;
let raw = arena_span(read, "idx_raw", 512)?;
let qfull = arena_span(read, "Qf", 49152)?;
let iq = arena_span(read, "q_idx", 2048)?;
Ok(ResidentSpans { out, raw, qfull, iq })
}
/// Run the index program, then copy the raw rows into the retained buffer. A failure of either puts the private image
/// back to `start`.
fn run_resident(
&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>,
) -> Result<DeviceBuffer<'ctx>> {
let index = self.index.as_mut().ok_or(Error::ContextPoisoned)?;
resident.in_flight = true;
resident.unpublished = true;
let operation =
resident.placed(index, |w| w.run_resident_arena(p0, t as u32, raw, qfull, iq, gamma, out, ws, false));
if timed {
crate::command_profile::add("qsa", 6, "index+norm+rope run", mark.elapsed());
mark = std::time::Instant::now();
}
if let Err(primary) = operation {
let cleanup = resident.restore_private(ws, &start);
if cleanup.is_ok() {
resident.in_flight = false;
let operation = job.run_index(resident, index, ws);
lap(mark, 6, "index+norm+rope run");
let copied = match operation {
Ok(()) => {
let retained = raw_rows.handle.ok_or(Error::ContextPoisoned)?;
resident.copy_ranges(ws, &[(job.spans.raw, retained, job.t * 512)])
}
if self.context.is_poisoned() {
std::mem::forget(raw_rows)
} else {
drop(raw_rows)
}
return combine(Err(primary), cleanup);
Err(primary) => Err(primary),
};
if let Err(primary) = copied {
return self.abort_resident(resident, ws, start, raw_rows, primary);
}
let retained = raw_rows.handle.ok_or(Error::ContextPoisoned)?;
if let Err(primary) = resident.copy_ranges(ws, &[(raw, retained, t * 512)]) {
let cleanup = resident.restore_private(ws, &start);
if cleanup.is_ok() {
resident.in_flight = false;
}
if self.context.is_poisoned() {
std::mem::forget(raw_rows)
} else {
drop(raw_rows)
}
return combine(Err(primary), cleanup);
lap(mark, 7, "copy raw rows");
resident.provisional_end(job.p + job.t);
Ok(raw_rows)
}
/// Put the private image back to `start` after `primary`; the raw rows are leaked on a poisoned context.
fn abort_resident<T>(
&self,
resident: &mut OriginalQsaResidentIndex<'ctx>,
ws: &mut NativeBatchWorkspace<'ctx>,
start: &OriginalQsaIndexCheckpoint<'ctx>,
raw_rows: DeviceBuffer<'ctx>,
primary: Error,
) -> Result<T> {
let cleanup = resident.restore_private(ws, start);
if cleanup.is_ok() {
resident.in_flight = false;
}
if timed {
crate::command_profile::add("qsa", 7, "copy raw rows", mark.elapsed());
if self.context.is_poisoned() {
std::mem::forget(raw_rows)
} else {
drop(raw_rows)
}
resident.provisional_end(p + t);
let batch =
OriginalQsaIndexBatch { owner: resident, start, raw: Some(raw_rows), gamma: weights.norms[3], rows: t };
Ok(OriginalQsaResidentSelection { owner: self, read, p0, batch })
combine(Err(primary), cleanup)
}
}
impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
@@ -166,37 +227,42 @@ pub(crate) fn kv_stage_spans_of(
read: &OriginalDeviceGrRead<'_, '_, '_>,
rows: usize,
) -> Result<[ffi::BufferHandle; 4]> {
{
let mut spans = Vec::new();
spans.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?;
let runs = crate::serving_context::geometry().stage_runs().map_err(|_| Error::InvalidSize)?;
for (name, bytes) in
[("kv_k_q", runs[0]), ("kv_v_q", runs[1]), ("kv_k_scale", runs[2]), ("kv_v_scale", runs[3])]
{
let (h, n) = read.lease().span(PrefillPhase::Common, name)?;
if n != bytes {
return Err(Error::InvalidQwenShape);
}
h.validate_projection_extent(n, 256)?;
for (old, size) in &spans {
if h.overlaps(n, *old, *size) {
return Err(Error::OutputAliasesInput);
}
}
for (q, nq) in [
(arena_span(read, "Kc", 2048)?, rows * 2048),
(arena_span(read, "Vc", 2048)?, rows * 2048),
(arena_span(read, "q", 24576)?, rows * 24576),
(arena_span(read, "sel_ids", CAP * 4)?, rows * CAP * 4),
(arena_span(read, "attn", 24576)?, rows * 24576),
(common(read, S::Block, 10240)?, rows * 10240),
] {
if h.overlaps(n, q, nq) {
return Err(Error::OutputAliasesInput);
}
}
spans.push((h, n));
let mut spans = Vec::new();
spans.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?;
let runs = crate::serving_context::geometry().stage_runs().map_err(|_| Error::InvalidSize)?;
for (name, bytes) in [("kv_k_q", runs[0]), ("kv_v_q", runs[1]), ("kv_k_scale", runs[2]), ("kv_v_scale", runs[3])] {
let (h, n) = read.lease().span(PrefillPhase::Common, name)?;
if n != bytes {
return Err(Error::InvalidQwenShape);
}
Ok([spans[0].0, spans[1].0, spans[2].0, spans[3].0])
h.validate_projection_extent(n, 256)?;
for (old, size) in &spans {
if h.overlaps(n, *old, *size) {
return Err(Error::OutputAliasesInput);
}
}
stage_clear_of_working(read, rows, (h, n))?;
spans.push((h, n));
}
Ok([spans[0].0, spans[1].0, spans[2].0, spans[3].0])
}
/// A KV stage span must not overlap the working spans of the chunk.
fn stage_clear_of_working(
read: &OriginalDeviceGrRead<'_, '_, '_>,
rows: usize,
(h, n): (ffi::BufferHandle, usize),
) -> Result<()> {
for (q, nq) in [
(arena_span(read, "Kc", 2048)?, rows * 2048),
(arena_span(read, "Vc", 2048)?, rows * 2048),
(arena_span(read, "q", 24576)?, rows * 24576),
(arena_span(read, "sel_ids", CAP * 4)?, rows * CAP * 4),
(arena_span(read, "attn", 24576)?, rows * 24576),
(common(read, S::Block, 10240)?, rows * 10240),
] {
if h.overlaps(n, q, nq) {
return Err(Error::OutputAliasesInput);
}
}
Ok(())
}
@@ -3,6 +3,32 @@
#[allow(unused_imports)]
use super::*;
/// The sealed kernels must be the pinned ones.
fn check_sealed() -> Result<()> {
if GATE_PTX.len() < 2
|| GATE_PTX.last() != Some(&0)
|| GATE_PTX[..GATE_PTX.len() - 1].contains(&0)
|| crate::qwen_ffi::sha256(&GATE_PTX[..GATE_PTX.len() - 1]) != GATE_SHA
{
return Err(Error::UnsupportedQwenOperation);
}
if [INDEX, SELECT, POSTOPS, DECODE_POSTOPS].iter().any(|x| x.starts_with(b"// UNSEALED")) {
return Err(Error::UnsupportedQwenOperation);
}
Ok(())
}
/// The index image holds four 4-byte placeholders instead of the canonical image.
fn resident_sizes(capacity: usize) -> [usize; 11] {
let mut sizes = sizes();
for n in &mut sizes[..4] {
*n = 4;
}
for i in [4, 5, 6, 7, 8] {
sizes[i] = 4
}
sizes[9] = capacity.min(256) * max_blocks() * 4;
sizes
}
impl<'ctx> OriginalQsaPromptDevice<'ctx> {
pub(super) fn new_resident(
context: &'ctx Context<'ctx>,
@@ -12,16 +38,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
let required = OriginalQsaResidentPromptDevice::device_bytes(capacity)?
.checked_add(RESERVE)
.ok_or(Error::BudgetExceeded)?;
if GATE_PTX.len() < 2
|| GATE_PTX.last() != Some(&0)
|| GATE_PTX[..GATE_PTX.len() - 1].contains(&0)
|| crate::qwen_ffi::sha256(&GATE_PTX[..GATE_PTX.len() - 1]) != GATE_SHA
{
return Err(Error::UnsupportedQwenOperation);
}
if [INDEX, SELECT, POSTOPS, DECODE_POSTOPS].iter().any(|x| x.starts_with(b"// UNSEALED")) {
return Err(Error::UnsupportedQwenOperation);
}
check_sealed()?;
if context.is_poisoned() {
return Err(Error::ContextPoisoned);
}
@@ -30,14 +47,15 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
{
return Err(Error::BudgetExceeded);
}
let mut sizes = sizes();
for n in &mut sizes[..4] {
*n = 4;
let sizes = resident_sizes(capacity);
let mut owner = Self::unloaded(context, capacity, packing, sizes);
if let Err(e) = owner.init_resident(sizes) {
let _ = owner.close();
return Err(e);
}
for i in [4, 5, 6, 7, 8] {
sizes[i] = 4
}
sizes[9] = capacity.min(256) * max_blocks() * 4;
Ok(owner)
}
fn unloaded(context: &'ctx Context<'ctx>, capacity: usize, packing: QsaNativePacking, sizes: [usize; 11]) -> Self {
let index = QsaPromptIndexWorkspace {
capacity,
sizes,
@@ -47,7 +65,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
late: None,
failed: false,
};
let mut owner = Self {
Self {
context,
capacity,
packing,
@@ -58,56 +76,56 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
pack: None,
gate: None,
failed: false,
};
let operation = (|| -> Result<()> {
for (i, n) in sizes.into_iter().enumerate() {
owner.index.as_mut().ok_or(Error::ContextPoisoned)?.buffers[i] = Some(context.allocate(n)?)
}
owner.scratch = Some(context.allocate(SCRATCH)?);
owner.steps = Some(context.allocate(capacity * 16)?);
let guard = context.enter().map_err(|e| {
context.poison();
context.retain_driver();
e
})?;
let load = (|| -> Result<()> {
owner.index.as_mut().ok_or(Error::ContextPoisoned)?.module =
Some(Module::load(INDEX, SELECT, POSTOPS, DECODE_POSTOPS)?);
owner.dequant = Some(if crate::prefill_stage::fast_dequant() {
KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES)?
} else {
KernelModule::load(
concat!(include_str!("../offline_native_dequant_f16.ptx"), "\0").as_bytes(),
&[
c"leleka_native_dequant_f16_q4_k",
c"leleka_native_dequant_f16_q5_k",
c"leleka_native_dequant_f16_q6_k",
c"leleka_native_dequant_f16_iq4_xs",
],
)?
});
owner.pack = Some(KernelModule::load(
concat!(include_str!("../qsa_native_batch.ptx"), "\0").as_bytes(),
&[c"qsa_pack", c"qsa_gate_pack", c"qsa_scan_half"],
)?);
owner.gate = Some(KernelModule::load(GATE_PTX, &[c"qsa_prompt_device_gate"])?);
Ok(())
})();
let pop = guard.finish();
if pop.is_err() {
context.poison();
context.retain_driver()
}
combine(load, pop)?;
if context.memory_info()?.0 < RESERVE {
return Err(Error::BudgetExceeded);
}
Ok(())
})();
if let Err(e) = operation {
let _ = owner.close();
return Err(e);
}
Ok(owner)
}
/// Allocate the buffers and load the kernel modules of a fresh resident device; the caller closes it on error.
fn init_resident(&mut self, sizes: [usize; 11]) -> Result<()> {
let context = self.context;
for (i, n) in sizes.into_iter().enumerate() {
self.index.as_mut().ok_or(Error::ContextPoisoned)?.buffers[i] = Some(context.allocate(n)?)
}
self.scratch = Some(context.allocate(SCRATCH)?);
self.steps = Some(context.allocate(self.capacity * 16)?);
let guard = context.enter().map_err(|e| {
context.poison();
context.retain_driver();
e
})?;
let load = self.load_resident_modules();
let pop = guard.finish();
if pop.is_err() {
context.poison();
context.retain_driver()
}
combine(load, pop)?;
if context.memory_info()?.0 < RESERVE {
return Err(Error::BudgetExceeded);
}
Ok(())
}
fn load_resident_modules(&mut self) -> Result<()> {
self.index.as_mut().ok_or(Error::ContextPoisoned)?.module =
Some(Module::load(INDEX, SELECT, POSTOPS, DECODE_POSTOPS)?);
self.dequant = Some(Self::load_dequant()?);
self.pack = Some(KernelModule::load(
concat!(include_str!("../qsa_native_batch.ptx"), "\0").as_bytes(),
&[c"qsa_pack", c"qsa_gate_pack", c"qsa_scan_half"],
)?);
self.gate = Some(KernelModule::load(GATE_PTX, &[c"qsa_prompt_device_gate"])?);
Ok(())
}
fn load_dequant() -> Result<KernelModule> {
if crate::prefill_stage::fast_dequant() {
return KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES);
}
KernelModule::load(
concat!(include_str!("../offline_native_dequant_f16.ptx"), "\0").as_bytes(),
&[
c"leleka_native_dequant_f16_q4_k",
c"leleka_native_dequant_f16_q5_k",
c"leleka_native_dequant_f16_q6_k",
c"leleka_native_dequant_f16_iq4_xs",
],
)
}
}
@@ -1,5 +1,6 @@
//! Moved out of the parent module by STRA-338: impl OriginalQsaResidentSelection, impl Context, impl OriginalQsaResidentPromptDevice.
use super::impl_originalqsapromptdevice::lap;
#[allow(unused_imports)]
use super::*;
@@ -60,12 +61,27 @@ impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
out_kind: QsaNativeKind,
) -> Result<OriginalQsaMappedAppend> {
self.validate(self.owner.context)?;
let t = self.rows();
let bytes = 2560 * (6144 / 256) * native_block(out_kind);
let weight = self.owner.own(out_weight, bytes, 2)?;
// Real Out owner admission again; no weight identity is inferred from
// earlier role bytes or a caller range. Runtime rechecks binding role.
ws.reject_alias(weight, bytes)?;
self.reject_weight_overlap(weight, bytes)?;
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)?;
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)?;
lap(&mut mark, 14, "proj out");
Ok(appended)
}
/// The Out weight must not overlap any buffer of the device or the chunk's working spans.
fn reject_weight_overlap(&self, weight: ffi::BufferHandle, bytes: usize) -> Result<()> {
let t = self.rows();
for b in self
.owner
.index
@@ -89,23 +105,19 @@ impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
if weight.overlaps(bytes, common(&self.read, S::Block, 10240)?, t * 10240) {
return Err(Error::OutputAliasesInput);
}
let timed = crate::command_profile::enabled();
let mut mark = std::time::Instant::now();
let appended = kv.append_resident_arena(ws, stage, prior, &self)?;
if timed {
crate::command_profile::add("qsa", 11, "kv append", mark.elapsed());
mark = std::time::Instant::now();
}
attention.attend_resident_arena(ws, stage, kv, appended.final_prefix(), &self)?;
if timed {
crate::command_profile::add("qsa", 12, "attend", mark.elapsed());
mark = std::time::Instant::now();
}
Ok(())
}
/// The literal strided Qf gate; returns the FP16 half rows it wrote.
fn run_gate(&mut self, ws: &mut NativeBatchWorkspace<'ctx>) -> Result<ffi::BufferHandle> {
let t = self.rows();
let input = arena_span(&self.read, "attn", 24576)?;
let qf = arena_span(&self.read, "Qf", 49152)?;
let half = arena_span(&self.read, "attn_h", 12288)?;
let mut args =
KernelArguments::new(vec![B::Address(input), B::Address(qf), B::Address(half), B::I64(t as i64)]);
let args = KernelArguments::new(vec![B::Address(input), B::Address(qf), B::Address(half), B::I64(t as i64)]);
self.launch_gate(ws, args)?;
Ok(half)
}
fn launch_gate(&mut self, ws: &mut NativeBatchWorkspace<'ctx>, mut args: KernelArguments) -> Result<()> {
let context = self.owner.context;
let blas = ws.blas()?;
let guard = context.enter().map_err(|e| {
@@ -113,19 +125,25 @@ impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
context.retain_driver();
e
})?;
let op = self.owner.gate.as_ref().ok_or(Error::ContextPoisoned)?.launch(
0,
(t * 6144).div_ceil(256) as u32,
256,
blas.stream(),
&mut args,
);
let blocks = (self.rows() * 6144).div_ceil(256) as u32;
let op =
self.owner.gate.as_ref().ok_or(Error::ContextPoisoned)?.launch(0, blocks, 256, blas.stream(), &mut args);
let sync = blas.synchronize();
let pop = guard.finish();
self.settle_gate(ws, (op, sync, pop), args)
}
/// Poison the context when the gate, its synchronisation or the context pop failed; the arguments are leaked then
/// when the device may still read them.
fn settle_gate(
&mut self,
ws: &mut NativeBatchWorkspace<'ctx>,
(op, sync, pop): (Result<()>, Result<()>, Result<()>),
args: KernelArguments,
) -> Result<()> {
if op.is_err() || sync.is_err() || pop.is_err() {
self.owner.failed = true;
context.poison();
context.retain_driver()
self.owner.context.poison();
self.owner.context.retain_driver()
}
if sync.is_err() || pop.is_err() {
std::mem::forget(args)
@@ -133,26 +151,8 @@ impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
let result = combine(combine(op, sync), pop);
if result.is_err() {
ws.mark_failed();
return result.map(|()| unreachable!("failed gate"));
}
if timed {
crate::command_profile::add("qsa", 13, "gate", mark.elapsed());
mark = std::time::Instant::now();
}
self.owner.project(
&self.read,
ws,
weight,
Some(out_kind),
2560,
6144,
half,
common(&self.read, S::Block, 10240)?,
)?;
if timed {
crate::command_profile::add("qsa", 14, "proj out", mark.elapsed());
}
Ok(appended)
result
}
}
impl<'ctx> Context<'ctx> {
@@ -23,24 +23,18 @@ impl<'index, 'weights, 'ctx> OriginalQsaIndexBatch<'index, 'weights, 'ctx> {
if self.owner.end != self.start.next_position() + self.rows {
return Err(Error::InvalidQwenShape);
}
let saved = self.owner.save(ws)?;
self.owner.in_flight = false;
self.owner.unpublished = false;
if let Some(raw) = self.raw.take() {
raw.release()?;
}
return Ok(saved);
return self.publish(ws);
}
self.owner.restore_private(ws, &self.start)?;
if accepted > 0 {
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))?;
self.replay_accepted(ws, workspace, accepted)?;
}
self.owner.end = self.start.next_position() + accepted;
self.owner.coverage.end.set(self.owner.end);
self.publish(ws)
}
/// Save the image as the new checkpoint, leave the in-flight state and release the raw rows.
fn publish(&mut self, ws: &mut NativeBatchWorkspace<'ctx>) -> Result<OriginalQsaIndexCheckpoint<'ctx>> {
let saved = self.owner.save(ws)?;
self.owner.in_flight = false;
self.owner.unpublished = false;
@@ -49,6 +43,17 @@ impl<'index, 'weights, 'ctx> OriginalQsaIndexBatch<'index, 'weights, 'ctx> {
}
Ok(saved)
}
fn replay_accepted(
&mut self,
ws: &mut NativeBatchWorkspace<'ctx>,
workspace: &mut QsaPromptIndexWorkspace<'ctx>,
accepted: usize,
) -> Result<()> {
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))
}
pub fn abort(
&mut self,
ws: &mut NativeBatchWorkspace<'ctx>,
@@ -17,7 +17,14 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
{
return Err(Error::BudgetExceeded);
}
let mut s = Self {
let mut s = Self::empty(context);
if let Err(e) = s.init_image() {
return combine(Err(e), s.close());
}
Ok(s)
}
fn empty(context: &'ctx Context<'ctx>) -> Self {
Self {
context,
origin: Rc::new(Origin),
epoch: 0,
@@ -29,34 +36,26 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
in_flight: false,
unpublished: false,
pool: Rc::new(RefCell::new(Vec::new())),
};
let op = (|| -> Result<()> {
s.copy = Some(Transfer::new()?);
// One-time bounded initialization, never a whole host index image. Each
// upload owns its actual staging until completion; no 33MiB host allocation.
let zero = [0u8; 65536];
for (i, n) in [sizes()[0], 1536, 512, 4].into_iter().enumerate() {
s.image[i] = Some(context.allocate(n)?);
let b = s.image[i].as_mut().ok_or(Error::ContextPoisoned)?;
for offset in (0..n).step_by(zero.len()) {
b.copy_from_range(offset, &zero[..(n - offset).min(zero.len())]).map_err(|e| {
if !matches!(e, Error::HostAllocation) {
context.poison();
context.retain_driver();
}
e
})?;
}
}
if context.memory_info()?.0 < RESERVE {
return Err(Error::BudgetExceeded);
}
Ok(())
})();
if let Err(e) = op {
return combine(Err(e), s.close());
}
Ok(s)
}
fn init_image(&mut self) -> Result<()> {
let context = self.context;
self.copy = Some(Transfer::new()?);
// One-time bounded initialization, never a whole host index image. Each
// upload owns its actual staging until completion; no 33MiB host allocation.
let zero = [0u8; 65536];
for (i, n) in [sizes()[0], 1536, 512, 4].into_iter().enumerate() {
self.image[i] = Some(context.allocate(n)?);
let b = self.image[i].as_mut().ok_or(Error::ContextPoisoned)?;
for offset in (0..n).step_by(zero.len()) {
b.copy_from_range(offset, &zero[..(n - offset).min(zero.len())])
.map_err(|e| poison_unless_host_allocation(context, e))?;
}
}
if context.memory_info()?.0 < RESERVE {
return Err(Error::BudgetExceeded);
}
Ok(())
}
pub fn is_failed(&self) -> bool {
self.failed || self.context.is_poisoned()
@@ -195,6 +194,28 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
indices: &mut [&mut OriginalQsaResidentIndex<'ctx>],
ws: &mut NativeBatchWorkspace<'ctx>,
) -> Result<Vec<OriginalQsaIndexCheckpoint<'ctx>>> {
let first = Self::fenced_context(indices, ws)?;
let mut buffers: Vec<DeviceBuffer<'ctx>> = Vec::new();
buffers.try_reserve_exact(indices.len()).map_err(|_| Error::HostAllocation)?;
let mut copies = Vec::new();
copies.try_reserve_exact(4 * indices.len()).map_err(|_| Error::HostAllocation)?;
let staged = Self::stage_fenced(indices, &mut buffers, &mut copies);
let copied = staged
.and_then(|()| indices[0].copy.as_ref().ok_or(Error::ContextPoisoned)?.copy_fenced(first, ws, &copies));
if let Err(e) = copied {
for i in indices.iter_mut() {
i.failed = true
}
Self::release_fenced(first, buffers);
return Err(e);
}
Ok(indices.iter().zip(buffers).map(|(i, b)| i.saved(b)).collect())
}
/// The shared context of idle, valid indices that a fenced checkpoint may copy.
fn fenced_context(
indices: &[&mut OriginalQsaResidentIndex<'ctx>],
ws: &NativeBatchWorkspace<'ctx>,
) -> Result<&'ctx Context<'ctx>> {
let first = indices.first().ok_or(Error::InvalidQwenShape)?.context;
for i in indices.iter() {
i.validate()?;
@@ -206,42 +227,37 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
}
}
ws.validate_context(first)?;
let mut buffers: Vec<DeviceBuffer<'ctx>> = Vec::new();
buffers.try_reserve_exact(indices.len()).map_err(|_| Error::HostAllocation)?;
let mut copies = Vec::new();
copies.try_reserve_exact(4 * indices.len()).map_err(|_| Error::HostAllocation)?;
let staged = (|| -> Result<()> {
for i in indices.iter() {
let b = i.checkpoint_buffer()?;
let h = b.handle.ok_or(Error::ContextPoisoned)?;
buffers.push(b);
for (src, dst, n) in i.save_ranges(h)? {
if n == 0 || src.overlaps(n, dst, n) {
return Err(Error::OutputAliasesInput);
}
src.validate_projection_extent(n, 1)?;
dst.validate_projection_extent(n, 1)?;
copies.push((src.qwen_address(), dst.qwen_address(), n));
Ok(first)
}
/// A checkpoint buffer per index and the copies that fill them.
fn stage_fenced(
indices: &[&mut OriginalQsaResidentIndex<'ctx>],
buffers: &mut Vec<DeviceBuffer<'ctx>>,
copies: &mut Vec<(u64, u64, usize)>,
) -> Result<()> {
for i in indices.iter() {
let b = i.checkpoint_buffer()?;
let h = b.handle.ok_or(Error::ContextPoisoned)?;
buffers.push(b);
for (src, dst, n) in i.save_ranges(h)? {
if n == 0 || src.overlaps(n, dst, n) {
return Err(Error::OutputAliasesInput);
}
src.validate_projection_extent(n, 1)?;
dst.validate_projection_extent(n, 1)?;
copies.push((src.qwen_address(), dst.qwen_address(), n));
}
}
Ok(())
}
fn release_fenced(first: &Context<'_>, buffers: Vec<DeviceBuffer<'ctx>>) {
for b in buffers {
if first.is_poisoned() {
std::mem::forget(b)
} else {
let _ = b.release();
}
Ok(())
})();
let copied = staged
.and_then(|()| indices[0].copy.as_ref().ok_or(Error::ContextPoisoned)?.copy_fenced(first, ws, &copies));
if let Err(e) = copied {
for i in indices.iter_mut() {
i.failed = true
}
for b in buffers {
if first.is_poisoned() {
std::mem::forget(b)
} else {
let _ = b.release();
}
}
return Err(e);
}
Ok(indices.iter().zip(buffers).map(|(i, b)| i.saved(b)).collect())
}
pub fn restore(&mut self, ws: &mut NativeBatchWorkspace<'ctx>, s: &OriginalQsaIndexCheckpoint<'ctx>) -> Result<()> {
if self.in_flight {
@@ -250,3 +266,11 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
self.restore_private(ws, s)
}
}
/// Poison the context unless `e` is a host allocation failure (no device state was touched); `e` passes through.
pub(super) fn poison_unless_host_allocation(context: &Context<'_>, e: Error) -> Error {
if !matches!(e, Error::HostAllocation) {
context.poison();
context.retain_driver();
}
e
}
@@ -1,8 +1,26 @@
//! Moved out of the parent module by STRA-338: impl OriginalQsaResidentIndex (2), impl OriginalQsaResidentIndex, impl Drop_for_OriginalQsaResidentIndex, impl OriginalQsaResidentIndex.
use super::impl_originalqsaresidentindex::poison_unless_host_allocation;
#[allow(unused_imports)]
use super::*;
/// The resident image swapped into a prompt-index workspace for the length of a run; dropping it swaps both back.
struct Placement<'a, 'ctx> {
owner: &'a mut OriginalQsaResidentIndex<'ctx>,
workspace: &'a mut QsaPromptIndexWorkspace<'ctx>,
sizes: [usize; 4],
}
impl Drop for Placement<'_, '_> {
fn drop(&mut self) {
for i in 0..4 {
std::mem::swap(&mut self.owner.image[i], &mut self.workspace.buffers[i]);
self.workspace.sizes[i] = self.sizes[i];
}
if self.workspace.is_failed() {
self.owner.failed = true
}
}
}
impl<'ctx> OriginalQsaResidentIndex<'ctx> {
pub(in super::super) fn restore_private(
&mut self,
@@ -35,22 +53,6 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
if !std::ptr::eq(self.context, w.context) {
return Err(Error::ContextMismatch);
}
struct Placement<'a, 'ctx> {
owner: &'a mut OriginalQsaResidentIndex<'ctx>,
workspace: &'a mut QsaPromptIndexWorkspace<'ctx>,
sizes: [usize; 4],
}
impl Drop for Placement<'_, '_> {
fn drop(&mut self) {
for i in 0..4 {
std::mem::swap(&mut self.owner.image[i], &mut self.workspace.buffers[i]);
self.workspace.sizes[i] = self.sizes[i];
}
if self.workspace.is_failed() {
self.owner.failed = true
}
}
}
let image_sizes = [sizes()[0], 1536, 512, 4];
let sizes = std::array::from_fn(|i| w.sizes[i]);
for i in 0..4 {
@@ -70,21 +72,10 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
let zero = [0u8; 1536];
for b in self.image[1..].iter_mut().flatten() {
let n = b.len();
b.copy_from(&zero[..n]).map_err(|e| {
if !matches!(e, Error::HostAllocation) {
self.context.poison();
self.context.retain_driver();
}
e
})?;
b.copy_from(&zero[..n]).map_err(|e| poison_unless_host_allocation(self.context, e))?;
}
self.image[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0, &zero[..512]).map_err(|e| {
if !matches!(e, Error::HostAllocation) {
self.context.poison();
self.context.retain_driver();
}
e
})?;
let first = self.image[0].as_mut().ok_or(Error::ContextPoisoned)?;
first.copy_from_range(0, &zero[..512]).map_err(|e| poison_unless_host_allocation(self.context, e))?;
self.coverage.end.set(0);
self.coverage = Rc::new(Coverage { end: Cell::new(0) });
self.end = 0;
@@ -209,6 +200,24 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
tail: &[u8],
end: usize,
) -> Result<OriginalQsaIndexCheckpoint<'ctx>> {
self.validate_import(spans, tail, end)?;
for (first, bytes) in spans {
self.image[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(first * Self::ROW_BYTES, bytes)?;
}
let b = self.parked_tail(tail)?;
let parked = OriginalQsaIndexCheckpoint(Rc::new(Saved {
origin: self.origin.clone(),
epoch: self.epoch,
coverage: Rc::new(Coverage { end: Cell::new(end) }),
end,
bytes: b,
pool: Rc::downgrade(&self.pool),
}));
self.restore_private(ws, &parked)?;
drop(parked);
self.save(ws)
}
fn validate_import(&self, spans: &[(usize, &[u8])], tail: &[u8], end: usize) -> Result<()> {
self.validate()?;
if self.in_flight {
return Err(Error::InvalidQwenShape);
@@ -224,9 +233,10 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
return Err(Error::InvalidQwenShape);
}
}
for (first, bytes) in spans {
self.image[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(first * Self::ROW_BYTES, bytes)?;
}
Ok(())
}
/// A checkpoint buffer holding the parked `tail`; released (or leaked on a poisoned context) when the upload fails.
fn parked_tail(&self, tail: &[u8]) -> Result<DeviceBuffer<'ctx>> {
let mut b = self.checkpoint_buffer()?;
if let Err(e) = b.copy_from(tail) {
if self.context.is_poisoned() {
@@ -236,16 +246,6 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
}
return Err(e);
}
let parked = OriginalQsaIndexCheckpoint(Rc::new(Saved {
origin: self.origin.clone(),
epoch: self.epoch,
coverage: Rc::new(Coverage { end: Cell::new(end) }),
end,
bytes: b,
pool: Rc::downgrade(&self.pool),
}));
self.restore_private(ws, &parked)?;
drop(parked);
self.save(ws)
Ok(b)
}
}
@@ -3,6 +3,71 @@
#[allow(unused_imports)]
use super::*;
/// The device spans one accepted-prefix replay reads and writes.
struct ReplayIo {
raw: ffi::BufferHandle,
gamma: ffi::BufferHandle,
step: ffi::BufferHandle,
status: ffi::BufferHandle,
pooled: ffi::BufferHandle,
tail: ffi::BufferHandle,
dead: ffi::BufferHandle,
bp: ffi::BufferHandle,
}
/// The launches of a replay and the step rows they read.
type ReplayWork<'ctx> = (Vec<(Launch, Arguments)>, DeviceBuffer<'ctx>);
/// The position rows `[p, p + 1, (p + 1) / 4, min(p + 1, CAP)]` of `t` rows from `p0`, as little-endian `i32`.
fn replay_steps(p0: usize, t: usize) -> Result<Vec<u8>> {
let mut steps = Vec::new();
steps.try_reserve_exact(t * 16).map_err(|_| Error::HostAllocation)?;
for row in 0..t {
let p = p0 + row;
for x in [p, p + 1, (p + 1) / 4, (p + 1).min(CAP)] {
steps.extend((x as i32).to_le_bytes());
}
}
Ok(steps)
}
/// The decode-append launch and the three finite scans of every replayed row.
fn replay_commands(p0: usize, t: usize, io: &ReplayIo) -> Result<Vec<(Launch, Arguments)>> {
let mut commands = Vec::new();
commands.try_reserve_exact(t * 4).map_err(|_| Error::HostAllocation)?;
let theta = crate::qsa_index_ffi::theta();
if !theta.is_finite() || theta <= 0.0 {
return Err(Error::InvalidDriverValue("QSA theta"));
}
for row in 0..t {
let p = p0 + row;
let key = io.raw.checked_subspan(t * 512, row * 512, 512)?;
let pos = io.step.checked_subspan(t * 16, row * 16, 4)?;
commands.push((Launch::DecodeAppend, replay_append(io, key, pos, theta)?));
for (h, n) in [(io.pooled, ((p + 1) / 4 + 1) * 128), (io.tail, 384), (io.dead, 128)] {
commands.push((
Launch::Scan(n as u32),
Arguments::new(vec![A::Address(h), A::I64(n as i64), A::Address(io.status), A::U32(0)])?,
));
}
}
Ok(commands)
}
fn replay_append(io: &ReplayIo, key: ffi::BufferHandle, pos: ffi::BufferHandle, theta: f32) -> Result<Arguments> {
Arguments::for_launch(
Launch::DecodeAppend,
vec![
A::Address(key),
A::Address(pos),
A::I32(0),
A::Address(io.gamma),
A::F32(1e-6),
A::Address(io.tail),
A::Address(io.dead),
A::Address(io.pooled),
A::Address(io.bp),
A::I32(crate::serving_context::geometry().cells() as i32),
A::F32(theta),
],
)
}
impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
pub(in super::super) fn replay_resident_prefix(
&mut self,
@@ -11,6 +76,29 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
raw: ffi::BufferHandle,
gamma: ffi::BufferHandle,
ws: &mut NativeBatchWorkspace<'ctx>,
) -> Result<()> {
self.check_replay(p0, t, (raw, gamma), ws)?;
let status = self.handle(10, 64)?;
let pooled = self.handle(0, self.sizes[0])?;
let tail = self.handle(1, 1536)?;
let dead = self.handle(2, 512)?;
let bp = self.handle(3, 4)?;
let steps = replay_steps(p0, t)?;
let mut step = self.context.allocate(t * 16)?;
step.copy_from(&steps)?;
let sh = step.handle.ok_or(Error::ContextPoisoned)?;
let io = ReplayIo { raw, gamma, step: sh, status, pooled, tail, dead, bp };
let commands = replay_commands(p0, t, &io)?;
let mut flags = [0u8; 64];
self.run_replay(ws, status, (commands, step), &mut flags)?;
self.check_replay_flags(&flags)
}
fn check_replay(
&self,
p0: usize,
t: usize,
(raw, gamma): (ffi::BufferHandle, ffi::BufferHandle),
ws: &NativeBatchWorkspace<'ctx>,
) -> Result<()> {
if !(1..=8192).contains(&t) || p0.checked_add(t).is_none_or(|x| x > crate::serving_context::geometry().cells())
{
@@ -18,59 +106,15 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
}
ws.validate_context(self.context)?;
raw.validate_projection_extent(t * 512, 4)?;
gamma.validate_projection_extent(512, 4)?;
let status = self.handle(10, 64)?;
let pooled = self.handle(0, self.sizes[0])?;
let tail = self.handle(1, 1536)?;
let dead = self.handle(2, 512)?;
let bp = self.handle(3, 4)?;
let mut steps = Vec::new();
steps.try_reserve_exact(t * 16).map_err(|_| Error::HostAllocation)?;
for row in 0..t {
let p = p0 + row;
for x in [p, p + 1, (p + 1) / 4, (p + 1).min(CAP)] {
steps.extend((x as i32).to_le_bytes());
}
}
let mut step = self.context.allocate(t * 16)?;
step.copy_from(&steps)?;
let sh = step.handle.ok_or(Error::ContextPoisoned)?;
let mut commands = Vec::new();
commands.try_reserve_exact(t * 4).map_err(|_| Error::HostAllocation)?;
let theta = crate::qsa_index_ffi::theta();
if !theta.is_finite() || theta <= 0.0 {
return Err(Error::InvalidDriverValue("QSA theta"));
}
for row in 0..t {
let p = p0 + row;
let key = raw.checked_subspan(t * 512, row * 512, 512)?;
let pos = sh.checked_subspan(t * 16, row * 16, 4)?;
commands.push((
Launch::DecodeAppend,
Arguments::for_launch(
Launch::DecodeAppend,
vec![
A::Address(key),
A::Address(pos),
A::I32(0),
A::Address(gamma),
A::F32(1e-6),
A::Address(tail),
A::Address(dead),
A::Address(pooled),
A::Address(bp),
A::I32(crate::serving_context::geometry().cells() as i32),
A::F32(theta),
],
)?,
));
for (h, n) in [(pooled, ((p + 1) / 4 + 1) * 128), (tail, 384), (dead, 128)] {
commands.push((
Launch::Scan(n as u32),
Arguments::new(vec![A::Address(h), A::I64(n as i64), A::Address(status), A::U32(0)])?,
));
}
}
gamma.validate_projection_extent(512, 4)
}
fn run_replay(
&mut self,
ws: &mut NativeBatchWorkspace<'ctx>,
status: ffi::BufferHandle,
mut work: ReplayWork<'ctx>,
flags: &mut [u8; 64],
) -> Result<()> {
let c = self.context;
let g = c.enter().map_err(|e| {
self.failed = true;
@@ -80,35 +124,46 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
e
})?;
let blas = ws.blas()?;
let zero = [0u8; 64];
let mut flags = [0u8; 64];
let op = (|| -> Result<()> {
c.driver.api.copy_from(status, &zero)?;
c.driver.api.copy_from(status, &[0u8; 64])?;
c.driver.api.synchronize()?;
for (shape, args) in &mut commands {
for (shape, args) in &mut work.0 {
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(*shape, blas.stream(), args)?;
}
Ok(())
})();
let sync = blas.synchronize();
let read = if sync.is_ok() { c.driver.api.copy_to(status, &mut flags) } else { Ok(()) };
let read = if sync.is_ok() { c.driver.api.copy_to(status, flags) } else { Ok(()) };
let pop = g.finish();
self.settle_replay(ws, (op, sync, read, pop), work)
}
/// Poison the context when any step of the replay failed; the launches are leaked when the device may still read them.
fn settle_replay(
&mut self,
ws: &mut NativeBatchWorkspace<'ctx>,
(op, sync, read, pop): (Result<()>, Result<()>, Result<()>, Result<()>),
work: ReplayWork<'ctx>,
) -> Result<()> {
if op.is_err() || sync.is_err() || read.is_err() || pop.is_err() {
let c = self.context;
self.failed = true;
ws.mark_failed();
c.poison();
c.retain_driver();
if sync.is_err() || pop.is_err() {
std::mem::forget((commands, step));
std::mem::forget(work);
}
return combine(combine(combine(op, sync), read), pop);
}
Ok(())
}
fn check_replay_flags(&mut self, flags: &[u8; 64]) -> Result<()> {
if flags[4..].iter().any(|x| *x != 0)
|| u32::from_le_bytes(flags[..4].try_into().map_err(|_| Error::InvalidSize)?) > 1
{
self.failed = true;
c.poison();
c.retain_driver();
self.context.poison();
self.context.retain_driver();
return Err(Error::InvalidDriverValue("QSA replay finite flags"));
}
if flags[0] != 0 {
@@ -1,9 +1,26 @@
//! Literal T1 native append/FP32 decode scores over the actual live index.
//! Host scalar projection inputs are genuine inputs, never prior-state images.
use super::*;
type Outputs<'ctx> = [Option<DeviceBuffer<'ctx>>; 5];
pub struct OriginalQsaResidentScalarIndex<'ctx> {
workspace: QsaPromptIndexWorkspace<'ctx>,
}
/// The index buffers of a scalar index: the image is four 4-byte placeholders.
fn scalar_index_sizes() -> [usize; 11] {
let mut sizes = sizes();
for n in &mut sizes[..4] {
*n = 4;
}
sizes[4] = 608;
sizes[7] = 49152;
sizes[8] = 2048;
sizes[9] = max_blocks() * 4;
sizes
}
/// The sizes of the five outputs: K, V, the query, the selected ids and the finite flags.
fn output_sizes() -> [usize; 5] {
[2048, 2048, 24576, CAP * 4, 16]
}
impl<'ctx> Context<'ctx> {
pub fn original_qsa_resident_scalar_index(&'ctx self) -> Result<OriginalQsaResidentScalarIndex<'ctx>> {
if self.is_poisoned() {
@@ -12,21 +29,8 @@ impl<'ctx> Context<'ctx> {
if [INDEX, SELECT, POSTOPS, DECODE_POSTOPS].iter().any(|x| x.starts_with(b"// UNSEALED")) {
return Err(Error::UnsupportedQwenOperation);
}
let mut sizes = sizes();
for n in &mut sizes[..4] {
*n = 4;
}
sizes[4] = 608;
sizes[7] = 49152;
sizes[8] = 2048;
sizes[9] = max_blocks() * 4;
let bytes = sizes.iter().try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))?;
let peak = bytes.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?;
if self.allocated_bytes().checked_add(peak).is_none_or(|n| n > self.budget_bytes())
|| self.memory_info()?.0 < peak
{
return Err(Error::BudgetExceeded);
}
let sizes = scalar_index_sizes();
self.admit_scalar_index(&sizes)?;
let mut workspace = QsaPromptIndexWorkspace {
capacity: 1,
sizes,
@@ -36,39 +40,128 @@ impl<'ctx> Context<'ctx> {
late: None,
failed: false,
};
let operation = (|| -> Result<()> {
for (i, n) in sizes.into_iter().enumerate() {
workspace.buffers[i] = Some(self.allocate(n)?)
}
let g = self.enter().map_err(|e| {
self.poison();
self.retain_driver();
e
})?;
let load = Module::load(INDEX, SELECT, POSTOPS, DECODE_POSTOPS);
let pop = g.finish();
if pop.is_err() {
self.poison();
self.retain_driver()
}
workspace.module = Some(load?);
pop?;
if self.memory_info()?.0 < RESERVE {
return Err(Error::BudgetExceeded);
}
Ok(())
})();
if let Err(primary) = operation {
if let Err(primary) = self.load_scalar_index(&mut workspace, sizes) {
return combine(Err(primary), workspace.close());
}
Ok(OriginalQsaResidentScalarIndex { workspace })
}
fn admit_scalar_index(&self, sizes: &[usize; 11]) -> Result<()> {
let bytes = sizes.iter().try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))?;
let peak = bytes.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?;
if self.allocated_bytes().checked_add(peak).is_none_or(|n| n > self.budget_bytes())
|| self.memory_info()?.0 < peak
{
return Err(Error::BudgetExceeded);
}
Ok(())
}
fn load_scalar_index(&'ctx self, workspace: &mut QsaPromptIndexWorkspace<'ctx>, sizes: [usize; 11]) -> Result<()> {
for (i, n) in sizes.into_iter().enumerate() {
workspace.buffers[i] = Some(self.allocate(n)?)
}
let g = self.enter().map_err(|e| {
self.poison();
self.retain_driver();
e
})?;
let load = Module::load(INDEX, SELECT, POSTOPS, DECODE_POSTOPS);
let pop = g.finish();
if pop.is_err() {
self.poison();
self.retain_driver()
}
workspace.module = Some(load?);
pop?;
if self.memory_info()?.0 < RESERVE {
return Err(Error::BudgetExceeded);
}
Ok(())
}
}
pub struct OriginalQsaResidentScalarSelection<'lease, 'index, 'weights, 'ctx> {
workspace: &'lease mut QsaPromptIndexWorkspace<'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],
}
impl ScalarInputs<'_> {
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 {
return Err(Error::InvalidQwenShape);
}
if [raw, k, v, qfull, index_q].iter().any(|x| x.iter().any(|v| !v.is_finite())) {
return Err(Error::NonFiniteMmqOutput("QSA native scalar input"));
}
Ok(())
}
}
/// A scalar output must not overlap the workspace, the norm weights or the outputs before it.
fn output_clear_of_others(
(i, h): (usize, ffi::BufferHandle),
gamma: &[ffi::BufferHandle; 4],
handles: &[ffi::BufferHandle; 5],
) -> Result<()> {
let sizes = output_sizes();
for (j, g) in gamma.iter().enumerate() {
if h.overlaps(sizes[i], *g, if j < 2 { 1024 } else { 512 }) {
return Err(Error::OutputAliasesInput);
}
}
for (j, old) in handles[..i].iter().enumerate() {
if h.overlaps(sizes[i], *old, sizes[j]) {
return Err(Error::OutputAliasesInput);
}
}
Ok(())
}
fn check_outputs(
workspace: &QsaPromptIndexWorkspace<'_>,
ws: &NativeBatchWorkspace<'_>,
gamma: &[ffi::BufferHandle; 4],
handles: &[ffi::BufferHandle; 5],
) -> Result<()> {
let sizes = output_sizes();
for (i, h) in handles.iter().enumerate() {
h.validate_projection_extent(sizes[i], 4)?;
ws.reject_alias(*h, sizes[i])?;
for b in workspace.buffers.iter().flatten() {
if h.overlaps(sizes[i], b.handle.ok_or(Error::ContextPoisoned)?, b.len()) {
return Err(Error::OutputAliasesInput);
}
}
output_clear_of_others((i, *h), gamma, handles)?;
}
Ok(())
}
/// Release the outputs after `primary`; they and the raw rows are leaked on a poisoned context.
fn abort_scalar<'ctx, T>(
context: &Context<'ctx>,
resident: &mut OriginalQsaResidentIndex<'ctx>,
ws: &mut NativeBatchWorkspace<'ctx>,
(start, outputs, raw_rows): (&OriginalQsaIndexCheckpoint<'ctx>, Outputs<'ctx>, DeviceBuffer<'ctx>),
primary: Error,
) -> Result<T> {
let cleanup = resident.restore_private(ws, start);
if cleanup.is_ok() {
resident.in_flight = false
}
if context.is_poisoned() {
std::mem::forget((outputs, raw_rows))
} else {
for b in outputs.into_iter().flatten() {
let _ = b.release();
}
}
combine(Err(primary), cleanup)
}
impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> {
pub fn allocated_bytes(&self) -> usize {
self.workspace.allocated_bytes()
@@ -89,9 +182,29 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> {
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 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)?;
let raw_rows = context.allocate(512)?;
let (outputs, handles) = self.stage_outputs(context, &inputs)?;
let copied = self.run_scalar(resident, ws, (p, gamma, handles), &raw_rows)?;
if let Err(primary) = copied {
return abort_scalar(context, resident, ws, (&start, outputs, raw_rows), primary);
}
resident.provisional_end(p + 1);
let batch = OriginalQsaIndexBatch { owner: resident, start, raw: Some(raw_rows), gamma: weights[3], rows: 1 };
Ok(OriginalQsaResidentScalarSelection { workspace: &mut self.workspace, outputs, batch: Some(batch) })
}
/// The position of the step, once the index, the inputs and the device budget admit it.
fn check_scalar(
resident: &OriginalQsaResidentIndex<'ctx>,
prior: &OriginalQsaIndexCheckpoint<'ctx>,
context: &'ctx Context<'ctx>,
inputs: &ScalarInputs<'_>,
) -> Result<usize> {
resident.validate_checkpoint(prior)?;
let p = prior.next_position();
let context = self.workspace.context;
if resident.in_flight
|| resident.unpublished
|| resident.next_position() != p
@@ -100,36 +213,23 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> {
{
return Err(Error::InvalidQwenShape);
}
if raw.len() != 128 || k.len() != 512 || v.len() != 512 || qfull.len() != 12288 || index_q.len() != 512 {
return Err(Error::InvalidQwenShape);
}
if [raw, k, v, qfull, index_q].iter().any(|x| x.iter().any(|v| !v.is_finite())) {
return Err(Error::NonFiniteMmqOutput("QSA native scalar input"));
}
inputs.check()?;
let peak = 2564 + 512 + (512 * 2 + 6144 + CAP + 4) * 4 + RESERVE;
if context.allocated_bytes().checked_add(peak).is_none_or(|n| n > context.budget_bytes())
|| context.memory_info()?.0 < peak
{
return Err(Error::BudgetExceeded);
}
let gamma = resident.placed(&mut self.workspace, |w| w.weights(weights, ws))?;
let start = resident.checkpoint(ws)?;
let raw_rows = context.allocate(512)?;
let mut outputs: [Option<DeviceBuffer<'ctx>>; 5] = std::array::from_fn(|_| None);
let sizes = [2048, 2048, 24576, CAP * 4, 16];
let setup = (|| -> Result<()> {
for (i, n) in sizes.into_iter().enumerate() {
outputs[i] = Some(context.allocate(n)?)
}
for (i, values) in [(0, k), (1, v)] {
outputs[i].as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&encode(values)?)?;
}
self.workspace.upload(4, raw)?;
self.workspace.upload(7, qfull)?;
self.workspace.upload(8, index_q)?;
Ok(())
})();
if let Err(primary) = setup {
Ok(p)
}
/// The five output buffers with K and V uploaded, and the inputs uploaded into the index workspace.
fn stage_outputs(
&mut self,
context: &'ctx Context<'ctx>,
inputs: &ScalarInputs<'_>,
) -> 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) {
for b in outputs.into_iter().flatten() {
let _ = b.release();
}
@@ -137,73 +237,47 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> {
}
let handles =
std::array::from_fn(|i| outputs[i].as_ref().and_then(|b| b.handle).expect("allocated actual owner"));
Ok((outputs, handles))
}
fn fill_outputs(
&mut self,
context: &'ctx Context<'ctx>,
outputs: &mut Outputs<'ctx>,
inputs: &ScalarInputs<'_>,
) -> Result<()> {
for (i, n) in output_sizes().into_iter().enumerate() {
outputs[i] = Some(context.allocate(n)?)
}
for (i, values) in [(0, inputs.k), (1, inputs.v)] {
outputs[i].as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&encode(values)?)?;
}
self.workspace.upload(4, inputs.raw)?;
self.workspace.upload(7, inputs.qfull)?;
self.workspace.upload(8, inputs.index_q)?;
Ok(())
}
/// Run the append/score program in the resident image, then copy the raw rows. The outer error leaves the image in
/// flight (the retained buffer or the raw span is unusable); the inner one is to be rolled back by the caller.
fn run_scalar(
&mut self,
resident: &mut OriginalQsaResidentIndex<'ctx>,
ws: &mut NativeBatchWorkspace<'ctx>,
(p, gamma, handles): (usize, [ffi::BufferHandle; 4], [ffi::BufferHandle; 5]),
raw_rows: &DeviceBuffer<'ctx>,
) -> Result<Result<()>> {
resident.in_flight = true;
resident.unpublished = true;
let operation = resident.placed(&mut self.workspace, |workspace| {
for (i, h) in handles.iter().enumerate() {
h.validate_projection_extent(sizes[i], 4)?;
ws.reject_alias(*h, sizes[i])?;
for b in workspace.buffers.iter().flatten() {
if h.overlaps(sizes[i], b.handle.ok_or(Error::ContextPoisoned)?, b.len()) {
return Err(Error::OutputAliasesInput);
}
}
for (j, g) in gamma.iter().enumerate() {
if h.overlaps(sizes[i], *g, if j < 2 { 1024 } else { 512 }) {
return Err(Error::OutputAliasesInput);
}
}
for (j, old) in handles[..i].iter().enumerate() {
if h.overlaps(sizes[i], *old, sizes[j]) {
return Err(Error::OutputAliasesInput);
}
}
}
workspace.run_resident_arena(
p as u32,
1,
workspace.handle(4, 512)?,
workspace.handle(7, 49152)?,
workspace.handle(8, 2048)?,
gamma,
handles,
ws,
true,
)
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)
});
if let Err(primary) = operation {
let cleanup = resident.restore_private(ws, &start);
if cleanup.is_ok() {
resident.in_flight = false
}
if context.is_poisoned() {
std::mem::forget((outputs, raw_rows))
} else {
for b in outputs.into_iter().flatten() {
let _ = b.release();
}
}
return combine(Err(primary), cleanup);
return Ok(Err(primary));
}
let retained = raw_rows.handle.ok_or(Error::ContextPoisoned)?;
let raw_h = self.workspace.handle(4, 512)?;
if let Err(primary) = resident.copy_ranges(ws, &[(raw_h, retained, 512)]) {
let cleanup = resident.restore_private(ws, &start);
if cleanup.is_ok() {
resident.in_flight = false
}
if context.is_poisoned() {
std::mem::forget((outputs, raw_rows))
} else {
for b in outputs.into_iter().flatten() {
let _ = b.release();
}
}
return combine(Err(primary), cleanup);
}
resident.provisional_end(p + 1);
let batch = OriginalQsaIndexBatch { owner: resident, start, raw: Some(raw_rows), gamma: weights[3], rows: 1 };
Ok(OriginalQsaResidentScalarSelection { workspace: &mut self.workspace, outputs, batch: Some(batch) })
Ok(resident.copy_ranges(ws, &[(raw_h, retained, 512)]))
}
pub fn commit_prefix(
&mut self,