STRA-338 size2 cd7: qsa transfer, transport and selected-kv functions cut into helpers

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 22:07:03 +01:00
parent a007ffcc33
commit e482c9fd45
4 changed files with 405 additions and 355 deletions
@@ -26,6 +26,61 @@ pub(crate) struct Transfer {
handles: std::cell::Cell<Option<(usize, usize, usize)>>,
pending: std::cell::Cell<bool>,
}
/// The exit code of a driver call as a result.
fn driver_code(operation: &'static str, code: i32) -> Result<()> {
if code != 0 {
return Err(Error::Driver { operation, code });
}
Ok(())
}
/// Poison the context after a failed copy; the workspace is dead with it.
fn poison_failed(c: &Context<'_>, w: &mut NativeBatchWorkspace<'_>) {
w.mark_failed();
c.poison();
c.retain_driver()
}
/// Every range needs a nonzero size and addresses, and its source and destination must not overlap.
fn check_ranges(ranges: &[(u64, u64, usize)]) -> Result<()> {
for (src, dst, n) in ranges {
if *n == 0 || *src == 0 || *dst == 0 {
return Err(Error::InvalidSize);
}
let se = src.checked_add(*n as u64).ok_or(Error::InvalidSize)?;
let de = dst.checked_add(*n as u64).ok_or(Error::InvalidSize)?;
if *src < de && *dst < se {
return Err(Error::OutputAliasesInput);
}
}
Ok(())
}
/// The side-stream symbols of `library`, or `None` when it lacks any of them.
fn load_side(library: *mut c_void) -> Option<Side> {
let sym = |n: &std::ffi::CStr| -> *mut c_void { unsafe { libc::dlsym(library, n.as_ptr()) } };
let (a, b, c, d, e, f, g) = (
sym(c"cuStreamCreate"),
sym(c"cuEventCreate"),
sym(c"cuEventRecord"),
sym(c"cuStreamWaitEvent"),
sym(c"cuStreamSynchronize"),
sym(c"cuStreamDestroy_v2"),
sym(c"cuEventDestroy_v2"),
);
if [a, b, c, d, e, f, g].iter().any(|p| p.is_null()) {
return None;
}
// SAFETY: the exact libcuda signatures of the seven calls; used only when all of them resolved.
unsafe {
Some(Side {
stream_create: std::mem::transmute::<*mut c_void, StreamCreate>(a),
event_create: std::mem::transmute::<*mut c_void, EventCreate>(b),
event_record: std::mem::transmute::<*mut c_void, EventRecord>(c),
stream_wait: std::mem::transmute::<*mut c_void, StreamWait>(d),
stream_sync: std::mem::transmute::<*mut c_void, StreamSync>(e),
stream_destroy: std::mem::transmute::<*mut c_void, Destroy>(f),
event_destroy: std::mem::transmute::<*mut c_void, Destroy>(g),
})
}
}
impl Transfer {
pub(crate) fn new() -> Result<Self> {
// SAFETY: fixed libcuda ABI; no caller resolver or host pointer conversion. The handle is owned by `Transfer`
@@ -43,32 +98,7 @@ impl Transfer {
}
// SAFETY: `Copy` is the exact cuMemcpyAsync(dst, src, bytes, stream) signature.
let copy = unsafe { std::mem::transmute::<*mut c_void, Copy>(p) };
let sym = |n: &std::ffi::CStr| -> *mut c_void { unsafe { libc::dlsym(library, n.as_ptr()) } };
let (a, b, c, d, e, f, g) = (
sym(c"cuStreamCreate"),
sym(c"cuEventCreate"),
sym(c"cuEventRecord"),
sym(c"cuStreamWaitEvent"),
sym(c"cuStreamSynchronize"),
sym(c"cuStreamDestroy_v2"),
sym(c"cuEventDestroy_v2"),
);
// SAFETY: the exact libcuda signatures of the seven calls; used only when all of them resolved.
let side = if [a, b, c, d, e, f, g].iter().any(|p| p.is_null()) {
None
} else {
unsafe {
Some(Side {
stream_create: std::mem::transmute::<*mut c_void, StreamCreate>(a),
event_create: std::mem::transmute::<*mut c_void, EventCreate>(b),
event_record: std::mem::transmute::<*mut c_void, EventRecord>(c),
stream_wait: std::mem::transmute::<*mut c_void, StreamWait>(d),
stream_sync: std::mem::transmute::<*mut c_void, StreamSync>(e),
stream_destroy: std::mem::transmute::<*mut c_void, Destroy>(f),
event_destroy: std::mem::transmute::<*mut c_void, Destroy>(g),
})
}
};
let side = load_side(library);
Ok(Self { library, copy, side, handles: std::cell::Cell::new(None), pending: std::cell::Cell::new(false) })
}
/// Whether `begin` can run (the driver exports the stream / event calls).
@@ -95,77 +125,54 @@ impl Transfer {
if self.pending.get() {
self.cancel(c)?;
}
for (src, dst, n) in ranges {
if *n == 0 || *src == 0 || *dst == 0 {
return Err(Error::InvalidSize);
}
let se = src.checked_add(*n as u64).ok_or(Error::InvalidSize)?;
let de = dst.checked_add(*n as u64).ok_or(Error::InvalidSize)?;
if *src < de && *dst < se {
return Err(Error::OutputAliasesInput);
}
}
check_ranges(ranges)?;
let g = c.enter().map_err(|e| {
w.mark_failed();
c.poison();
c.retain_driver();
poison_failed(c, w);
e
})?;
let b = w.blas()?;
let op = (|| -> Result<()> {
let (stream, e1, e2) = match self.handles.get() {
Some(h) => h,
None => {
let (mut s, mut x, mut y) = (std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut());
// SAFETY: fresh out-pointers; CU_STREAM_NON_BLOCKING = 1, CU_EVENT_DISABLE_TIMING = 2; the handles are owned by this Transfer and destroyed in Drop.
let code = unsafe { (side.stream_create)(&mut s, 1) };
if code != 0 {
return Err(Error::Driver { operation: "cuStreamCreate", code });
}
let code = unsafe { (side.event_create)(&mut x, 2) };
if code != 0 {
return Err(Error::Driver { operation: "cuEventCreate", code });
}
let code = unsafe { (side.event_create)(&mut y, 2) };
if code != 0 {
return Err(Error::Driver { operation: "cuEventCreate", code });
}
let h = (s as usize, x as usize, y as usize);
self.handles.set(Some(h));
h
}
};
// SAFETY: live handles of this context; the compute stream is the workspace's retained stream.
let code = unsafe { (side.event_record)(e1 as *mut c_void, b.stream() as *mut c_void) };
if code != 0 {
return Err(Error::Driver { operation: "cuEventRecord", code });
}
let code = unsafe { (side.stream_wait)(stream as *mut c_void, e1 as *mut c_void, 0) };
if code != 0 {
return Err(Error::Driver { operation: "cuStreamWaitEvent", code });
}
for (src, dst, n) in ranges {
// SAFETY: as `copy`: checked extents of live owners; the owners stay leased until `wait_pending` / `cancel` / the chunk's final drain.
let code = unsafe { (self.copy)(*dst, *src, *n, stream as *mut c_void) };
if code != 0 {
return Err(Error::Driver { operation: "cuMemcpyAsync", code });
}
}
let code = unsafe { (side.event_record)(e2 as *mut c_void, stream as *mut c_void) };
if code != 0 {
return Err(Error::Driver { operation: "cuEventRecord", code });
}
self.pending.set(true);
Ok(())
})();
let op = self.enqueue_side(side, b.stream() as *mut c_void, ranges);
let pop = g.finish();
if op.is_err() || pop.is_err() {
w.mark_failed();
c.poison();
c.retain_driver()
poison_failed(c, w)
}
combine(op, pop)
}
/// The side stream and its two events, created on first use (owned by this Transfer, destroyed in Drop).
fn side_handles(&self, side: &Side) -> Result<(usize, usize, usize)> {
if let Some(h) = self.handles.get() {
return Ok(h);
}
let (mut s, mut x, mut y) = (std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut());
// SAFETY: fresh out-pointers; CU_STREAM_NON_BLOCKING = 1, CU_EVENT_DISABLE_TIMING = 2; the handles are owned by this Transfer and destroyed in Drop.
driver_code("cuStreamCreate", unsafe { (side.stream_create)(&mut s, 1) })?;
driver_code("cuEventCreate", unsafe { (side.event_create)(&mut x, 2) })?;
driver_code("cuEventCreate", unsafe { (side.event_create)(&mut y, 2) })?;
let h = (s as usize, x as usize, y as usize);
self.handles.set(Some(h));
Ok(h)
}
/// Queue the side copy behind the compute stream's work so far and mark it pending.
fn enqueue_side(&self, side: &Side, compute: *mut c_void, ranges: &[(u64, u64, usize)]) -> Result<()> {
let (stream, e1, e2) = self.side_handles(side)?;
// SAFETY: live handles of this context; the compute stream is the workspace's retained stream.
driver_code("cuEventRecord", unsafe { (side.event_record)(e1 as *mut c_void, compute) })?;
driver_code("cuStreamWaitEvent", unsafe { (side.stream_wait)(stream as *mut c_void, e1 as *mut c_void, 0) })?;
// SAFETY: as `copy`: checked extents of live owners; the owners stay leased until `wait_pending` / `cancel` / the chunk's final drain.
self.enqueue_copies(ranges, stream as *mut c_void)?;
driver_code("cuEventRecord", unsafe { (side.event_record)(e2 as *mut c_void, stream as *mut c_void) })?;
self.pending.set(true);
Ok(())
}
/// Enqueue every copy of `ranges` on `stream`.
fn enqueue_copies(&self, ranges: &[(u64, u64, usize)], stream: *mut c_void) -> Result<()> {
for (src, dst, n) in ranges {
// SAFETY: actual checked owner extents, real Context and a live stream;
// source/destination leases live through the caller's drain or wait.
driver_code("cuMemcpyAsync", unsafe { (self.copy)(*dst, *src, *n, stream) })?;
}
Ok(())
}
/// Order the compute stream after the side copy (no host wait). A no-op when nothing is pending.
pub(crate) fn wait_pending<'ctx>(&self, c: &'ctx Context<'ctx>, w: &mut NativeBatchWorkspace<'ctx>) -> Result<()> {
if !self.pending.get() {
@@ -232,41 +239,17 @@ impl Transfer {
}
// Private callers derive each address and checked byte extent from actual
// initialized mapped/device owners; reject overflow and overlap prewrite.
for (src, dst, n) in ranges {
if *n == 0 || *src == 0 || *dst == 0 {
return Err(Error::InvalidSize);
}
let se = src.checked_add(*n as u64).ok_or(Error::InvalidSize)?;
let de = dst.checked_add(*n as u64).ok_or(Error::InvalidSize)?;
if *src < de && *dst < se {
return Err(Error::OutputAliasesInput);
}
}
check_ranges(ranges)?;
let g = c.enter().map_err(|e| {
w.mark_failed();
c.poison();
c.retain_driver();
poison_failed(c, w);
e
})?;
let b = w.blas()?;
let op = (|| -> Result<()> {
c.driver.api.synchronize()?;
for (src, dst, n) in ranges {
// SAFETY: actual checked owner extents, real Context and retained stream;
// source/destination leases live through the final synchronize below.
let code = unsafe { (self.copy)(*dst, *src, *n, b.stream() as *mut c_void) };
if code != 0 {
return Err(Error::Driver { operation: "cuMemcpyAsync", code });
}
}
Ok(())
})();
let op = c.driver.api.synchronize().and_then(|()| self.enqueue_copies(ranges, b.stream() as *mut c_void));
let sync = b.synchronize();
let pop = g.finish();
if op.is_err() || sync.is_err() || pop.is_err() {
w.mark_failed();
c.poison();
c.retain_driver()
poison_failed(c, w)
}
combine(combine(op, sync), pop)
}
@@ -282,39 +265,18 @@ impl Transfer {
if c.is_poisoned() {
return Err(Error::ContextPoisoned);
}
for (src, dst, n) in ranges {
if *n == 0 || *src == 0 || *dst == 0 {
return Err(Error::InvalidSize);
}
let se = src.checked_add(*n as u64).ok_or(Error::InvalidSize)?;
let de = dst.checked_add(*n as u64).ok_or(Error::InvalidSize)?;
if *src < de && *dst < se {
return Err(Error::OutputAliasesInput);
}
}
check_ranges(ranges)?;
let g = c.enter().map_err(|e| {
w.mark_failed();
c.poison();
c.retain_driver();
poison_failed(c, w);
e
})?;
let b = w.blas()?;
let op = (|| -> Result<()> {
for (src, dst, n) in ranges {
// SAFETY: as `copy`; the caller's fence replaces the context synchronize.
let code = unsafe { (self.copy)(*dst, *src, *n, b.stream() as *mut c_void) };
if code != 0 {
return Err(Error::Driver { operation: "cuMemcpyAsync", code });
}
}
Ok(())
})();
// The caller's fence replaces the context synchronize.
let op = self.enqueue_copies(ranges, b.stream() as *mut c_void);
let sync = b.synchronize();
let pop = g.finish();
if op.is_err() || sync.is_err() || pop.is_err() {
w.mark_failed();
c.poison();
c.retain_driver()
poison_failed(c, w)
}
combine(combine(op, sync), pop)
}
+106 -95
View File
@@ -23,38 +23,43 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
admit(context, Self::device_bytes())?;
let mut s =
Self { context, table: None, status: None, module: None, transfer: None, failed: false, prefix: None };
let r = (|| -> Result<()> {
s.transfer = Some(crate::qsa_prompt_index::resident_transfer::Transfer::new()?);
let g = context.enter().map_err(|e| {
context.poison();
context.retain_driver();
e
})?;
let load = Module::load(
include_bytes!("qsa_prompt_kv.ptx"),
&[c"leleka_qsa_kv_guard", c"leleka_qsa_kv_append", c"leleka_qsa_kv_scale_guard"],
);
let pop = g.finish();
if pop.is_err() {
context.poison();
context.retain_driver()
}
s.module = Some(load?);
pop?;
let mut table = context.allocate(crate::serving_context::geometry().page_table_bytes())?;
table.copy_from(&bytes_i32((0..crate::serving_context::geometry().pages()).map(|p| p as i32))?)?;
s.table = Some(table);
s.status = Some(context.allocate(4)?);
if context.memory_info()?.0 < RESERVE {
return Err(Error::BudgetExceeded);
}
Ok(())
})();
if let Err(e) = r {
if let Err(e) = s.init() {
return combine(Err(e), s.close());
}
Ok(s)
}
fn init(&mut self) -> Result<()> {
let context = self.context;
self.transfer = Some(crate::qsa_prompt_index::resident_transfer::Transfer::new()?);
let g = context.enter().map_err(|e| {
context.poison();
context.retain_driver();
e
})?;
let load = Module::load(
include_bytes!("qsa_prompt_kv.ptx"),
&[c"leleka_qsa_kv_guard", c"leleka_qsa_kv_append", c"leleka_qsa_kv_scale_guard"],
);
let pop = g.finish();
if pop.is_err() {
context.poison();
context.retain_driver()
}
self.module = Some(load?);
pop?;
self.init_table()?;
if context.memory_info()?.0 < RESERVE {
return Err(Error::BudgetExceeded);
}
Ok(())
}
fn init_table(&mut self) -> Result<()> {
let mut table = self.context.allocate(crate::serving_context::geometry().page_table_bytes())?;
table.copy_from(&bytes_i32((0..crate::serving_context::geometry().pages()).map(|p| p as i32))?)?;
self.table = Some(table);
self.status = Some(self.context.allocate(4)?);
Ok(())
}
pub fn allocated_bytes(&self) -> usize {
self.table.as_ref().map_or(0, DeviceBuffer::len) + self.status.as_ref().map_or(0, DeviceBuffer::len)
}
@@ -110,35 +115,34 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
w.validate_context(self.context)?;
let c = self.context;
let g = c.enter().map_err(|e| {
self.failed = true;
w.mark_failed();
c.poison();
c.retain_driver();
self.fail_run(w);
e
})?;
let op = c.driver.api.synchronize().and_then(|()| {
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(
index,
grid,
block,
0,
w.blas()?.stream(),
&mut a,
)
});
let op = c.driver.api.synchronize().and_then(|()| self.launch_run(w, (index, grid, block), &mut a));
let sync = w.blas()?.synchronize();
let pop = g.finish();
if op.is_err() || sync.is_err() || pop.is_err() {
self.failed = true;
w.mark_failed();
c.poison();
c.retain_driver()
self.fail_run(w)
}
if sync.is_err() || pop.is_err() {
std::mem::forget(a)
}
combine(combine(op, sync), pop)
}
fn launch_run(
&self,
w: &mut NativeBatchWorkspace<'ctx>,
(index, grid, block): (usize, [u32; 3], u32),
a: &mut Arguments,
) -> Result<()> {
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(index, grid, block, 0, w.blas()?.stream(), a)
}
fn fail_run(&mut self, w: &mut NativeBatchWorkspace<'ctx>) {
self.failed = true;
w.mark_failed();
self.context.poison();
self.context.retain_driver()
}
fn prefix_ranges(
&self,
@@ -183,11 +187,7 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
if pages > crate::serving_context::geometry().pages() {
return Err(Error::InvalidQwenShape);
}
if let Some(t) = self.transfer.as_ref() {
if t.is_pending() {
t.cancel(self.context)?;
}
}
self.cancel_pending()?;
self.prefix = None;
if pages == 0 || !Self::prefetch_enabled() || !self.transfer.as_ref().is_some_and(|t| t.can_overlap()) {
return Ok(());
@@ -197,14 +197,17 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
if result.is_err() {
self.failed = true
} else {
self.prefix = Some((
host,
[stage[0].qwen_address(), stage[1].qwen_address(), stage[2].qwen_address(), stage[3].qwen_address()],
pages,
))
self.prefix = Some((host, stage_addresses(&stage), pages))
}
result
}
/// Host wait for a side copy that is still pending.
fn cancel_pending(&self) -> Result<()> {
match self.transfer.as_ref() {
Some(t) if t.is_pending() => t.cancel(self.context),
_ => Ok(()),
}
}
/// Abandon a started prefetch (host wait): nothing may reuse or free the stage under the copy.
pub fn cancel_prefix(&mut self) -> Result<()> {
self.prefix = None;
@@ -229,27 +232,20 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
}
let ranges = self.prefix_ranges(w, host, stage, pages)?;
// a prefix started at the layer's beginning for exactly these ranges: order the compute stream after it
if let Some((h, s, p)) = self.prefix.take() {
if h == host
&& p == pages
&& s == [
stage[0].qwen_address(),
stage[1].qwen_address(),
stage[2].qwen_address(),
stage[3].qwen_address(),
]
{
if let Some(started) = self.prefix.take() {
if started == (host, stage_addresses(&stage), pages) {
let result = self.transfer.as_ref().ok_or(Error::ContextPoisoned)?.wait_pending(self.context, w);
if result.is_err() {
self.failed = true
}
return result;
return self.flag(result);
}
if let Some(t) = self.transfer.as_ref() {
t.cancel(self.context)?;
}
}
let result = self.transfer.as_ref().ok_or(Error::ContextPoisoned)?.copy(self.context, w, &ranges);
self.flag(result)
}
/// A failed transfer fails the transport.
fn flag(&mut self, result: Result<()>) -> Result<()> {
if result.is_err() {
self.failed = true
}
@@ -260,7 +256,19 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
}
fn close_inner(&mut self) -> Result<()> {
self.failed = true;
let mut r = Ok(());
let r = self.close_transfer(Ok(()));
let mut r = self.close_module(r);
for b in [self.status.take(), self.table.take()].into_iter().flatten() {
if self.context.is_poisoned() {
std::mem::forget(b);
r = combine(r, Err(Error::ContextPoisoned))
} else {
r = combine(r, b.release())
}
}
r
}
fn close_transfer(&mut self, mut r: Result<()>) -> Result<()> {
if let Some(t) = self.transfer.take() {
if !self.context.is_poisoned() {
let _ = t.cancel(self.context);
@@ -272,39 +280,42 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
drop(t)
}
}
r
}
fn close_module(&mut self, mut r: Result<()>) -> Result<()> {
if let Some(m) = self.module.take() {
if self.context.is_poisoned() {
std::mem::forget(m);
r = Err(Error::ContextPoisoned)
} else {
match self.context.enter() {
Ok(g) => {
let x = combine(m.close(), g.finish());
if x.is_err() {
self.context.poison();
self.context.retain_driver()
}
r = combine(r, x)
}
Err(e) => {
self.context.poison();
self.context.retain_driver();
std::mem::forget(m);
r = combine(r, Err(e))
}
}
}
}
for b in [self.status.take(), self.table.take()].into_iter().flatten() {
if self.context.is_poisoned() {
std::mem::forget(b);
r = combine(r, Err(Error::ContextPoisoned))
} else {
r = combine(r, b.release())
r = combine(r, self.close_entered(m))
}
}
r
}
/// Close the module inside the context; a context that cannot be entered is poisoned and the module leaked.
fn close_entered(&self, m: Module) -> Result<()> {
match self.context.enter() {
Ok(g) => {
let x = combine(m.close(), g.finish());
if x.is_err() {
self.context.poison();
self.context.retain_driver()
}
x
}
Err(e) => {
self.context.poison();
self.context.retain_driver();
std::mem::forget(m);
Err(e)
}
}
}
}
/// The device addresses of the four stage spans.
fn stage_addresses(stage: &[crate::ffi::BufferHandle; 4]) -> [u64; 4] {
[stage[0].qwen_address(), stage[1].qwen_address(), stage[2].qwen_address(), stage[3].qwen_address()]
}
/// Per-arm override of `LELEKA_PREFILL_QSA_PREFETCH` (-1: none, 0: off, 1: on).
static PREFETCH_OVERRIDE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
@@ -23,7 +23,27 @@ impl QsaSelectedKvProducts<'_, '_> {
return Err(Error::InvalidQwenShape);
}
let function = w.functions.ok_or(Error::ContextPoisoned)?[2];
if !std::ptr::eq(w.context, query.context) || !std::ptr::eq(w.context, output.context) {
let (q, o) = w.attend_io(&h, query, output)?;
let bytes = self.width as usize * CELL;
let k = h[2].checked_subspan(PACKED, 0, bytes)?;
let v = h[3].checked_subspan(PACKED, 0, bytes)?;
let layout = qwen_ffi::qsa_layout(Operation::QsaAttend, self.width)?;
let mut handles = [q; 9];
handles[..4].copy_from_slice(&[q, k, v, o]);
let args = qwen_ffi::Arguments::with_layout(Operation::QsaAttend, layout, handles, 0.0);
w.launch_attend(function, args)
}
}
impl QsaSelectedKvWorkspace<'_> {
/// The query and output spans of an attend, once both belong to this context, have the exact size and overlap
/// neither each other nor any buffer of the workspace.
fn attend_io(
&self,
h: &[ffi::BufferHandle; 8],
query: &DeviceBuffer<'_>,
output: &DeviceBuffer<'_>,
) -> Result<(ffi::BufferHandle, ffi::BufferHandle)> {
if !std::ptr::eq(self.context, query.context) || !std::ptr::eq(self.context, output.context) {
return Err(Error::ContextMismatch);
}
if query.bytes != 24576 || output.bytes != 24576 {
@@ -41,28 +61,24 @@ impl QsaSelectedKvProducts<'_, '_> {
return Err(Error::OutputAliasesInput);
}
}
let bytes = self.width as usize * CELL;
let k = h[2].checked_subspan(PACKED, 0, bytes)?;
let v = h[3].checked_subspan(PACKED, 0, bytes)?;
let layout = qwen_ffi::qsa_layout(Operation::QsaAttend, self.width)?;
let mut handles = [q; 9];
handles[..4].copy_from_slice(&[q, k, v, o]);
let mut args = qwen_ffi::Arguments::with_layout(Operation::QsaAttend, layout, handles, 0.0);
let guard = match w.context.enter() {
Ok((q, o))
}
fn launch_attend(&self, function: ffi::FunctionHandle, mut args: qwen_ffi::Arguments) -> Result<()> {
let guard = match self.context.enter() {
Ok(guard) => guard,
Err(error) => {
w.failed.set(true);
self.failed.set(true);
return Err(error);
}
};
let launch = w.context.driver.api.launch_qwen(function, Operation::QsaAttend, &mut args);
let sync = w.context.driver.api.synchronize();
let launch = self.context.driver.api.launch_qwen(function, Operation::QsaAttend, &mut args);
let sync = self.context.driver.api.synchronize();
let pop = guard.finish();
if launch.is_err() || sync.is_err() || pop.is_err() {
w.failed.set(true);
self.failed.set(true);
}
if sync.is_err() || pop.is_err() {
w.context.poisoned.set(true);
self.context.poisoned.set(true);
std::mem::forget(args);
}
combine(combine(launch, sync), pop)
@@ -3,20 +3,77 @@
#[allow(unused_imports)]
use super::*;
/// The staged host bytes, arguments and device targets of one `prepare` launch window.
struct SelectedLaunch {
stages: [Vec<u8>; 4],
scatter: ffi::QsaSelectedArguments,
gather: ffi::QsaSelectedArguments,
misses: Option<[ffi::BufferHandle; 3]>,
selection: ffi::BufferHandle,
miss_count: u32,
selected_count: u32,
}
/// The shape of one layer's miss and selection lists.
fn check_shapes(
layer: u32,
(miss_slots, miss_k, miss_v): (&[u32], &[u8], &[u8]),
selected_slots: &[u32],
) -> Result<()> {
if layer as usize >= LAYERS
|| !(1..=CELLS).contains(&selected_slots.len())
|| miss_slots.len() > CELLS
|| miss_k.len() != miss_slots.len() * CELL
|| miss_v.len() != miss_k.len()
{
return Err(Error::InvalidQwenShape);
}
Ok(())
}
/// The missed rows must be finite FP16.
fn check_finite(miss_k: &[u8], miss_v: &[u8]) -> Result<()> {
if miss_k
.as_chunks::<2>()
.0
.iter()
.chain(miss_v.as_chunks::<2>().0.iter())
.any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00)
{
return Err(Error::InvalidQwenShape);
}
Ok(())
}
/// A buffer is released; a poisoned context leaks it, and a failed release poisons the context.
fn release_buffer(context: &Context<'_>, buffer: DeviceBuffer<'_>) -> Result<()> {
let release = if context.is_poisoned() {
std::mem::forget(buffer);
Err(Error::ContextPoisoned)
} else {
buffer.release()
};
if release.is_err() {
context.poisoned.set(true);
}
release
}
/// A module is unloaded inside the context; a failure poisons the context and holds the driver for good.
fn unload_module(context: &Context<'_>, module: ffi::ModuleHandle) -> Result<()> {
let release = if context.is_poisoned() {
Err(Error::ContextPoisoned)
} else {
match context.enter() {
Ok(guard) => combine(context.driver.api.unload(module), guard.finish()),
Err(e) => Err(e),
}
};
if release.is_err() {
context.poisoned.set(true);
std::mem::forget(Rc::clone(&context.driver.api));
}
release
}
impl<'ctx> QsaSelectedKvWorkspace<'ctx> {
pub(super) fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
if context.is_poisoned() || context.handle.is_none() {
return Err(Error::ContextPoisoned);
}
asset()?; // Pending asset refuses before allocation or module mutation.
let attention = qwen_ffi::asset(Operation::QsaAttend).ok_or(Error::UnsupportedQwenOperation)?;
attention.validate(Operation::QsaAttend)?;
let required = TOTAL.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?;
if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget)
|| context.memory_info()?.0 < required
{
return Err(Error::BudgetExceeded);
}
let attention = Self::admit_new(context)?;
let mut initialized = Vec::new();
initialized.try_reserve_exact(LAYERS * CELLS).map_err(|_| Error::HostAllocation)?;
initialized.resize(LAYERS * CELLS, false);
@@ -29,30 +86,50 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> {
generation: 0,
failed: Cell::new(false),
};
let operation = (|| {
for (i, bytes) in SIZES.into_iter().enumerate() {
owner.buffers[i] = Some(context.allocate(bytes)?);
}
let guard = context.enter()?;
let load = (|| {
let transport = context.driver.api.load_qsa_selected()?;
owner.modules[0] = Some(transport);
let scatter = context.driver.api.qsa_selected_function(transport, false)?;
let gather = context.driver.api.qsa_selected_function(transport, true)?;
let original = context.driver.api.load_qwen_module(attention)?;
owner.modules[1] = Some(original);
let attend = context.driver.api.qwen_function(original, Operation::QsaAttend)?;
owner.functions = Some([scatter, gather, attend]);
Ok(())
})();
combine(load, guard.finish())
})();
if let Err(error) = operation {
if let Err(error) = owner.load(attention) {
return combine(Err(error), owner.close());
}
owner.handles()?;
Ok(owner)
}
/// The sealed attention asset, once the context and the device budget admit a workspace.
fn admit_new(context: &Context<'_>) -> Result<&'static qwen_ffi::Asset> {
if context.is_poisoned() || context.handle.is_none() {
return Err(Error::ContextPoisoned);
}
asset()?; // Pending asset refuses before allocation or module mutation.
let attention = qwen_ffi::asset(Operation::QsaAttend).ok_or(Error::UnsupportedQwenOperation)?;
attention.validate(Operation::QsaAttend)?;
let required = TOTAL.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?;
if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget)
|| context.memory_info()?.0 < required
{
return Err(Error::BudgetExceeded);
}
Ok(attention)
}
fn load(&mut self, attention: &qwen_ffi::Asset) -> Result<()> {
let context = self.context;
for (i, bytes) in SIZES.into_iter().enumerate() {
self.buffers[i] = Some(context.allocate(bytes)?);
}
let guard = context.enter()?;
let load = self.load_modules(attention);
combine(load, guard.finish())
}
fn load_modules(&mut self, attention: &qwen_ffi::Asset) -> Result<()> {
let context = self.context;
let api = &context.driver.api;
let transport = api.load_qsa_selected()?;
self.modules[0] = Some(transport);
let scatter = api.qsa_selected_function(transport, false)?;
let gather = api.qsa_selected_function(transport, true)?;
let original = api.load_qwen_module(attention)?;
self.modules[1] = Some(original);
let attend = api.qwen_function(original, Operation::QsaAttend)?;
self.functions = Some([scatter, gather, attend]);
Ok(())
}
pub fn allocated_bytes(&self) -> usize {
self.buffers.iter().flatten().map(|b| b.bytes).sum()
@@ -97,15 +174,23 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> {
) -> Result<QsaSelectedKvProducts<'lease, 'ctx>> {
let h = self.handles()?;
let functions = self.functions.ok_or(Error::ContextPoisoned)?;
if layer as usize >= LAYERS
|| !(1..=CELLS).contains(&selected_slots.len())
|| miss_slots.len() > CELLS
|| miss_k.len() != miss_slots.len() * CELL
|| miss_v.len() != miss_k.len()
{
return Err(Error::InvalidQwenShape);
}
check_shapes(layer, (miss_slots, miss_k, miss_v), selected_slots)?;
let generation = self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?;
self.check_slots(layer, miss_slots, selected_slots)?;
check_finite(miss_k, miss_v)?;
if self.context.allocated_bytes() > self.context.budget {
return Err(Error::BudgetExceeded);
}
let launch = Self::selected_launch(&h, layer, (miss_slots, miss_k, miss_v), selected_slots)?;
self.run_selected(functions, launch)?;
for &slot in miss_slots {
self.initialized[layer as usize * CELLS + slot as usize] = true;
}
self.generation = generation;
Ok(QsaSelectedKvProducts { workspace: self, width: selected_slots.len() as u32, generation })
}
/// Miss slots are unique and in range, selected slots are unique, in range and either missed now or already resident.
fn check_slots(&self, layer: u32, miss_slots: &[u32], selected_slots: &[u32]) -> Result<()> {
let mut missing = [false; CELLS];
for &slot in miss_slots {
if slot as usize >= CELLS || missing[slot as usize] {
@@ -123,24 +208,19 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> {
}
selected[slot as usize] = true;
}
if miss_k
.as_chunks::<2>()
.0
.iter()
.chain(miss_v.as_chunks::<2>().0.iter())
.any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00)
{
return Err(Error::InvalidQwenShape);
}
if self.context.allocated_bytes() > self.context.budget {
return Err(Error::BudgetExceeded);
}
// All fallible staging allocation and closed ranges precede the first copy.
Ok(())
}
/// All fallible staging allocation and closed ranges precede the first copy.
fn selected_launch(
h: &[ffi::BufferHandle; 8],
layer: u32,
(miss_slots, miss_k, miss_v): (&[u32], &[u8], &[u8]),
selected_slots: &[u32],
) -> Result<SelectedLaunch> {
let stages = [owned_bytes(miss_k)?, owned_bytes(miss_v)?, slot_bytes(miss_slots)?, slot_bytes(selected_slots)?];
let mut scatter =
ffi::QsaSelectedArguments::new([h[0], h[1], h[4], h[5], h[6]], layer, miss_slots.len() as u32);
let mut gather =
ffi::QsaSelectedArguments::new([h[0], h[1], h[2], h[3], h[7]], layer, selected_slots.len() as u32);
let (miss_count, selected_count) = (miss_slots.len() as u32, selected_slots.len() as u32);
let scatter = ffi::QsaSelectedArguments::new([h[0], h[1], h[4], h[5], h[6]], layer, miss_count);
let gather = ffi::QsaSelectedArguments::new([h[0], h[1], h[2], h[3], h[7]], layer, selected_count);
let misses = if miss_slots.is_empty() {
None
} else {
@@ -151,6 +231,10 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> {
])
};
let selection = h[7].checked_subspan(MAP, 0, stages[3].len())?;
Ok(SelectedLaunch { stages, scatter, gather, misses, selection, miss_count, selected_count })
}
/// Copy the staged rows in, scatter the misses and gather the selection inside the context, then drain.
fn run_selected(&self, functions: [ffi::FunctionHandle; 3], mut launch: SelectedLaunch) -> Result<()> {
let guard = match self.context.enter() {
Ok(guard) => guard,
Err(error) => {
@@ -158,25 +242,7 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> {
return Err(error);
}
};
let mut operation = Ok(());
if let Some(targets) = misses {
for i in 0..3 {
if operation.is_ok() {
operation = self.context.driver.api.copy_from(targets[i], &stages[i]);
}
}
if operation.is_ok() {
operation =
self.context.driver.api.launch_qsa_selected(functions[0], miss_slots.len() as u32, &mut scatter);
}
}
if operation.is_ok() {
operation = self.context.driver.api.copy_from(selection, &stages[3]);
}
if operation.is_ok() {
operation =
self.context.driver.api.launch_qsa_selected(functions[1], selected_slots.len() as u32, &mut gather);
}
let operation = self.enqueue_selected(functions, &mut launch);
let sync = self.context.driver.api.synchronize();
let pop = guard.finish();
if operation.is_err() || sync.is_err() || pop.is_err() {
@@ -184,14 +250,30 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> {
}
if sync.is_err() || pop.is_err() {
self.context.poisoned.set(true);
std::mem::forget((stages, scatter, gather));
std::mem::forget(launch);
}
combine(combine(operation, sync), pop)?;
for &slot in miss_slots {
self.initialized[layer as usize * CELLS + slot as usize] = true;
combine(combine(operation, sync), pop)
}
fn enqueue_selected(&self, functions: [ffi::FunctionHandle; 3], launch: &mut SelectedLaunch) -> Result<()> {
let api = &self.context.driver.api;
let mut operation = Ok(());
if let Some(targets) = launch.misses {
for i in 0..3 {
if operation.is_ok() {
operation = api.copy_from(targets[i], &launch.stages[i]);
}
}
if operation.is_ok() {
operation = api.launch_qsa_selected(functions[0], launch.miss_count, &mut launch.scatter);
}
}
self.generation = generation;
Ok(QsaSelectedKvProducts { workspace: self, width: selected_slots.len() as u32, generation })
if operation.is_ok() {
operation = api.copy_from(launch.selection, &launch.stages[3]);
}
if operation.is_ok() {
operation = api.launch_qsa_selected(functions[1], launch.selected_count, &mut launch.gather);
}
operation
}
pub fn close(mut self) -> Result<()> {
@@ -203,33 +285,12 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> {
let mut result = Ok(());
for slot in &mut self.buffers {
if let Some(buffer) = slot.take() {
let release = if self.context.is_poisoned() {
std::mem::forget(buffer);
Err(Error::ContextPoisoned)
} else {
buffer.release()
};
if release.is_err() {
self.context.poisoned.set(true);
}
result = combine(result, release);
result = combine(result, release_buffer(self.context, buffer));
}
}
for slot in &mut self.modules {
if let Some(module) = slot.take() {
let release = if self.context.is_poisoned() {
Err(Error::ContextPoisoned)
} else {
match self.context.enter() {
Ok(guard) => combine(self.context.driver.api.unload(module), guard.finish()),
Err(e) => Err(e),
}
};
if release.is_err() {
self.context.poisoned.set(true);
std::mem::forget(Rc::clone(&self.context.driver.api));
}
result = combine(result, release);
result = combine(result, unload_module(self.context, module));
}
}
result