STRA-338 size: cuda-driver ple_closed_queue, ple_batch_queue, native_prompt_device, original_file_expert_source: remaining long functions end within the limits
This commit is contained in:
+23
@@ -3,6 +3,18 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
pub(super) const GR_READ_ORDER: [usize; 7] = [0, 1, 2, 3, 6, 4, 5];
|
||||
pub(super) const GR_READ_NAMES: [&str; 8] = [
|
||||
"GR native norm",
|
||||
"GR native down",
|
||||
"GR native silu",
|
||||
"GR native up",
|
||||
"GR native products",
|
||||
"GR native mixed",
|
||||
"GR native inject",
|
||||
"GR native candidate",
|
||||
];
|
||||
|
||||
/// Spans, weights and scalars every command of one GR read shares.
|
||||
pub(super) struct GrReadPlan {
|
||||
h: [BufferHandle; 15],
|
||||
@@ -23,6 +35,17 @@ impl GrReadPlan {
|
||||
Self { h, w, flags, t, low_half }
|
||||
}
|
||||
|
||||
/// All commands of one GR read: norm, projections, mix.
|
||||
pub(super) fn commands(&self, epsilon: f32, normed: bool) -> Result<Vec<C>> {
|
||||
let mut v = Vec::new();
|
||||
v.try_reserve_exact(20).map_err(|_| Error::HostAllocation)?;
|
||||
let fused = fused_scans();
|
||||
self.push_norm(&mut v, epsilon, normed, fused);
|
||||
self.push_projections(&mut v, fused);
|
||||
self.push_mix(&mut v, fused);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn low(&self, i: usize) -> A {
|
||||
if self.low_half { A::Address(self.h[i]) } else { A::NullAddress }
|
||||
}
|
||||
|
||||
+14
-27
@@ -1,7 +1,7 @@
|
||||
//! Moved out of the parent module by STRA-338: impl OriginalPromptDevice (5).
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::gr_read_phases::GrReadPlan;
|
||||
use super::gr_read_phases::{GR_READ_NAMES, GR_READ_ORDER, GrReadPlan};
|
||||
use super::*;
|
||||
|
||||
impl<'ctx> OriginalPromptDevice<'ctx> {
|
||||
@@ -20,38 +20,25 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let t = lease.rows();
|
||||
let plan = self.gr_read_plan(lease, workspace, weights)?;
|
||||
let v = plan.commands(epsilon, normed)?;
|
||||
self.run(lease, workspace, v, t, 8, &GR_READ_ORDER, &GR_READ_NAMES)?;
|
||||
Ok(OriginalDeviceGrRead { lease: residual.lease })
|
||||
}
|
||||
/// The spans and weights of a GR read of the lease's rows.
|
||||
fn gr_read_plan(
|
||||
&self,
|
||||
lease: &OriginalPromptRows<'_, '_, 'ctx>,
|
||||
workspace: &NativeBatchWorkspace<'ctx>,
|
||||
weights: [&DeviceBuffer<'_>; 4],
|
||||
) -> Result<GrReadPlan> {
|
||||
let h = self.gr_read_spans(lease)?;
|
||||
let mut w = [h[0]; 4];
|
||||
for (i, n) in [40960, 6553600, 6553600, 81920].into_iter().enumerate() {
|
||||
w[i] = self.weight(lease, workspace, weights[i], n, if i == 0 { 4 } else { 2 })?;
|
||||
}
|
||||
let low_half = self.profile == GrNativeProfile::HighAndLow;
|
||||
let plan = GrReadPlan::new(h, w, self.status()?, t, low_half);
|
||||
let mut v = Vec::new();
|
||||
v.try_reserve_exact(20).map_err(|_| Error::HostAllocation)?;
|
||||
let fused = fused_scans();
|
||||
plan.push_norm(&mut v, epsilon, normed, fused);
|
||||
plan.push_projections(&mut v, fused);
|
||||
plan.push_mix(&mut v, fused);
|
||||
self.run(
|
||||
lease,
|
||||
workspace,
|
||||
v,
|
||||
t,
|
||||
8,
|
||||
&[0, 1, 2, 3, 6, 4, 5],
|
||||
&[
|
||||
"GR native norm",
|
||||
"GR native down",
|
||||
"GR native silu",
|
||||
"GR native up",
|
||||
"GR native products",
|
||||
"GR native mixed",
|
||||
"GR native inject",
|
||||
"GR native candidate",
|
||||
],
|
||||
)?;
|
||||
Ok(OriginalDeviceGrRead { lease: residual.lease })
|
||||
Ok(GrReadPlan::new(h, w, self.status()?, lease.rows(), low_half))
|
||||
}
|
||||
/// The device spans a GR read touches; the low-half ones only when the profile keeps a low half.
|
||||
fn gr_read_spans(&self, lease: &OriginalPromptRows<'_, '_, 'ctx>) -> Result<[BufferHandle; 15]> {
|
||||
|
||||
+51
-11
@@ -2,6 +2,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::CurrentGuard;
|
||||
|
||||
type Primary = Vec<(i32, i32, usize)>;
|
||||
|
||||
@@ -22,6 +23,32 @@ pub(super) fn poison_parts(failed: &mut bool, context: &Context<'_>) {
|
||||
context.retain_driver();
|
||||
}
|
||||
|
||||
/// The arena allocation failed: leave the context, and poison it on a driver error or a failed pop.
|
||||
pub(super) fn alloc_failed(
|
||||
failed: &mut bool,
|
||||
context: &Context<'_>,
|
||||
guard: CurrentGuard<'_, '_>,
|
||||
primary: Error,
|
||||
) -> Result<()> {
|
||||
let pop = guard.finish();
|
||||
if matches!(primary, Error::Driver { .. }) || pop.is_err() {
|
||||
poison_parts(failed, context);
|
||||
}
|
||||
combine(Err(primary), pop)
|
||||
}
|
||||
|
||||
/// The context pop failed, so the arena may still be in use by the device: poison and leak it.
|
||||
pub(super) fn leak_arena(
|
||||
failed: &mut bool,
|
||||
context: &Context<'_>,
|
||||
arena: abi::Arena,
|
||||
result: Result<()>,
|
||||
) -> Result<()> {
|
||||
poison_parts(failed, context);
|
||||
std::mem::forget(arena);
|
||||
result
|
||||
}
|
||||
|
||||
/// Closes a half-built arena after its fill failed, returning the fill error combined with the cleanup result.
|
||||
pub(super) fn discard_arena(
|
||||
failed: &mut bool,
|
||||
@@ -273,17 +300,10 @@ impl<'ctx> OriginalFileExpertSource<'ctx> {
|
||||
headroom: usize,
|
||||
) -> Result<usize> {
|
||||
let stack = abi::worker_stack_bytes()?;
|
||||
let prospective_meta = self
|
||||
.metadata_bytes()?
|
||||
.checked_add(
|
||||
layout.offsets.capacity() * size_of::<usize>()
|
||||
+ 2 * primary.capacity() * size_of::<(i32, i32, usize)>()
|
||||
+ slot_bytes.capacity() * size_of::<usize>()
|
||||
+ N * (size_of::<abi::Copy>() + size_of::<u8>() + size_of::<usize>())
|
||||
+ LAYERS * size_of::<Vec<abi::Copy>>()
|
||||
+ 5 * size_of::<thread::ScopedJoinHandle<'_, ()>>(),
|
||||
)
|
||||
.ok_or(Error::BudgetExceeded)?;
|
||||
let bookkeeping = layout.offsets.capacity() * size_of::<usize>()
|
||||
+ 2 * primary.capacity() * size_of::<(i32, i32, usize)>()
|
||||
+ slot_bytes.capacity() * size_of::<usize>();
|
||||
let prospective_meta = self.prospective_meta(bookkeeping)?;
|
||||
let bytes = layout.bytes;
|
||||
if prospective_meta > META_CAP
|
||||
|| bytes.checked_add(prospective_meta).is_none_or(|n| n > SOURCE_CAP)
|
||||
@@ -298,6 +318,26 @@ impl<'ctx> OriginalFileExpertSource<'ctx> {
|
||||
Ok(stack)
|
||||
}
|
||||
|
||||
/// The source metadata plus the build's own bookkeeping and the worker tables.
|
||||
fn prospective_meta(&self, bookkeeping: usize) -> Result<usize> {
|
||||
self.metadata_bytes()?
|
||||
.checked_add(
|
||||
bookkeeping
|
||||
+ N * (size_of::<abi::Copy>() + size_of::<u8>() + size_of::<usize>())
|
||||
+ LAYERS * size_of::<Vec<abi::Copy>>()
|
||||
+ 5 * size_of::<thread::ScopedJoinHandle<'_, ()>>(),
|
||||
)
|
||||
.ok_or(Error::BudgetExceeded)
|
||||
}
|
||||
|
||||
/// Takes the filled arena and its layout into the source.
|
||||
pub(super) fn commit_arena(&mut self, arena: abi::Arena, layout: Layout, slots: usize) {
|
||||
self.arena = Some(arena);
|
||||
self.offsets = layout.offsets;
|
||||
self.ready = true;
|
||||
self.lent_slots = if layout.lend.is_some() { slots - layout.keep_from } else { 0 };
|
||||
}
|
||||
|
||||
/// Pins the arena as asked, then copies every planned expert from the mapped source with worker threads.
|
||||
pub(super) fn fill_arena(
|
||||
&self,
|
||||
|
||||
+5
-22
@@ -1,7 +1,7 @@
|
||||
//! Moved out of the parent module by STRA-338: impl OriginalFileExpertSource (2).
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::build_phases::{discard_arena, poison_parts};
|
||||
use super::build_phases::{alloc_failed, discard_arena, leak_arena, poison_parts};
|
||||
use super::*;
|
||||
|
||||
impl<'ctx> OriginalFileExpertSource<'ctx> {
|
||||
@@ -18,38 +18,21 @@ impl<'ctx> OriginalFileExpertSource<'ctx> {
|
||||
let (primary, slot_bytes) = self.collect_primary(cache)?;
|
||||
let layout = self.plan_layout(cache, (&primary, &slot_bytes), (additional, rank), options)?;
|
||||
let stack = self.check_host_budget(&layout, (&primary, &slot_bytes), options.headroom_bytes)?;
|
||||
let guard = self.context.enter().inspect_err(|_| {
|
||||
self.failed = true;
|
||||
self.context.poison();
|
||||
self.context.retain_driver();
|
||||
})?;
|
||||
let guard = self.context.enter().inspect_err(|_| poison_parts(&mut self.failed, self.context))?;
|
||||
let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let mut arena = match api.allocate(layout.bytes, options.pin) {
|
||||
Ok(a) => a,
|
||||
Err(primary) => {
|
||||
let pop = guard.finish();
|
||||
if matches!(primary, Error::Driver { .. }) || pop.is_err() {
|
||||
self.failed = true;
|
||||
self.context.poison();
|
||||
self.context.retain_driver();
|
||||
}
|
||||
return combine(Err(primary), pop);
|
||||
}
|
||||
Err(primary) => return alloc_failed(&mut self.failed, self.context, guard, primary),
|
||||
};
|
||||
let prepare = self.fill_arena(api, &mut arena, &layout, options, stack);
|
||||
let pop = guard.finish();
|
||||
if pop.is_err() {
|
||||
poison_parts(&mut self.failed, self.context);
|
||||
std::mem::forget(arena);
|
||||
return combine(prepare, pop);
|
||||
return leak_arena(&mut self.failed, self.context, arena, combine(prepare, pop));
|
||||
}
|
||||
if let Err(primary) = prepare {
|
||||
return discard_arena(&mut self.failed, self.context, api, arena, primary);
|
||||
}
|
||||
self.arena = Some(arena);
|
||||
self.offsets = layout.offsets;
|
||||
self.ready = true;
|
||||
self.lent_slots = if layout.lend.is_some() { cache.slots() - layout.keep_from } else { 0 };
|
||||
self.commit_arena(arena, layout, cache.slots());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,28 +4,24 @@
|
||||
use super::*;
|
||||
|
||||
pub(super) fn assets() -> Result<[&'static [u8]; 2]> {
|
||||
let expected = PTX_SHA256.ok_or(Error::UnsupportedQwenOperation)?;
|
||||
let bytes = PTX_BYTES.ok_or(Error::UnsupportedQwenOperation)?;
|
||||
if bytes.checked_add(1) != Some(PTX.len())
|
||||
|| PTX.last() != Some(&0)
|
||||
|| PTX[..bytes].contains(&0)
|
||||
|| !PTX[..bytes].is_ascii()
|
||||
|| crate::qwen_ffi::sha256(&PTX[..bytes]) != expected
|
||||
{
|
||||
return Err(Error::UnsupportedQwenOperation);
|
||||
}
|
||||
let expected = PACK_PTX_SHA256.ok_or(Error::UnsupportedQwenOperation)?;
|
||||
let bytes = PACK_PTX_BYTES.ok_or(Error::UnsupportedQwenOperation)?;
|
||||
if bytes.checked_add(1) != Some(PACK_PTX.len())
|
||||
|| PACK_PTX.last() != Some(&0)
|
||||
|| PACK_PTX[..bytes].contains(&0)
|
||||
|| !PACK_PTX[..bytes].is_ascii()
|
||||
|| crate::qwen_ffi::sha256(&PACK_PTX[..bytes]) != expected
|
||||
{
|
||||
return Err(Error::UnsupportedQwenOperation);
|
||||
}
|
||||
check_ptx(PTX_SHA256, PTX_BYTES, PTX)?;
|
||||
check_ptx(PACK_PTX_SHA256, PACK_PTX_BYTES, PACK_PTX)?;
|
||||
Ok([PACK_PTX, PTX])
|
||||
}
|
||||
/// A sealed PTX is a pinned, NUL-terminated, NUL-free ASCII text of exactly the pinned length and digest.
|
||||
fn check_ptx(sha: Option<[u8; 32]>, length: Option<usize>, ptx: &[u8]) -> Result<()> {
|
||||
let expected = sha.ok_or(Error::UnsupportedQwenOperation)?;
|
||||
let bytes = length.ok_or(Error::UnsupportedQwenOperation)?;
|
||||
if bytes.checked_add(1) != Some(ptx.len())
|
||||
|| ptx.last() != Some(&0)
|
||||
|| ptx[..bytes].contains(&0)
|
||||
|| !ptx[..bytes].is_ascii()
|
||||
|| crate::qwen_ffi::sha256(&ptx[..bytes]) != expected
|
||||
{
|
||||
return Err(Error::UnsupportedQwenOperation);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
impl PleBatchCompletion<'_, '_> {
|
||||
pub fn rows(&self) -> usize {
|
||||
self.rows
|
||||
@@ -47,34 +43,50 @@ impl PleBatchCompletion<'_, '_> {
|
||||
let handles = self.owner.handles()?;
|
||||
let streams = handles[1].checked_subspan(self.owner.sizes[1], index * 40960, 40960)?;
|
||||
let history = handles[11].checked_subspan(self.owner.sizes[11], index * 368640, 368640)?;
|
||||
let (sv, hv) = self.owner.read_row(streams, history)?;
|
||||
self.next += 1;
|
||||
Ok(Some(PleBatchRow { streams: sv.into_boxed_slice(), history: hv.into_boxed_slice() }))
|
||||
}
|
||||
}
|
||||
impl PleBatchQueue<'_> {
|
||||
/// Downloads one row's streams and history; an uncertain drain leaks the staging buffers.
|
||||
fn read_row(&mut self, streams: BufferHandle, history: BufferHandle) -> Result<(Vec<f32>, Vec<f32>)> {
|
||||
let mut sb = staging(40960)?;
|
||||
let mut hb = staging(368640)?;
|
||||
let mut sv = float_owner(10240)?;
|
||||
let mut hv = float_owner(92160)?;
|
||||
let context = self.owner.context;
|
||||
let context = self.context;
|
||||
let guard = context.enter()?;
|
||||
let mut operation = context.driver.api.copy_to(streams, &mut sb);
|
||||
if operation.is_ok() {
|
||||
operation = context.driver.api.copy_to(history, &mut hb);
|
||||
}
|
||||
let operation =
|
||||
context.driver.api.copy_to(streams, &mut sb).and_then(|()| context.driver.api.copy_to(history, &mut hb));
|
||||
let sync = context.driver.api.synchronize();
|
||||
let pop = guard.finish();
|
||||
self.settle_row([operation, sync, pop], (sb, hb, sv, hv)).map(|(sb, hb, mut sv, mut hv)| {
|
||||
decode(&sb, &mut sv);
|
||||
decode(&hb, &mut hv);
|
||||
(sv, hv)
|
||||
})
|
||||
}
|
||||
/// Marks the queue failed on any error; an uncertain drain leaks the host buffers.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn settle_row(
|
||||
&mut self,
|
||||
[operation, sync, pop]: [Result<()>; 3],
|
||||
bufs: (Vec<u8>, Vec<u8>, Vec<f32>, Vec<f32>),
|
||||
) -> Result<(Vec<u8>, Vec<u8>, Vec<f32>, Vec<f32>)> {
|
||||
if operation.is_err() || sync.is_err() || pop.is_err() {
|
||||
self.owner.failed = true;
|
||||
context.poisoned.set(true);
|
||||
self.failed = true;
|
||||
self.context.poisoned.set(true);
|
||||
}
|
||||
if sync.is_err() || pop.is_err() {
|
||||
std::mem::forget((sb, hb, sv, hv));
|
||||
context.retain_driver();
|
||||
std::mem::forget(bufs);
|
||||
self.context.retain_driver();
|
||||
// Those genuine owners were retained, so no later statement may
|
||||
// borrow them even if a compiler cannot infer the failed drain.
|
||||
return combine(combine(operation, sync), pop).and_then(|()| Err(Error::ContextPoisoned));
|
||||
}
|
||||
combine(combine(operation, sync), pop)?;
|
||||
decode(&sb, &mut sv);
|
||||
decode(&hb, &mut hv);
|
||||
self.next += 1;
|
||||
Ok(Some(PleBatchRow { streams: sv.into_boxed_slice(), history: hv.into_boxed_slice() }))
|
||||
Ok(bufs)
|
||||
}
|
||||
}
|
||||
impl Context<'_> {
|
||||
|
||||
@@ -48,6 +48,20 @@ impl BatchHost {
|
||||
}
|
||||
|
||||
impl<'ctx> PleBatchQueue<'ctx> {
|
||||
/// Checks the inputs and weights, builds the launch list and allocates the host staging.
|
||||
pub(super) fn stage_batch(
|
||||
&self,
|
||||
workspace: &NativeBatchWorkspace<'_>,
|
||||
weights: &PleClosedWeights<'_, '_>,
|
||||
h: [BufferHandle; 15],
|
||||
(embedding, streams, history): (&[f32], &[f32], &[f32]),
|
||||
) -> Result<(usize, Vec<Command>, BatchHost)> {
|
||||
let rows = self.check_batch_inputs(workspace, h, (embedding, streams, history))?;
|
||||
let plan = self.batch_plan(workspace, weights, h, rows)?;
|
||||
let commands = self.batch_commands(&plan)?;
|
||||
Ok((rows, commands, BatchHost::new(embedding, streams, history, rows)?))
|
||||
}
|
||||
|
||||
/// Rejects spans aliasing the workspace and sources of the wrong shape or with non-finite values; returns the rows.
|
||||
pub(super) fn check_batch_inputs(
|
||||
&self,
|
||||
@@ -144,6 +158,61 @@ impl<'ctx> PleBatchQueue<'ctx> {
|
||||
api.synchronize()
|
||||
}
|
||||
|
||||
pub(super) fn batch_modules(&self) -> Result<(&KernelModule, &KernelModule)> {
|
||||
let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let pack = self.pack_module.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
Ok((module, pack))
|
||||
}
|
||||
|
||||
/// Reads the status words back once the stream drained cleanly.
|
||||
pub(super) fn read_batch_statuses(
|
||||
&self,
|
||||
operation: Result<()>,
|
||||
sync: &Result<()>,
|
||||
status: BufferHandle,
|
||||
host: &mut BatchHost,
|
||||
) -> Result<()> {
|
||||
if operation.is_ok() && sync.is_ok() {
|
||||
return self.context.driver.api.copy_to(status, &mut host.statuses);
|
||||
}
|
||||
operation
|
||||
}
|
||||
|
||||
/// Marks the queue failed on any error; an uncertain drain leaks every host buffer the device may still read.
|
||||
pub(super) fn settle_batch(
|
||||
&mut self,
|
||||
workspace: &mut NativeBatchWorkspace<'_>,
|
||||
[operation, sync, all, pop]: [Result<()>; 4],
|
||||
(commands, host, weights): (Vec<Command>, BatchHost, PleClosedWeights<'_, '_>),
|
||||
) -> Result<BatchHost> {
|
||||
if operation.is_err() || sync.is_err() || all.is_err() || pop.is_err() {
|
||||
self.failed = true;
|
||||
workspace.mark_failed();
|
||||
}
|
||||
if sync.is_err() || all.is_err() || pop.is_err() {
|
||||
std::mem::forget((commands, host, weights));
|
||||
self.context.retain_driver();
|
||||
return combine(combine(combine(operation, sync), all), pop)
|
||||
.map(|()| unreachable!("uncertain PLE batch drain"));
|
||||
}
|
||||
combine(combine(combine(operation, sync), all), pop)?;
|
||||
Ok(host)
|
||||
}
|
||||
|
||||
/// Decodes the status words into the completion; a status above 1 fails the queue.
|
||||
pub(super) fn finish_batch<'loan>(
|
||||
&'loan mut self,
|
||||
rows: usize,
|
||||
mut host: BatchHost,
|
||||
) -> Result<PleBatchCompletion<'loan, 'ctx>> {
|
||||
if !host.decode_flags() {
|
||||
self.failed = true;
|
||||
self.context.poisoned.set(true);
|
||||
return Err(Error::InvalidDriverValue("PLE batch finite status"));
|
||||
}
|
||||
Ok(PleBatchCompletion { owner: self, rows, next: 0, flags: host.flags.into_boxed_slice() })
|
||||
}
|
||||
|
||||
/// Launches every command in order; the first failure stops the rest.
|
||||
pub(super) fn launch_batch(
|
||||
&self,
|
||||
|
||||
@@ -15,62 +15,44 @@ impl<'ctx> PleBatchQueue<'ctx> {
|
||||
if !(1..=8192).contains(&capacity) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let mut sizes = SIZES;
|
||||
for (i, size) in sizes.iter_mut().enumerate() {
|
||||
if i != 2 {
|
||||
*size = (*size / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?;
|
||||
}
|
||||
}
|
||||
let sizes = batch_sizes(capacity)?;
|
||||
let ptx = assets()?; // explicit pending refusal before any allocation/module.
|
||||
if context.is_poisoned() || context.handle.is_none() {
|
||||
return Err(Error::ContextPoisoned);
|
||||
}
|
||||
let required = sizes
|
||||
.iter()
|
||||
.try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))?
|
||||
.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 mut owner = Self {
|
||||
capacity,
|
||||
sizes,
|
||||
context,
|
||||
buffers: std::array::from_fn(|_| None),
|
||||
pack_module: None,
|
||||
module: None,
|
||||
mode,
|
||||
failed: false,
|
||||
};
|
||||
let operation = (|| {
|
||||
for (i, bytes) in sizes.into_iter().enumerate() {
|
||||
owner.buffers[i] = Some(context.allocate(bytes)?);
|
||||
}
|
||||
let guard = context.enter()?;
|
||||
let load = (|| {
|
||||
owner.pack_module = Some(KernelModule::load(ptx[0], &PACK_ENTRIES)?);
|
||||
owner.module = Some(KernelModule::load(ptx[1], &ENTRIES)?);
|
||||
Ok(())
|
||||
})();
|
||||
let pop = guard.finish();
|
||||
if pop.is_err() {
|
||||
context.poisoned.set(true);
|
||||
}
|
||||
combine(load, pop)?;
|
||||
owner.handles()?;
|
||||
if context.memory_info()?.0 < RESERVE {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = operation {
|
||||
check_required(context, &sizes)?;
|
||||
let buffers = std::array::from_fn(|_| None);
|
||||
let mut owner =
|
||||
Self { capacity, sizes, context, buffers, pack_module: None, module: None, mode, failed: false };
|
||||
if let Err(error) = owner.init_resources(ptx) {
|
||||
return combine(Err(error), owner.close());
|
||||
}
|
||||
Ok(owner)
|
||||
}
|
||||
/// Allocates every buffer, loads both kernel modules under the context guard and re-checks the free memory.
|
||||
fn init_resources(&mut self, ptx: [&'static [u8]; 2]) -> Result<()> {
|
||||
let context = self.context;
|
||||
for (i, bytes) in self.sizes.into_iter().enumerate() {
|
||||
self.buffers[i] = Some(context.allocate(bytes)?);
|
||||
}
|
||||
let guard = context.enter()?;
|
||||
let load = self.load_modules(ptx);
|
||||
let pop = guard.finish();
|
||||
if pop.is_err() {
|
||||
context.poisoned.set(true);
|
||||
}
|
||||
combine(load, pop)?;
|
||||
self.handles()?;
|
||||
if context.memory_info()?.0 < RESERVE {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn load_modules(&mut self, ptx: [&'static [u8]; 2]) -> Result<()> {
|
||||
self.pack_module = Some(KernelModule::load(ptx[0], &PACK_ENTRIES)?);
|
||||
self.module = Some(KernelModule::load(ptx[1], &ENTRIES)?);
|
||||
Ok(())
|
||||
}
|
||||
pub fn prompt_device_bytes(capacity: usize) -> Result<usize> {
|
||||
if !(1..=8192).contains(&capacity) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
@@ -102,27 +84,31 @@ impl<'ctx> PleBatchQueue<'ctx> {
|
||||
let first = self.buffer(0)?.handle.ok_or(Error::ContextPoisoned)?;
|
||||
let mut handles = [first; 15];
|
||||
for (i, bytes) in self.sizes.into_iter().enumerate() {
|
||||
let b = self.buffer(i)?;
|
||||
if !std::ptr::eq(b.context, self.context) {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
if b.bytes != bytes {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let h = b.handle.ok_or(Error::ContextPoisoned)?;
|
||||
h.validate_projection_extent(bytes, 4)?;
|
||||
for (j, other) in handles.iter().take(i).enumerate() {
|
||||
if h.overlaps(bytes, *other, self.sizes[j]) {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
}
|
||||
handles[i] = h;
|
||||
handles[i] = self.checked_buffer(i, bytes, &handles)?;
|
||||
}
|
||||
if self.context.allocated_bytes() > self.context.budget {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(handles)
|
||||
}
|
||||
/// Buffer `i` must belong to this context, have exactly `bytes` and overlap no earlier buffer.
|
||||
fn checked_buffer(&self, i: usize, bytes: usize, handles: &[BufferHandle; 15]) -> Result<BufferHandle> {
|
||||
let b = self.buffer(i)?;
|
||||
if !std::ptr::eq(b.context, self.context) {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
if b.bytes != bytes {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let h = b.handle.ok_or(Error::ContextPoisoned)?;
|
||||
h.validate_projection_extent(bytes, 4)?;
|
||||
for (j, other) in handles.iter().take(i).enumerate() {
|
||||
if h.overlaps(bytes, *other, self.sizes[j]) {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
}
|
||||
Ok(h)
|
||||
}
|
||||
pub(in super::super) fn weight(&self, w: &DeviceBuffer<'_>, bytes: usize, alignment: u64) -> Result<BufferHandle> {
|
||||
if !std::ptr::eq(w.context, self.context) {
|
||||
return Err(Error::ContextMismatch);
|
||||
@@ -140,3 +126,29 @@ impl<'ctx> PleBatchQueue<'ctx> {
|
||||
Ok(h)
|
||||
}
|
||||
}
|
||||
|
||||
/// Buffer sizes for a queue of `capacity` rows (the history is fixed).
|
||||
fn batch_sizes(capacity: usize) -> Result<[usize; 15]> {
|
||||
let mut sizes = SIZES;
|
||||
for (i, size) in sizes.iter_mut().enumerate() {
|
||||
if i != 2 {
|
||||
*size = (*size / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?;
|
||||
}
|
||||
}
|
||||
Ok(sizes)
|
||||
}
|
||||
|
||||
/// The buffers plus the reserve must fit the context budget and the free device memory.
|
||||
fn check_required(context: &Context<'_>, sizes: &[usize; 15]) -> Result<()> {
|
||||
let required = sizes
|
||||
.iter()
|
||||
.try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))?
|
||||
.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(())
|
||||
}
|
||||
|
||||
+7
-30
@@ -18,41 +18,18 @@ impl<'ctx> PleBatchQueue<'ctx> {
|
||||
) -> Result<PleBatchCompletion<'loan, 'ctx>> {
|
||||
workspace.validate_context(self.context)?;
|
||||
let h = self.handles()?;
|
||||
let rows = self.check_batch_inputs(workspace, h, (embedding, streams, history))?;
|
||||
let plan = self.batch_plan(workspace, &weights, h, rows)?;
|
||||
let mut commands = self.batch_commands(&plan)?;
|
||||
let mut host = BatchHost::new(embedding, streams, history, rows)?;
|
||||
let (rows, mut commands, mut host) = self.stage_batch(workspace, &weights, h, (embedding, streams, history))?;
|
||||
let context = self.context;
|
||||
let guard = context.enter()?;
|
||||
let mut operation = self.upload_batch(&h, &host);
|
||||
let operation = self.upload_batch(&h, &host);
|
||||
let blas = workspace.blas()?;
|
||||
let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let pack = self.pack_module.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
if operation.is_ok() {
|
||||
operation = self.launch_batch((blas, pack, module), &mut commands);
|
||||
}
|
||||
let (module, pack) = self.batch_modules()?;
|
||||
let operation = operation.and_then(|()| self.launch_batch((blas, pack, module), &mut commands));
|
||||
let sync = blas.synchronize();
|
||||
if operation.is_ok() && sync.is_ok() {
|
||||
operation = context.driver.api.copy_to(h[14], &mut host.statuses);
|
||||
}
|
||||
let operation = self.read_batch_statuses(operation, &sync, h[14], &mut host);
|
||||
let all = context.driver.api.synchronize();
|
||||
let pop = guard.finish();
|
||||
if operation.is_err() || sync.is_err() || all.is_err() || pop.is_err() {
|
||||
self.failed = true;
|
||||
workspace.mark_failed();
|
||||
}
|
||||
if sync.is_err() || all.is_err() || pop.is_err() {
|
||||
std::mem::forget((commands, host, weights));
|
||||
context.retain_driver();
|
||||
return combine(combine(combine(operation, sync), all), pop)
|
||||
.map(|()| unreachable!("uncertain PLE batch drain"));
|
||||
}
|
||||
combine(combine(combine(operation, sync), all), pop)?;
|
||||
if !host.decode_flags() {
|
||||
self.failed = true;
|
||||
context.poisoned.set(true);
|
||||
return Err(Error::InvalidDriverValue("PLE batch finite status"));
|
||||
}
|
||||
Ok(PleBatchCompletion { owner: self, rows, next: 0, flags: host.flags.into_boxed_slice() })
|
||||
let host = self.settle_batch(workspace, [operation, sync, all, pop], (commands, host, weights))?;
|
||||
self.finish_batch(rows, host)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::CurrentGuard;
|
||||
|
||||
impl<'ctx> PleBatchQueue<'ctx> {
|
||||
pub fn close(mut self) -> Result<()> {
|
||||
@@ -12,49 +13,16 @@ impl<'ctx> PleBatchQueue<'ctx> {
|
||||
let mut result = Ok(());
|
||||
// No queued commands survive a successful compose. A poisoned owner
|
||||
// retains vendor/kernel/whole banks and the Driver instead of freeing.
|
||||
let guard = if self.context.is_poisoned() {
|
||||
None
|
||||
} else {
|
||||
match self.context.enter() {
|
||||
Ok(g) => Some(g),
|
||||
Err(e) => {
|
||||
self.context.poisoned.set(true);
|
||||
result = Err(e);
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
let guard = self.close_guard(&mut result);
|
||||
for module in [self.pack_module.take(), self.module.take()].into_iter().flatten() {
|
||||
let close = if self.context.is_poisoned() {
|
||||
std::mem::forget(module);
|
||||
Err(Error::ContextPoisoned)
|
||||
} else {
|
||||
module.close()
|
||||
};
|
||||
if close.is_err() {
|
||||
self.context.poisoned.set(true);
|
||||
}
|
||||
result = combine(result, close);
|
||||
result = combine(result, close_or_leak(self.context, module, |m| m.close()));
|
||||
}
|
||||
if let Some(g) = guard {
|
||||
let pop = g.finish();
|
||||
if pop.is_err() {
|
||||
self.context.poisoned.set(true);
|
||||
}
|
||||
result = combine(result, pop);
|
||||
result = combine(result, poison_on_error(self.context, g.finish()));
|
||||
}
|
||||
for slot in &mut self.buffers {
|
||||
if let Some(b) = slot.take() {
|
||||
let close = if self.context.is_poisoned() {
|
||||
std::mem::forget(b);
|
||||
Err(Error::ContextPoisoned)
|
||||
} else {
|
||||
b.release()
|
||||
};
|
||||
if close.is_err() {
|
||||
self.context.poisoned.set(true);
|
||||
}
|
||||
result = combine(result, close);
|
||||
result = combine(result, close_or_leak(self.context, b, |b| b.release()));
|
||||
}
|
||||
}
|
||||
if self.context.is_poisoned() {
|
||||
@@ -62,4 +30,34 @@ impl<'ctx> PleBatchQueue<'ctx> {
|
||||
}
|
||||
result
|
||||
}
|
||||
/// Enters the context for the module closes, unless it is already poisoned; an enter failure poisons it.
|
||||
fn close_guard(&self, result: &mut Result<()>) -> Option<CurrentGuard<'ctx, 'ctx>> {
|
||||
if self.context.is_poisoned() {
|
||||
return None;
|
||||
}
|
||||
match self.context.enter() {
|
||||
Ok(g) => Some(g),
|
||||
Err(e) => {
|
||||
self.context.poisoned.set(true);
|
||||
*result = Err(e);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes an owner, or leaks it when the context is poisoned; a failed close poisons the context.
|
||||
fn close_or_leak<T>(context: &Context<'_>, owner: T, close: impl FnOnce(T) -> Result<()>) -> Result<()> {
|
||||
if context.is_poisoned() {
|
||||
std::mem::forget(owner);
|
||||
return Err(Error::ContextPoisoned);
|
||||
}
|
||||
poison_on_error(context, close(owner))
|
||||
}
|
||||
|
||||
fn poison_on_error(context: &Context<'_>, r: Result<()>) -> Result<()> {
|
||||
if r.is_err() {
|
||||
context.poisoned.set(true);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
@@ -187,4 +187,72 @@ impl<'ctx> PleClosedQueue<'ctx> {
|
||||
context.driver.api.copy_to(handles[12], &mut host.streams_out)?;
|
||||
context.driver.api.copy_to(handles[11], &mut host.history_out)
|
||||
}
|
||||
|
||||
/// Marks the queue failed on any error; an uncertain drain leaks every host buffer the device may still read.
|
||||
pub(super) fn settle_compose(
|
||||
&mut self,
|
||||
[operation, sync, pop]: [Result<()>; 3],
|
||||
(commands, reset, host, weights): (
|
||||
Vec<Command>,
|
||||
ffi::MmqResidentArguments,
|
||||
ComposeHost,
|
||||
PleClosedWeights<'_, '_>,
|
||||
),
|
||||
) -> Result<ComposeHost> {
|
||||
if operation.is_err() || sync.is_err() || pop.is_err() {
|
||||
self.failed = true;
|
||||
self.context.poisoned.set(true);
|
||||
}
|
||||
if sync.is_err() || pop.is_err() {
|
||||
std::mem::forget((commands, reset, host, weights));
|
||||
self.context.retain_driver();
|
||||
return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain PLE drain"));
|
||||
}
|
||||
combine(combine(operation, sync), pop)?;
|
||||
Ok(host)
|
||||
}
|
||||
|
||||
/// Decodes the drained results into the completion; a status above 1 fails the queue.
|
||||
pub(super) fn finish_compose<'loan>(
|
||||
&'loan mut self,
|
||||
mut host: ComposeHost,
|
||||
) -> Result<PleClosedCompletion<'loan, 'ctx>> {
|
||||
let Some(flags) = host.decode_flags() else {
|
||||
self.failed = true;
|
||||
self.context.poisoned.set(true);
|
||||
return Err(Error::InvalidDriverValue("PLE finite status"));
|
||||
};
|
||||
// Staging is no longer exposed or used once the actual completion drains.
|
||||
host.embedding_bytes.clear();
|
||||
host.streams_bytes.clear();
|
||||
host.history_bytes.clear();
|
||||
Ok(PleClosedCompletion {
|
||||
owner: self,
|
||||
flags,
|
||||
streams: host.streams_values.into_boxed_slice(),
|
||||
history: host.history_values.into_boxed_slice(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Unloads the kernel module under the context guard, or leaks it on a poisoned context.
|
||||
pub(super) fn unload_module(&self, module: ffi::ModuleHandle) -> Result<()> {
|
||||
let release = if self.context.is_poisoned() {
|
||||
self.context.retain_driver();
|
||||
Err(Error::ContextPoisoned)
|
||||
} else {
|
||||
match self.context.enter() {
|
||||
Ok(guard) => {
|
||||
let unload = self.context.driver.api.unload(module);
|
||||
let pop = guard.finish();
|
||||
combine(unload, pop)
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
};
|
||||
if release.is_err() {
|
||||
self.context.poisoned.set(true);
|
||||
self.context.retain_driver();
|
||||
}
|
||||
release
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,16 @@ impl PleClosedCompletion<'_, '_> {
|
||||
Ok((self.streams, self.history))
|
||||
}
|
||||
}
|
||||
/// The queue's charge plus the reserve must fit the context budget and the free device memory.
|
||||
fn check_charge(context: &Context<'_>) -> Result<()> {
|
||||
let required = CHARGE.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(())
|
||||
}
|
||||
impl Context<'_> {
|
||||
pub fn ple_closed_queue(&self) -> Result<PleClosedQueue<'_>> {
|
||||
PleClosedQueue::new(self)
|
||||
@@ -29,56 +39,49 @@ impl<'ctx> PleClosedQueue<'ctx> {
|
||||
for operation in OPS {
|
||||
qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?.validate(operation)?;
|
||||
}
|
||||
let required = CHARGE.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 mut owner = Self {
|
||||
context,
|
||||
buffers: std::array::from_fn(|_| None),
|
||||
module: None,
|
||||
functions: None,
|
||||
finite: None,
|
||||
failed: 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 mut functions = [None; 6];
|
||||
for (i, operation) in OPS.into_iter().enumerate() {
|
||||
let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?;
|
||||
functions[i] = Some(registered(context, &context.qwen_kernels, asset)?.function);
|
||||
}
|
||||
owner.functions = Some(functions.map(|f| f.expect("six admitted original PLE operators")));
|
||||
let module = context.driver.api.load_mmq_resident()?;
|
||||
owner.module = Some(module);
|
||||
owner.finite = Some([
|
||||
context.driver.api.mmq_resident_function(module, 0)?,
|
||||
context.driver.api.mmq_resident_function(module, 1)?,
|
||||
]);
|
||||
Ok(())
|
||||
})();
|
||||
let pop = guard.finish();
|
||||
if pop.is_err() {
|
||||
context.poisoned.set(true);
|
||||
}
|
||||
combine(load, pop)?;
|
||||
owner.handles()?;
|
||||
if context.memory_info()?.0 < RESERVE {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = operation {
|
||||
check_charge(context)?;
|
||||
let buffers = std::array::from_fn(|_| None);
|
||||
let mut owner = Self { context, buffers, module: None, functions: None, finite: None, failed: false };
|
||||
if let Err(error) = owner.init_resources() {
|
||||
return combine(Err(error), owner.close());
|
||||
}
|
||||
Ok(owner)
|
||||
}
|
||||
/// Allocates every buffer, registers the operators and loads the finite kernels under the context guard.
|
||||
fn init_resources(&mut self) -> 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_kernels();
|
||||
let pop = guard.finish();
|
||||
if pop.is_err() {
|
||||
context.poisoned.set(true);
|
||||
}
|
||||
combine(load, pop)?;
|
||||
self.handles()?;
|
||||
if context.memory_info()?.0 < RESERVE {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn load_kernels(&mut self) -> Result<()> {
|
||||
let context = self.context;
|
||||
let mut functions = [None; 6];
|
||||
for (i, operation) in OPS.into_iter().enumerate() {
|
||||
let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?;
|
||||
functions[i] = Some(registered(context, &context.qwen_kernels, asset)?.function);
|
||||
}
|
||||
self.functions = Some(functions.map(|f| f.expect("six admitted original PLE operators")));
|
||||
let module = context.driver.api.load_mmq_resident()?;
|
||||
self.module = Some(module);
|
||||
self.finite = Some([
|
||||
context.driver.api.mmq_resident_function(module, 0)?,
|
||||
context.driver.api.mmq_resident_function(module, 1)?,
|
||||
]);
|
||||
Ok(())
|
||||
}
|
||||
pub fn validate_context(&self, context: &Context<'_>) -> Result<()> {
|
||||
if !std::ptr::eq(self.context, context) {
|
||||
return Err(Error::ContextMismatch);
|
||||
@@ -101,27 +104,31 @@ impl<'ctx> PleClosedQueue<'ctx> {
|
||||
let first = self.buffer(0)?.handle.ok_or(Error::ContextPoisoned)?;
|
||||
let mut handles = [first; 14];
|
||||
for (i, bytes) in SIZES.into_iter().enumerate() {
|
||||
let buffer = self.buffer(i)?;
|
||||
if !std::ptr::eq(buffer.context, self.context) {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
if buffer.bytes != bytes {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let handle = buffer.handle.ok_or(Error::ContextPoisoned)?;
|
||||
handle.validate_projection_extent(bytes, 4)?;
|
||||
for (j, other) in handles.iter().take(i).enumerate() {
|
||||
if handle.overlaps(bytes, *other, SIZES[j]) {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
}
|
||||
handles[i] = handle;
|
||||
handles[i] = self.checked_buffer(i, bytes, &handles)?;
|
||||
}
|
||||
if self.context.allocated_bytes() > self.context.budget {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(handles)
|
||||
}
|
||||
/// Buffer `i` must belong to this context, have exactly `bytes` and overlap no earlier buffer.
|
||||
fn checked_buffer(&self, i: usize, bytes: usize, handles: &[ffi::BufferHandle; 14]) -> Result<ffi::BufferHandle> {
|
||||
let buffer = self.buffer(i)?;
|
||||
if !std::ptr::eq(buffer.context, self.context) {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
if buffer.bytes != bytes {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let handle = buffer.handle.ok_or(Error::ContextPoisoned)?;
|
||||
handle.validate_projection_extent(bytes, 4)?;
|
||||
for (j, other) in handles.iter().take(i).enumerate() {
|
||||
if handle.overlaps(bytes, *other, SIZES[j]) {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
}
|
||||
Ok(handle)
|
||||
}
|
||||
pub(super) fn weight(&self, weight: &DeviceBuffer<'_>, bytes: usize, alignment: u64) -> Result<()> {
|
||||
if !std::ptr::eq(weight.context, self.context) {
|
||||
return Err(Error::ContextMismatch);
|
||||
|
||||
@@ -24,31 +24,8 @@ impl<'ctx> PleClosedQueue<'ctx> {
|
||||
let operation = self.drain_ops(&handles, &mut commands, &mut reset, &mut host);
|
||||
let sync = context.driver.api.synchronize();
|
||||
let pop = guard.finish();
|
||||
if operation.is_err() || sync.is_err() || pop.is_err() {
|
||||
self.failed = true;
|
||||
context.poisoned.set(true);
|
||||
}
|
||||
if sync.is_err() || pop.is_err() {
|
||||
std::mem::forget((commands, reset, host, weights));
|
||||
context.retain_driver();
|
||||
return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain PLE drain"));
|
||||
}
|
||||
combine(combine(operation, sync), pop)?;
|
||||
let Some(flags) = host.decode_flags() else {
|
||||
self.failed = true;
|
||||
context.poisoned.set(true);
|
||||
return Err(Error::InvalidDriverValue("PLE finite status"));
|
||||
};
|
||||
// Staging is no longer exposed or used once the actual completion drains.
|
||||
host.embedding_bytes.clear();
|
||||
host.streams_bytes.clear();
|
||||
host.history_bytes.clear();
|
||||
Ok(PleClosedCompletion {
|
||||
owner: self,
|
||||
flags,
|
||||
streams: host.streams_values.into_boxed_slice(),
|
||||
history: host.history_values.into_boxed_slice(),
|
||||
})
|
||||
let host = self.settle_compose([operation, sync, pop], (commands, reset, host, weights))?;
|
||||
self.finish_compose(host)
|
||||
}
|
||||
pub fn close(mut self) -> Result<()> {
|
||||
self.close_inner()
|
||||
@@ -60,37 +37,11 @@ impl<'ctx> PleClosedQueue<'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));
|
||||
}
|
||||
}
|
||||
if let Some(module) = self.module.take() {
|
||||
let release = if self.context.is_poisoned() {
|
||||
self.context.retain_driver();
|
||||
Err(Error::ContextPoisoned)
|
||||
} else {
|
||||
match self.context.enter() {
|
||||
Ok(guard) => {
|
||||
let unload = self.context.driver.api.unload(module);
|
||||
let pop = guard.finish();
|
||||
combine(unload, pop)
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
};
|
||||
if release.is_err() {
|
||||
self.context.poisoned.set(true);
|
||||
self.context.retain_driver();
|
||||
}
|
||||
result = combine(result, release);
|
||||
result = combine(result, self.unload_module(module));
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -113,3 +64,17 @@ pub(super) fn float_staging(values: &[f32]) -> Result<Vec<u8>> {
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// A buffer is released, or leaked on a poisoned context; a failed release poisons the context.
|
||||
fn release_buffer<'ctx>(context: &Context<'ctx>, buffer: DeviceBuffer<'ctx>) -> 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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user