Files
leleka/crates/cuda-driver/src/mmq/context.rs
T

362 lines
15 KiB
Rust

//! MMQ weight upload on a Context: format and charge admission, then repacking host or device raw weights into
//! padded MMQ layouts (single, gate/up/down triplet, owned gate-up) with checks that block counts and targets fit.
use super::{
Context, DeviceBuffer, Error, Layout, MmqFormat, MmqWeights, ProjectionKind, ProjectionSpec, Result, RoutedFormat,
bytes, combine, ffi, release_triplet,
};
impl Context<'_> {
/// Closed Gate/Up/Down upload. All three immutable owners become usable
/// only after the attempted copies share one confirmed completion fence.
pub fn mmq_weight_triplet(&self, formats: [MmqFormat; 3], raw: [&[u8]; 3]) -> Result<[MmqWeights<'_>; 3]> {
let layouts = self.triplet_admit(formats, &raw)?;
let mut staging = [bytes(layouts[0].weight)?, bytes(layouts[1].weight)?, bytes(layouts[2].weight)?];
for (padded, source) in staging.iter_mut().zip(raw) {
padded[..source.len()].copy_from_slice(source);
}
let buffers = self.allocate_triplet(&layouts)?;
let operation = self.triplet_upload(&buffers, &mut staging);
if let Err(primary) = operation {
// Poisoned release retains uncertain native allocations/charges;
// completed failures attempt every owner, never publish a prefix.
return combine(Err(primary), release_triplet(self, buffers));
}
Ok(self.publish_triplet(formats, buffers))
}
/// One device buffer per layout; a failed allocation releases the ones already made.
fn allocate_triplet(&self, layouts: &[Layout; 3]) -> Result<[Option<DeviceBuffer<'_>>; 3]> {
let mut buffers: [Option<DeviceBuffer<'_>>; 3] = std::array::from_fn(|_| None);
for (slot, layout) in layouts.iter().enumerate() {
match self.allocate(layout.weight) {
Ok(buffer) => buffers[slot] = Some(buffer),
Err(primary) => return combine(Err(primary), release_triplet(self, buffers)),
}
}
Ok(buffers)
}
fn publish_triplet<'a>(
&'a self,
formats: [MmqFormat; 3],
buffers: [Option<DeviceBuffer<'a>>; 3],
) -> [MmqWeights<'a>; 3] {
let [Some(gate), Some(up), Some(down)] = buffers else {
unreachable!("all triplet allocations completed before the upload")
};
[
MmqWeights { context: self, format: formats[0], buffer: Some(gate) },
MmqWeights { context: self, format: formats[1], buffer: Some(up) },
MmqWeights { context: self, format: formats[2], buffer: Some(down) },
]
}
/// Context state and formats (`allowed` Gate/Up kinds, Iq4NlDown or Q2Down for Down) of a weight triplet.
fn admit_formats(&self, formats: [MmqFormat; 3], allowed: &[MmqFormat]) -> Result<[Layout; 3]> {
if self.is_poisoned() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
if !formats[..2].iter().all(|format| allowed.contains(format))
|| !matches!(formats[2], MmqFormat::Iq4NlDown | MmqFormat::Q2Down)
{
return Err(Error::InvalidProjectionShape);
}
Ok([formats[0].layout(1)?, formats[1].layout(1)?, formats[2].layout(1)?])
}
/// The padded charge must fit the context budget.
fn admit_charge(&self, charge: usize) -> Result<()> {
if self.allocated.get().checked_add(charge).is_none_or(|n| n > self.budget) {
return Err(Error::BudgetExceeded);
}
Ok(())
}
/// Format, source and budget admission of three host weight images; returns their layouts.
fn triplet_admit(&self, formats: [MmqFormat; 3], raw: &[&[u8]; 3]) -> Result<[Layout; 3]> {
let layouts = self.admit_formats(formats, &[MmqFormat::Iq3XxsGateUp, MmqFormat::Iq2SGateUp])?;
let mut charge = 0usize;
// Validate every source before allocating staging or entering CUDA.
for (source, layout) in raw.iter().zip(layouts) {
if source.len() != layout.raw_weight {
return Err(Error::InvalidProjectionShape);
}
check_weight_blocks(source, &layout)?;
charge = charge.checked_add(layout.weight).ok_or(Error::BudgetExceeded)?;
}
self.admit_charge(charge)?;
Ok(layouts)
}
/// Copies the three padded staging images into their device buffers under one confirmed fence.
fn triplet_upload(&self, buffers: &[Option<DeviceBuffer<'_>>; 3], staging: &mut [Vec<u8>; 3]) -> Result<()> {
let handles = buffer_handles(buffers)?;
let guard = self.enter()?;
let mut copy = Ok(());
for (handle, padded) in handles.into_iter().zip(staging.iter()) {
copy = self.driver.api.copy_from(handle, padded);
if copy.is_err() {
break;
}
}
// Drain every attempted copy, including reported command errors.
let sync = self.driver.api.synchronize();
let restored = guard.finish();
if sync.is_err() || restored.is_err() {
self.poisoned.set(true);
// Even successful synchronous-looking H2D calls are not a
// lifetime certificate after failed completion/restoration.
std::mem::forget(std::mem::take(staging));
}
combine(combine(copy, sync), restored)
}
/// Byte transport from three actual immutable raw GPU owners into three
/// genuine padded MMQ owners. This is not a source/finite certificate:
/// the runtime retains and authenticates its binding/source/role loans.
pub fn mmq_weight_triplet_from_device(
&self,
formats: [MmqFormat; 3],
raw: [&DeviceBuffer<'_>; 3],
) -> Result<[MmqWeights<'_>; 3]> {
let (layouts, sources) = self.device_triplet_admit(formats, &raw)?;
// Only the literal over-read tails have host staging; no raw GPU weight
// is read back or presented as borrowed padded/ready weights.
let mut tails = [
bytes(layouts[0].weight - layouts[0].raw_weight)?,
bytes(layouts[1].weight - layouts[1].raw_weight)?,
bytes(layouts[2].weight - layouts[2].raw_weight)?,
];
let buffers = self.allocate_triplet(&layouts)?;
let operation = self.device_triplet_operation(&buffers, &mut tails, (&layouts, &raw), sources);
if let Err(primary) = operation {
return combine(Err(primary), release_triplet(self, buffers));
}
Ok(self.publish_triplet(formats, buffers))
}
/// Format, context, extent, alias and budget admission of three raw GPU owners; returns layouts and handles.
fn device_triplet_admit(
&self,
formats: [MmqFormat; 3],
raw: &[&DeviceBuffer<'_>; 3],
) -> Result<([Layout; 3], [ffi::BufferHandle; 3])> {
let allowed = [
MmqFormat::Iq3XxsGateUp,
MmqFormat::Iq2SGateUp,
MmqFormat::Iq3SGateUp,
MmqFormat::Iq4XsGateUp,
MmqFormat::Iq4NlGateUp,
];
let layouts = self.admit_formats(formats, &allowed)?;
let sources = [
raw[0].handle.ok_or(Error::ContextPoisoned)?,
raw[1].handle.ok_or(Error::ContextPoisoned)?,
raw[2].handle.ok_or(Error::ContextPoisoned)?,
];
let charge = self.device_triplet_charge(formats, raw, (&layouts, &sources))?;
self.admit_charge(charge)?;
Ok((layouts, sources))
}
/// Checks each raw owner (context, size, extent, overlap with the earlier ones); returns the padded byte charge.
fn device_triplet_charge(
&self,
formats: [MmqFormat; 3],
raw: &[&DeviceBuffer<'_>; 3],
(layouts, sources): (&[Layout; 3], &[ffi::BufferHandle; 3]),
) -> Result<usize> {
let mut charge = 0usize;
for i in 0..3 {
if !std::ptr::eq(self, raw[i].context) {
return Err(Error::ContextMismatch);
}
if raw[i].bytes != layouts[i].raw_weight {
return Err(Error::InvalidProjectionShape);
}
let alignment = if formats[i] == MmqFormat::Iq4XsGateUp { 4 } else { 2 };
sources[i].validate_projection_extent(raw[i].bytes, alignment)?;
for j in 0..i {
if sources[i].overlaps(raw[i].bytes, sources[j], raw[j].bytes) {
return Err(Error::OutputAliasesInput);
}
}
charge = charge.checked_add(layouts[i].weight).ok_or(Error::BudgetExceeded)?;
}
Ok(charge)
}
/// Validates the three padded targets against the sources and each other, then copies raw weights and tails.
fn device_triplet_operation(
&self,
buffers: &[Option<DeviceBuffer<'_>>; 3],
tails: &mut [Vec<u8>; 3],
(layouts, raw): (&[Layout; 3], &[&DeviceBuffer<'_>; 3]),
sources: [ffi::BufferHandle; 3],
) -> Result<()> {
let targets = buffer_handles(buffers)?;
let raw_bytes = [raw[0].bytes, raw[1].bytes, raw[2].bytes];
check_padded_targets((sources, targets), raw_bytes, layouts)?;
let mut tail_handles = [None; 3];
for i in 0..3 {
if !tails[i].is_empty() {
tail_handles[i] =
Some(targets[i].checked_subspan(layouts[i].weight, layouts[i].raw_weight, tails[i].len())?);
}
}
self.device_triplet_copy((targets, sources), (&tail_handles, tails), raw_bytes)
}
/// One guarded sequence of tail uploads and device-to-device weight copies, drained by one synchronize.
fn device_triplet_copy(
&self,
(targets, sources): ([ffi::BufferHandle; 3], [ffi::BufferHandle; 3]),
(tail_handles, tails): (&[Option<ffi::BufferHandle>; 3], &mut [Vec<u8>; 3]),
raw_bytes: [usize; 3],
) -> Result<()> {
let guard = self.enter()?;
let copy = self.device_triplet_enqueue((targets, sources), (tail_handles, tails), raw_bytes);
let sync = self.driver.api.synchronize();
let pop = guard.finish();
if copy.is_err() || sync.is_err() || pop.is_err() {
self.poisoned.set(true);
}
if sync.is_err() || pop.is_err() {
std::mem::forget(std::mem::take(tails));
}
combine(combine(copy, sync), pop)
}
/// Enqueues each tail upload and weight copy, stopping at the first failure.
fn device_triplet_enqueue(
&self,
(targets, sources): ([ffi::BufferHandle; 3], [ffi::BufferHandle; 3]),
(tail_handles, tails): (&[Option<ffi::BufferHandle>; 3], &[Vec<u8>; 3]),
raw_bytes: [usize; 3],
) -> Result<()> {
let mut copy = Ok(());
for i in 0..3 {
if let Some(tail) = tail_handles[i] {
copy = self.driver.api.copy_from(tail, &tails[i]);
if copy.is_err() {
break;
}
}
copy = self.driver.api.copy_mmq_weight(targets[i], sources[i], raw_bytes[i]);
if copy.is_err() {
break;
}
}
copy
}
/// Closed owned cold Gate/Up upload; no tail padding, no module loading.
/// The caller still authenticates source, binding and current role separately.
pub fn mmq_weights_owned_gate_up(
&self,
shape: ProjectionSpec,
kind: MmqFormat,
raw: Vec<u8>,
) -> Result<MmqWeights<'_>> {
if self.is_poisoned() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
let l = owned_gate_up_layout(shape, kind, raw.len())?;
check_weight_blocks(&raw, &l)?;
let mut b = self.allocate(l.weight)?;
let upload = b.copy_from_owned(raw);
let b = self.settle_upload(b, upload)?;
Ok(MmqWeights { context: self, format: kind, buffer: Some(b) })
}
/// A failed upload poisons the context and releases the buffer; the upload error stays primary.
fn settle_upload<'a>(&'a self, b: DeviceBuffer<'a>, upload: Result<()>) -> Result<DeviceBuffer<'a>> {
if let Err(error) = upload {
self.poisoned.set(true);
let cleanup = b.release();
if cleanup.is_err() {
self.poisoned.set(true);
}
return combine(Err(error), cleanup);
}
Ok(b)
}
/// One producer-owned padded native/MMQ matrix. No experimental modules are loaded.
pub fn mmq_weights(&self, format: MmqFormat, raw: &[u8]) -> Result<MmqWeights<'_>> {
if self.is_poisoned() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
let l = format.layout(1)?;
if raw.len() != l.raw_weight {
return Err(Error::InvalidProjectionShape);
}
check_weight_blocks(raw, &l)?;
let mut padded = bytes(l.weight)?;
padded[..raw.len()].copy_from_slice(raw);
let mut b = self.allocate(l.weight)?;
let upload = b.copy_from(&padded);
let b = self.settle_upload(b, upload)?;
Ok(MmqWeights { context: self, format, buffer: Some(b) })
}
}
/// The weights of a source may not carry a NaN/Inf scale in any block header.
fn check_weight_blocks(raw: &[u8], l: &Layout) -> Result<()> {
if raw.chunks_exact(l.block_bytes).any(|block| u16::from_le_bytes([block[0], block[1]]) & 0x7c00 == 0x7c00) {
return Err(Error::InvalidQ8Activation);
}
Ok(())
}
fn buffer_handles(buffers: &[Option<DeviceBuffer<'_>>; 3]) -> Result<[ffi::BufferHandle; 3]> {
Ok([
buffers[0].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?,
buffers[1].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?,
buffers[2].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?,
])
}
/// The padded targets need a 4-byte aligned extent and may overlap neither the sources nor each other.
fn check_padded_targets(
(sources, targets): ([ffi::BufferHandle; 3], [ffi::BufferHandle; 3]),
raw_bytes: [usize; 3],
layouts: &[Layout; 3],
) -> Result<()> {
let all = [
(sources[0], raw_bytes[0]),
(sources[1], raw_bytes[1]),
(sources[2], raw_bytes[2]),
(targets[0], layouts[0].weight),
(targets[1], layouts[1].weight),
(targets[2], layouts[2].weight),
];
for i in 3..6 {
all[i].0.validate_projection_extent(all[i].1, 4)?;
for j in 0..i {
if all[i].0.overlaps(all[i].1, all[j].0, all[j].1) {
return Err(Error::OutputAliasesInput);
}
}
}
Ok(())
}
/// The layout of an owned Gate/Up upload: Iq3Xxs or Iq2S, exactly the closed 640x2560 shape, no tail padding.
fn owned_gate_up_layout(shape: ProjectionSpec, kind: MmqFormat, raw_len: usize) -> Result<Layout> {
let format = match kind {
MmqFormat::Iq3XxsGateUp => RoutedFormat::IQ3_XXS,
MmqFormat::Iq2SGateUp => RoutedFormat::IQ2_S,
_ => return Err(Error::UnsupportedProjection),
};
let l = kind.layout(1)?;
if shape != (ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 640, columns: 2560 })
|| l.weight != l.raw_weight
|| raw_len != l.raw_weight
{
return Err(Error::InvalidProjectionShape);
}
Ok(l)
}