diff --git a/crates/cuda-driver/src/mmq/impl_context.rs b/crates/cuda-driver/src/mmq/impl_context.rs index 352da153..685ec491 100644 --- a/crates/cuda-driver/src/mmq/impl_context.rs +++ b/crates/cuda-driver/src/mmq/impl_context.rs @@ -7,6 +7,36 @@ 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 mut buffers: [Option>; 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)), + } + } + 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)); + } + let [Some(gate), Some(up), Some(down)] = buffers else { + unreachable!("all triplet allocations completed before upload") + }; + Ok([ + 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) }, + ]) + } + + /// 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]> { if self.is_poisoned() || self.handle.is_none() { return Err(Error::ContextPoisoned); } @@ -33,55 +63,34 @@ impl Context<'_> { if self.allocated.get().checked_add(charge).is_none_or(|n| n > self.budget) { return Err(Error::BudgetExceeded); } - 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 mut buffers: [Option>; 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(layouts) + } + + /// Copies the three padded staging images into their device buffers under one confirmed fence. + fn triplet_upload(&self, buffers: &[Option>; 3], staging: &mut [Vec; 3]) -> Result<()> { + let handles = [ + 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)?, + ]; + 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; } } - let operation = (|| { - let handles = [ - 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)?, - ]; - let guard = self.enter()?; - let mut copy = Ok(()); - for (handle, padded) in handles.into_iter().zip(&staging) { - 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(&mut staging)); - } - combine(combine(copy, sync), restored) - })(); - 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)); + // 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)); } - let [Some(gate), Some(up), Some(down)] = buffers else { - unreachable!("all triplet allocations completed before upload") - }; - Ok([ - 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) }, - ]) + combine(combine(copy, sync), restored) } /// Byte transport from three actual immutable raw GPU owners into three @@ -92,6 +101,41 @@ impl Context<'_> { 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 mut buffers: [Option>; 3] = std::array::from_fn(|_| None); + for i in 0..3 { + match self.allocate(layouts[i].weight) { + Ok(buffer) => buffers[i] = Some(buffer), + Err(primary) => return combine(Err(primary), release_triplet(self, buffers)), + } + } + 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)); + } + let [Some(gate), Some(up), Some(down)] = buffers else { + unreachable!("all padded triplet allocations complete before any copy") + }; + Ok([ + 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) }, + ]) + } + + /// 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])> { if self.is_poisoned() || self.handle.is_none() { return Err(Error::ContextPoisoned); } @@ -114,6 +158,20 @@ impl Context<'_> { raw[1].handle.ok_or(Error::ContextPoisoned)?, raw[2].handle.ok_or(Error::ContextPoisoned)?, ]; + let charge = self.device_triplet_charge(formats, raw, (&layouts, &sources))?; + if self.allocated.get().checked_add(charge).is_none_or(|n| n > self.budget) { + return Err(Error::BudgetExceeded); + } + 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 { let mut charge = 0usize; for i in 0..3 { if !std::ptr::eq(self, raw[i].context) { @@ -131,87 +189,78 @@ impl Context<'_> { } charge = charge.checked_add(layouts[i].weight).ok_or(Error::BudgetExceeded)?; } - if self.allocated.get().checked_add(charge).is_none_or(|n| n > self.budget) { - return Err(Error::BudgetExceeded); - } - // 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)?, + 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>; 3], + tails: &mut [Vec; 3], + (layouts, raw): (&[Layout; 3], &[&DeviceBuffer<'_>; 3]), + sources: [ffi::BufferHandle; 3], + ) -> Result<()> { + let targets = [ + 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)?, ]; - let mut buffers: [Option>; 3] = std::array::from_fn(|_| None); - for i in 0..3 { - match self.allocate(layouts[i].weight) { - Ok(buffer) => buffers[i] = Some(buffer), - Err(primary) => return combine(Err(primary), release_triplet(self, buffers)), + let all = [ + (sources[0], raw[0].bytes), + (sources[1], raw[1].bytes), + (sources[2], raw[2].bytes), + (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); + } } } - let operation = (|| { - let targets = [ - 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)?, - ]; - let all = [ - (sources[0], raw[0].bytes), - (sources[1], raw[1].bytes), - (sources[2], raw[2].bytes), - (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); - } - } + 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())?); } - 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())?); - } - } - let guard = self.enter()?; - 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[i].bytes); + } + self.device_triplet_copy((targets, sources), (&tail_handles, tails), [raw[0].bytes, raw[1].bytes, raw[2].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; 3], &mut [Vec; 3]), + raw_bytes: [usize; 3], + ) -> Result<()> { + let guard = self.enter()?; + 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; } } - let sync = self.driver.api.synchronize(); - let pop = guard.finish(); - if copy.is_err() || sync.is_err() || pop.is_err() { - self.poisoned.set(true); + copy = self.driver.api.copy_mmq_weight(targets[i], sources[i], raw_bytes[i]); + if copy.is_err() { + break; } - if sync.is_err() || pop.is_err() { - std::mem::forget(std::mem::take(&mut tails)); - } - combine(combine(copy, sync), pop) - })(); - if let Err(primary) = operation { - return combine(Err(primary), release_triplet(self, buffers)); } - let [Some(gate), Some(up), Some(down)] = buffers else { - unreachable!("all padded triplet allocations complete before any copy") - }; - Ok([ - 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) }, - ]) + 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) } /// Closed owned cold Gate/Up upload; no tail padding, no module loading.