Keep routed MoE Down products on CUDA through combine

This commit is contained in:
Pavlo Ratushnyi
2026-10-10 09:18:19 +02:00
parent 7c6cc64751
commit 69fc520e3e
8 changed files with 1256 additions and 1 deletions
+35
View File
@@ -54,6 +54,22 @@ impl BufferHandle {
self.0 < other.0.saturating_add(other_bytes as u64)
&& other.0 < self.0.saturating_add(bytes as u64)
}
// The only admitted interior address is one of ten fixed MoE Down slots.
pub(crate) fn moe_down_slot(self, slot: u32) -> Result<Self> {
if slot >= 10 {
return Err(Error::InvalidQwenShape);
}
self.validate_projection_extent(102_400, 4)?;
let offset = u64::from(slot)
.checked_mul(10_240)
.ok_or(Error::InvalidQwenShape)?;
let address = self.0.checked_add(offset).ok_or(Error::InvalidQwenShape)?;
let end = address.checked_add(10_240).ok_or(Error::InvalidQwenShape)?;
if end > self.0.checked_add(102_400).ok_or(Error::InvalidQwenShape)? {
return Err(Error::InvalidQwenShape);
}
Ok(Self(address))
}
#[cfg(test)]
pub(crate) fn synthetic(address: u64) -> Self {
Self(address)
@@ -503,6 +519,7 @@ mod enabled {
concat!(include_str!("q8_1_quantize.ptx"), "\0").as_bytes();
static Q6_K_PTX: &[u8] = concat!(include_str!("q6_k_q8_1.ptx"), "\0").as_bytes();
type MemcpyDtoHV2 = unsafe extern "C" fn(*mut c_void, CuDevicePtr, usize) -> CuResult;
type MemcpyDtoDV2 = unsafe extern "C" fn(CuDevicePtr, CuDevicePtr, usize) -> CuResult;
struct Library(*mut c_void);
impl Drop for Library {
@@ -530,6 +547,7 @@ mod enabled {
free: MemFreeV2,
copy_from: MemcpyHtoDV2,
copy_to: MemcpyDtoHV2,
copy_moe_down: MemcpyDtoDV2,
load_module: ModuleLoadData,
get_function: ModuleGetFunction,
unload_module: ModuleUnload,
@@ -643,6 +661,7 @@ mod enabled {
free: symbol!(library, c"cuMemFree_v2", MemFreeV2),
copy_from: symbol!(library, c"cuMemcpyHtoD_v2", MemcpyHtoDV2),
copy_to: symbol!(library, c"cuMemcpyDtoH_v2", MemcpyDtoHV2),
copy_moe_down: symbol!(library, c"cuMemcpyDtoD_v2", MemcpyDtoDV2),
load_module: symbol!(library, c"cuModuleLoadData", ModuleLoadData),
get_function: symbol!(library, c"cuModuleGetFunction", ModuleGetFunction),
unload_module: symbol!(library, c"cuModuleUnload", ModuleUnload),
@@ -968,6 +987,19 @@ mod enabled {
(self.copy_to)(owned.as_mut_ptr().cast(), buffer.0, owned.len())
})
}
pub(crate) fn copy_moe_down(
&self,
destination: BufferHandle,
source: BufferHandle,
) -> Result<()> {
// SAFETY: facade admits exact same-context disjoint owned extents,
// a checked ten-slot destination address and exactly10240 bytes.
// Both allocations remain borrowed until sync and context restore;
// ambiguous completion poisons their context before any later free.
check("cuMemcpyDtoD_v2", unsafe {
(self.copy_moe_down)(destination.0, source.0, 10_240)
})
}
}
}
#[cfg(all(
@@ -1126,6 +1158,9 @@ impl Api {
pub(crate) fn copy_to(&self, _: BufferHandle, _: &mut [u8]) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn copy_moe_down(&self, _: BufferHandle, _: BufferHandle) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
}
#[cfg(test)]
+47
View File
@@ -768,6 +768,49 @@ impl Context<'_> {
}
combine(sync, guard.finish())
}
/// Copy one complete2560-F32 MoE Down result into its fixed ordered slot.
/// This performs no arithmetic or finite admission; callers retain the
/// actual producer's finite proof. Successful return attests completed copy.
pub fn pack_moe_down_f32(
&self,
source: &DeviceBuffer<'_>,
destination: &mut DeviceBuffer<'_>,
slot: u32,
) -> Result<()> {
if self.poisoned.get() {
return Err(Error::ContextPoisoned);
}
if !std::ptr::eq(self, source.context) || !std::ptr::eq(self, destination.context) {
return Err(Error::ContextMismatch);
}
if source.bytes != 10_240 || destination.bytes != 102_400 || slot >= 10 {
return Err(Error::InvalidQwenShape);
}
let source = source.handle.ok_or(Error::ContextPoisoned)?;
let destination = destination.handle.ok_or(Error::ContextPoisoned)?;
source.validate_projection_extent(10_240, 4)?;
destination.validate_projection_extent(102_400, 4)?;
if source.overlaps(10_240, destination, 102_400) {
return Err(Error::OutputAliasesInput);
}
let target = destination.moe_down_slot(slot)?;
let guard = match self.enter() {
Ok(guard) => guard,
Err(error) => {
self.poisoned.set(true);
return Err(error);
}
};
let copy = self.driver.api.copy_moe_down(target, source);
// A failed copy can report earlier work. Always attempt synchronization
// and restore, preserving primary copy→sync→restore error precedence.
let sync = self.driver.api.synchronize();
let restore = guard.finish();
if copy.is_err() || sync.is_err() || restore.is_err() {
self.poisoned.set(true);
}
combine(combine(copy, sync), restore)
}
/// Add two exact f32 byte vectors with the fixed trusted kernel. The
/// output is usable as a computed vector only after a successful return.
pub fn vector_add_f32(
@@ -1879,6 +1922,10 @@ impl Drop for DeviceBuffer<'_> {
}
}
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
#[path = "moe_down_pack_gpu.rs"]
mod moe_down_pack_gpu_tests;
#[cfg(test)]
mod tests {
use super::*;
+151
View File
@@ -0,0 +1,151 @@
//! New fixed ten-slot D2D admission and exact original-upload byte oracle.
use super::*;
const SOURCE: usize = 10_240;
const DEST: usize = 102_400;
fn upload<'ctx>(ctx: &'ctx Context<'ctx>, bytes: &[u8]) -> DeviceBuffer<'ctx> {
let mut b = ctx.allocate(bytes.len()).unwrap();
b.copy_from(bytes).unwrap();
b
}
fn read(b: &DeviceBuffer<'_>) -> Vec<u8> {
let mut bytes = vec![0; b.len()];
b.copy_to(&mut bytes).unwrap();
bytes
}
fn words(slot: usize, zero: bool) -> Vec<u8> {
(0..2560)
.flat_map(|i| {
let value = if zero {
if (slot + i) % 2 == 0 { -0.0f32 } else { 0. }
} else {
(((slot * 17 + i * 3) % 97) as f32 - 48.) / 64.
};
value.to_le_bytes()
})
.collect()
}
#[test]
#[ignore = "root schedules one new fixed MoE Down D2D packing proof"]
fn fixed_down_pack_matches_original_upload_and_refuses_before_copy() {
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let ctx = device.create_context(1024 * 1024).unwrap();
for zero in [false, true] {
let expected: Vec<u8> = (0..10).flat_map(|slot| words(slot, zero)).collect();
let reference = upload(&ctx, &expected); // Original host concatenation FIRST.
let sentinel = 0xdeadbeefu32.to_le_bytes().repeat(25_600);
let mut actual = upload(&ctx, &sentinel);
let mut source = upload(&ctx, &words(0, zero));
let charge = ctx.allocated_bytes();
let mut staged = sentinel;
for slot in (0..10).rev() {
let bytes = words(slot, zero);
source.copy_from(&bytes).unwrap();
ctx.pack_moe_down_f32(&source, &mut actual, slot as u32)
.unwrap();
staged[slot * SOURCE..(slot + 1) * SOURCE].copy_from_slice(&bytes);
assert_eq!(
read(&actual),
staged,
"fixed slot{slot} must not touch other slots"
);
assert_eq!(read(&source), bytes);
assert_eq!(ctx.allocated_bytes(), charge);
}
assert_eq!(read(&actual), read(&reference));
source.release().unwrap();
actual.release().unwrap();
reference.release().unwrap();
assert_eq!(ctx.allocated_bytes(), 0);
println!("MOE_DOWN_PACK PAIR zero={zero} exact_words=25600");
}
let source = upload(&ctx, &words(0, false));
let sentinel = 0xdeadbeefu32.to_le_bytes().repeat(25_600);
let mut destination = upload(&ctx, &sentinel);
let baseline = ctx.allocated_bytes();
for slot in [10, u32::MAX] {
assert_eq!(
ctx.pack_moe_down_f32(&source, &mut destination, slot),
Err(Error::InvalidQwenShape)
);
assert_eq!(read(&destination), sentinel);
assert_eq!(ctx.allocated_bytes(), baseline);
}
for len in [SOURCE - 4, SOURCE + 4] {
let malformed = upload(&ctx, &vec![0x27; len]);
let charge = ctx.allocated_bytes();
assert_eq!(
ctx.pack_moe_down_f32(&malformed, &mut destination, 0),
Err(Error::InvalidQwenShape)
);
assert_eq!(read(&destination), sentinel);
assert_eq!(ctx.allocated_bytes(), charge);
malformed.release().unwrap();
}
for len in [DEST - 4, DEST + 4] {
let bytes = vec![0x39; len];
let mut malformed = upload(&ctx, &bytes);
let charge = ctx.allocated_bytes();
assert_eq!(
ctx.pack_moe_down_f32(&source, &mut malformed, 0),
Err(Error::InvalidQwenShape)
);
assert_eq!(read(&malformed), bytes);
assert_eq!(ctx.allocated_bytes(), charge);
malformed.release().unwrap();
}
let foreign = device.create_context(1024 * 1024).unwrap();
let foreign_source = upload(&foreign, &words(0, false));
let mut foreign_destination = upload(&foreign, &sentinel);
assert_eq!(
ctx.pack_moe_down_f32(&foreign_source, &mut destination, 0),
Err(Error::ContextMismatch)
);
assert_eq!(
ctx.pack_moe_down_f32(&source, &mut foreign_destination, 0),
Err(Error::ContextMismatch)
);
assert_eq!(
foreign.pack_moe_down_f32(&source, &mut destination, 0),
Err(Error::ContextMismatch)
);
assert_eq!(read(&destination), sentinel);
assert_eq!(read(&foreign_destination), sentinel);
assert_eq!(read(&source), words(0, false));
assert_eq!(ctx.allocated_bytes(), baseline);
foreign_destination.release().unwrap();
foreign_source.release().unwrap();
source.release().unwrap();
destination.release().unwrap();
assert_eq!(ctx.allocated_bytes(), 0);
assert_eq!(foreign.allocated_bytes(), 0);
ctx.close().unwrap();
foreign.close().unwrap();
// Direct existing poison-policy flag only: no fabricated CUDA failure and
// never clear it. Raw allocations remain owned by context destruction when
// the existing poisoned-context buffer-release guard refuses native frees.
let mut poisoned = device.create_context(1024 * 1024).unwrap();
let source = upload(&poisoned, &words(0, false));
let mut destination = upload(&poisoned, &sentinel);
poisoned.poisoned.set(true);
assert_eq!(
poisoned.pack_moe_down_f32(&source, &mut destination, 0),
Err(Error::ContextPoisoned)
);
assert_eq!(
poisoned.pack_moe_down_f32(&source, &mut destination, 10),
Err(Error::ContextPoisoned)
);
assert_eq!(poisoned.allocated_bytes(), SOURCE + DEST);
assert_eq!(source.release(), Err(Error::ContextPoisoned));
assert_eq!(destination.release(), Err(Error::ContextPoisoned));
assert!(poisoned.poisoned.get());
poisoned.destroy().unwrap();
assert!(poisoned.poisoned.get());
assert_eq!(poisoned.allocated_bytes(), 0);
poisoned.close().unwrap();
println!(
"MOE_DOWN_PACK COMPLETE finite_cases=2 exact_words=51200 pre_copy_refusals=11 context_destroy_cleanup=1 allocated=0"
);
}
+7
View File
@@ -156,6 +156,13 @@ CUresult cuMemcpyDtoH_v2(void *host,CUdeviceptr ptr,size_t bytes) {
}
#endif
/* Load-only ABI compatibility. This synthetic harness intentionally refuses
the new fixed MoE pack; its numerical proof requires the real GPU driver. */
CUresult cuMemcpyDtoD_v2(CUdeviceptr destination,CUdeviceptr source,size_t bytes) {
(void)destination;(void)source;(void)bytes;
return 1;
}
/* Independent fixed vector ABI fixture. Arithmetic here is a CPU reference;
it neither interprets nor executes PTX. */
static int exact_image(const char *ptx,int matvec) {
@@ -0,0 +1,320 @@
//! Step-local actual Down outputs; no host/device pair constructor.
use super::{Error, K, N, Result, download_f32, driver_error, validate_values};
use leleka_cuda_driver::{Context, DeviceBuffer};
use std::{cell::Cell, rc::Rc};
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum DownSelection {
Routed(usize),
Shared,
}
pub(super) struct DownScope<'ctx> {
context: &'ctx Context<'ctx>,
epoch: Rc<()>,
failed: Rc<Cell<bool>>,
}
impl<'ctx> DownScope<'ctx> {
pub(super) fn new(context: &'ctx Context<'ctx>, failed: Rc<Cell<bool>>) -> Self {
Self {
context,
epoch: Rc::new(()),
failed,
}
}
fn check(&self) -> Result<()> {
if self.failed.get() {
Err(Error::CudaExecution)
} else {
Ok(())
}
}
pub(super) fn record<T>(&self, result: &Result<T>) {
if matches!(result, Err(Error::CudaExecution)) {
self.failed.set(true);
}
}
pub(super) fn allocate(&self, bytes: usize) -> Result<TransportBuffer<'ctx>> {
self.check()?;
let result = self.context.allocate(bytes).map_err(driver_error);
self.record(&result);
Ok(TransportBuffer {
buffer: Some(result?),
failed: Rc::clone(&self.failed),
})
}
pub(super) fn upload(&self, values: &[f32]) -> Result<TransportBuffer<'ctx>> {
validate_values(values, values.len())?;
let mut bytes = Vec::new();
bytes
.try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?)
.map_err(|_| Error::InputAllocation)?;
for value in values {
bytes.extend_from_slice(&value.to_le_bytes());
}
let mut output = self.allocate(bytes.len())?;
let result = output.buffer_mut()?.copy_from(&bytes).map_err(driver_error);
self.record(&result);
if let Err(primary) = result {
let _ = output.close();
return Err(primary);
}
Ok(output)
}
/// The producer writes the allocation we create; only its own readback
/// admits the next consumer. The callback is private to this stage.
pub(super) fn project(
&self,
selection: DownSelection,
project: impl FnOnce(&mut DeviceBuffer<'ctx>) -> Result<()>,
) -> Result<RetainedDown<'ctx>> {
self.check()?;
if matches!(selection, DownSelection::Routed(slot) if slot >= K) {
return Err(Error::InvalidExpert);
}
let mut output = self.allocate(N * 4)?;
let result = project(output.buffer_mut()?).and_then(|()| download_f32(output.buffer()?, N));
self.record(&result);
let values = match result {
Ok(values) => values,
Err(primary) => {
let _ = output.close();
return Err(primary);
}
};
Ok(RetainedDown {
output,
values,
epoch: Rc::clone(&self.epoch),
context: self.context,
selection,
})
}
pub(super) fn shared_scalar(
&self,
activation: &DeviceBuffer<'_>,
weights: &DeviceBuffer<'_>,
) -> Result<RetainedScalar<'ctx>> {
let mut output = self.allocate(4)?;
let result = self
.context
.moe_shared_scalar_f32_bf16(activation, weights, output.buffer_mut()?)
.map_err(driver_error)
.and_then(|()| download_f32(output.buffer()?, 1));
self.record(&result);
let values = match result {
Ok(values) => values,
Err(primary) => {
let _ = output.close();
return Err(primary);
}
};
if !(0.0..=1.0).contains(&values[0]) {
let _ = output.close();
return Err(Error::NonFinite);
}
Ok(RetainedScalar {
output,
epoch: Rc::clone(&self.epoch),
context: self.context,
})
}
}
pub(super) struct RetainedScalar<'ctx> {
output: TransportBuffer<'ctx>,
epoch: Rc<()>,
context: &'ctx Context<'ctx>,
}
impl RetainedScalar<'_> {
pub(super) fn close(self) -> Result<()> {
self.output.close()
}
}
pub(super) struct TransportBuffer<'ctx> {
buffer: Option<DeviceBuffer<'ctx>>,
failed: Rc<Cell<bool>>,
}
impl<'ctx> TransportBuffer<'ctx> {
pub(super) fn buffer(&self) -> Result<&DeviceBuffer<'ctx>> {
if self.failed.get() {
return Err(Error::CudaExecution);
}
self.buffer.as_ref().ok_or(Error::IdentityMismatch)
}
pub(super) fn buffer_mut(&mut self) -> Result<&mut DeviceBuffer<'ctx>> {
if self.failed.get() {
return Err(Error::CudaExecution);
}
self.buffer.as_mut().ok_or(Error::IdentityMismatch)
}
pub(super) fn close(mut self) -> Result<()> {
let primary = self.failed.get().then_some(Error::CudaExecution);
let release = self.release();
primary.map_or(release, Err)
}
fn release(&mut self) -> Result<()> {
let result = self
.buffer
.take()
.map_or(Ok(()), |buffer| buffer.release().map_err(driver_error));
if result.is_err() {
self.failed.set(true);
}
result
}
}
impl Drop for TransportBuffer<'_> {
fn drop(&mut self) {
let _ = self.release();
}
}
pub(super) struct RetainedDown<'ctx> {
output: TransportBuffer<'ctx>,
values: Box<[f32]>,
epoch: Rc<()>,
context: &'ctx Context<'ctx>,
selection: DownSelection,
}
impl<'ctx> RetainedDown<'ctx> {
pub(super) fn values(&self) -> &[f32] {
&self.values
}
fn validate(&self, scope: &DownScope<'_>, selection: DownSelection) -> Result<()> {
scope.check()?;
if !Rc::ptr_eq(&self.epoch, &scope.epoch)
|| !std::ptr::eq(self.context, scope.context)
|| self.selection != selection
{
return Err(Error::IdentityMismatch);
}
validate_values(&self.values, N)
}
pub(super) fn close(self) -> Result<()> {
self.output.close()
}
pub(super) fn scale(
self,
scope: &DownScope<'ctx>,
scalar: &RetainedScalar<'_>,
) -> Result<ScaledDown<'ctx>> {
self.validate(scope, DownSelection::Shared)?;
if !Rc::ptr_eq(&scalar.epoch, &scope.epoch) || !std::ptr::eq(scalar.context, scope.context)
{
return Err(Error::IdentityMismatch);
}
let mut output = scope.allocate(N * 4)?;
let result = scope
.context
.moe_shared_scale_f32(
self.output.buffer()?,
scalar.output.buffer()?,
output.buffer_mut()?,
)
.map_err(driver_error)
.and_then(|()| download_f32(output.buffer()?, N));
scope.record(&result);
let cleanup = self.close();
if let Err(primary) = result {
let _ = output.close();
return Err(primary);
}
if let Err(primary) = cleanup {
let _ = output.close();
return Err(primary);
}
Ok(ScaledDown {
output,
epoch: Rc::clone(&scope.epoch),
context: scope.context,
})
}
}
pub(super) struct ScaledDown<'ctx> {
output: TransportBuffer<'ctx>,
epoch: Rc<()>,
context: &'ctx Context<'ctx>,
}
impl ScaledDown<'_> {
pub(super) fn close(self) -> Result<()> {
self.output.close()
}
}
pub(super) struct PackedDown<'ctx> {
output: TransportBuffer<'ctx>,
epoch: Rc<()>,
context: &'ctx Context<'ctx>,
next: usize,
}
impl<'ctx> PackedDown<'ctx> {
pub(super) fn new(scope: &DownScope<'ctx>) -> Result<Self> {
Ok(Self {
output: scope.allocate(K * N * 4)?,
epoch: Rc::clone(&scope.epoch),
context: scope.context,
next: 0,
})
}
pub(super) fn pack(&mut self, scope: &DownScope<'_>, down: RetainedDown<'_>) -> Result<()> {
let result = (|| {
if !Rc::ptr_eq(&self.epoch, &scope.epoch)
|| !std::ptr::eq(self.context, scope.context)
|| self.next >= K
{
return Err(Error::IdentityMismatch);
}
down.validate(scope, DownSelection::Routed(self.next))?;
scope
.context
.pack_moe_down_f32(
down.output.buffer()?,
self.output.buffer_mut()?,
self.next as u32,
)
.map_err(driver_error)
})();
scope.record(&result);
let cleanup = down.close();
result?;
cleanup?;
self.next += 1;
Ok(())
}
pub(super) fn combine(
&self,
scope: &DownScope<'ctx>,
weights: &DeviceBuffer<'_>,
scaled: &ScaledDown<'_>,
) -> Result<Box<[f32]>> {
scope.check()?;
if self.next != K
|| !Rc::ptr_eq(&self.epoch, &scope.epoch)
|| !Rc::ptr_eq(&scaled.epoch, &scope.epoch)
|| !std::ptr::eq(self.context, scope.context)
|| !std::ptr::eq(scaled.context, scope.context)
{
return Err(Error::IdentityMismatch);
}
let mut output = scope.allocate(N * 4)?;
let result = scope
.context
.moe_combine_f64(
self.output.buffer()?,
weights,
scaled.output.buffer()?,
output.buffer_mut()?,
)
.map_err(driver_error)
.and_then(|()| download_f32(output.buffer()?, N));
scope.record(&result);
let cleanup = output.close();
let values = result?;
cleanup?;
Ok(values)
}
pub(super) fn close(self) -> Result<()> {
self.output.close()
}
}
#[cfg(test)]
#[path = "moe_down_reuse_gpu.rs"]
mod moe_down_reuse_gpu;
@@ -0,0 +1,407 @@
//! New genuine Down/closed scalar/packed DOUBLE combine transport proof.
#![cfg(all(target_os = "linux", target_arch = "x86_64"))]
use super::super::{upload_bytes, upload_f32};
use super::*;
use leleka_cuda_driver::{DenseFormat, Driver, ProjectionKind, ProjectionSpec};
fn exact(a: &[f32], b: &[f32]) {
assert_eq!(a.len(), b.len());
for (i, (a, b)) in a.iter().zip(b).enumerate() {
assert!(a.is_finite() && b.is_finite());
assert_eq!(a.to_bits(), b.to_bits(), "word{i}");
}
}
fn down_weights(seed: usize) -> Vec<u8> {
let mut bytes = Vec::with_capacity(1_740_800);
for row in 0..N {
for block in 0..20 {
bytes.extend_from_slice(&0x1c00u16.to_le_bytes());
for lane in 0..32 {
bytes.push((((row + 3 * (block * 32 + lane) + seed) % 11) as i8 - 5) as u8);
}
}
}
assert_eq!(bytes.len(), 1_740_800);
bytes
}
fn scalar_weights() -> Vec<u8> {
(0..N)
.flat_map(|i| {
let v = ((i % 7) as f32 - 3.) / 1024.;
((v.to_bits() >> 16) as u16).to_le_bytes()
})
.collect()
}
fn project(
ctx: &Context<'_>,
weights: &DeviceBuffer<'_>,
input: &DeviceBuffer<'_>,
out: &mut DeviceBuffer<'_>,
) -> Result<()> {
ctx.project_q8_1(
weights,
input,
out,
ProjectionSpec {
rows: N,
columns: 640,
kind: ProjectionKind::Dense(DenseFormat::Q8_0),
},
)
.map_err(driver_error)
}
fn original_down(ctx: &Context<'_>, input: &[f32], seed: usize) -> Box<[f32]> {
let x = upload_f32(ctx, input).unwrap();
let w = upload_bytes(ctx, &down_weights(seed)).unwrap();
let mut y = ctx.allocate(N * 4).unwrap();
project(ctx, &w, &x, &mut y).unwrap();
let result = download_f32(&y, N).unwrap();
y.release().unwrap();
w.release().unwrap();
x.release().unwrap();
result
}
fn retained<'ctx>(
scope: &DownScope<'ctx>,
input: &DeviceBuffer<'_>,
selection: DownSelection,
seed: usize,
) -> RetainedDown<'ctx> {
let weights = upload_bytes(scope.context, &down_weights(seed)).unwrap();
let result = scope
.project(selection, |out| {
project(scope.context, &weights, input, out)
})
.unwrap();
weights.release().unwrap();
result
}
fn refused<T>(result: Result<T>, expected: Error, count: &Cell<usize>) {
assert_eq!(result.err(), Some(expected));
count.set(count.get() + 1);
}
#[test]
#[ignore = "root schedules one new retained Down/shared scalar/pack/DOUBLE combine proof"]
fn retained_down_pack_scale_combine_matches_old_uploads_and_fences_abort() {
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let ctx = device.create_context(144 * 1024 * 1024).unwrap();
let failed = Rc::new(Cell::new(false));
let refusals = Cell::new(0);
let route: [f32; K] = std::array::from_fn(|i| if i < 6 { 0.125 } else { 0.0625 });
for zero in [false, true] {
let hidden: Vec<f32> = (0..640)
.map(|i| {
if zero {
if i % 2 == 0 { -0. } else { 0. }
} else {
((i % 17) as f32 - 8.) / 64.
}
})
.collect();
let input: Vec<f32> = (0..N)
.map(|i| {
if zero {
if i % 2 == 0 { -0. } else { 0. }
} else {
((i % 13) as f32 - 6.) / 128.
}
})
.collect();
let scalar_bytes = scalar_weights();
// Independent genuine old path FIRST, complete host concatenation.
let expected_parts: Vec<f32> = (0..K)
.flat_map(|i| original_down(&ctx, &hidden, i).into_vec())
.collect();
let expected_shared = original_down(&ctx, &hidden, K);
let scalar_input = upload_f32(&ctx, &input).unwrap();
let scalar_matrix = upload_bytes(&ctx, &scalar_bytes).unwrap();
let mut scalar = ctx.allocate(4).unwrap();
ctx.moe_shared_scalar_f32_bf16(&scalar_input, &scalar_matrix, &mut scalar)
.unwrap();
let expected_scalar = download_f32(&scalar, 1).unwrap();
assert!((0.0..=1.0).contains(&expected_scalar[0]));
let old_shared = upload_f32(&ctx, &expected_shared).unwrap();
let mut old_scaled = ctx.allocate(N * 4).unwrap();
ctx.moe_shared_scale_f32(&old_shared, &scalar, &mut old_scaled)
.unwrap();
let expected_scaled = download_f32(&old_scaled, N).unwrap();
let old_parts = upload_f32(&ctx, &expected_parts).unwrap();
let weights = upload_f32(&ctx, &route).unwrap();
let mut old_output = ctx.allocate(N * 4).unwrap();
ctx.moe_combine_f64(&old_parts, &weights, &old_scaled, &mut old_output)
.unwrap();
let expected_out = download_f32(&old_output, N).unwrap();
old_output.release().unwrap();
old_parts.release().unwrap();
old_scaled.release().unwrap();
old_shared.release().unwrap();
scalar.release().unwrap();
let scope = DownScope::new(&ctx, failed.clone());
let mut parts = PackedDown::new(&scope).unwrap();
let x = upload_f32(&ctx, &hidden).unwrap();
for slot in 0..K {
let down = retained(&scope, &x, DownSelection::Routed(slot), slot);
exact(down.values(), &expected_parts[slot * N..(slot + 1) * N]);
parts.pack(&scope, down).unwrap();
assert_eq!(parts.next, slot + 1);
}
exact(
&download_f32(parts.output.buffer().unwrap(), K * N).unwrap(),
&expected_parts,
);
let shared = retained(&scope, &x, DownSelection::Shared, K);
exact(shared.values(), &expected_shared);
let scalar = scope.shared_scalar(&scalar_input, &scalar_matrix).unwrap();
exact(
&download_f32(scalar.output.buffer().unwrap(), 1).unwrap(),
&expected_scalar,
);
let scaled = shared.scale(&scope, &scalar).unwrap();
exact(
&download_f32(scaled.output.buffer().unwrap(), N).unwrap(),
&expected_scaled,
);
exact(
&parts.combine(&scope, &weights, &scaled).unwrap(),
&expected_out,
);
if !zero {
let wrong = DownScope::new(&ctx, failed.clone());
refused(
parts.combine(&wrong, &weights, &scaled),
Error::IdentityMismatch,
&refusals,
);
let malformed = upload_bytes(&ctx, &[0; 4]).unwrap();
let charge = ctx.allocated_bytes();
refused(
parts.combine(&scope, &malformed, &scaled),
Error::InvalidDimension,
&refusals,
);
assert_eq!(ctx.allocated_bytes(), charge);
malformed.release().unwrap();
let mut bad_route = route;
bad_route[K - 1] = f32::NAN;
let bad = upload_bytes(
&ctx,
&bad_route
.iter()
.flat_map(|v| v.to_le_bytes())
.collect::<Vec<_>>(),
)
.unwrap();
let charge = ctx.allocated_bytes();
refused(
parts.combine(&scope, &bad, &scaled),
Error::NonFinite,
&refusals,
);
assert_eq!(ctx.allocated_bytes(), charge);
bad.release().unwrap();
assert!(!failed.get());
}
let mut unchanged = vec![0; hidden.len() * 4];
x.copy_to(&mut unchanged).unwrap();
assert_eq!(
unchanged,
hidden
.iter()
.flat_map(|v| v.to_le_bytes())
.collect::<Vec<_>>()
);
let mut unchanged = vec![0; scalar_bytes.len()];
scalar_matrix.copy_to(&mut unchanged).unwrap();
assert_eq!(unchanged, scalar_bytes);
let mut unchanged = vec![0; input.len() * 4];
scalar_input.copy_to(&mut unchanged).unwrap();
assert_eq!(
unchanged,
input
.iter()
.flat_map(|v| v.to_le_bytes())
.collect::<Vec<_>>()
);
let mut unchanged = vec![0; K * 4];
weights.copy_to(&mut unchanged).unwrap();
assert_eq!(
unchanged,
route
.iter()
.flat_map(|v| v.to_le_bytes())
.collect::<Vec<_>>()
);
x.release().unwrap();
parts.close().unwrap();
scaled.close().unwrap();
scalar.close().unwrap();
weights.release().unwrap();
scalar_matrix.release().unwrap();
scalar_input.release().unwrap();
assert_eq!(ctx.allocated_bytes(), 0);
println!("MOE_DOWN_RETAINED PAIR zero={zero} exact_words=58881 unique_words=33281");
}
let scope = DownScope::new(&ctx, failed.clone());
let rival = DownScope::new(&ctx, failed.clone());
let x = upload_f32(&ctx, &[0.125; 640]).unwrap();
let input = upload_f32(&ctx, &[0.125; N]).unwrap();
let matrix = upload_bytes(&ctx, &scalar_weights()).unwrap();
let scalar = scope.shared_scalar(&input, &matrix).unwrap();
let rival_scalar = rival.shared_scalar(&input, &matrix).unwrap();
let mut parts = PackedDown::new(&scope).unwrap();
let charge = ctx.allocated_bytes();
refused(
parts.pack(&scope, retained(&scope, &x, DownSelection::Routed(1), 1)),
Error::IdentityMismatch,
&refusals,
);
refused(
parts.pack(&scope, retained(&scope, &x, DownSelection::Shared, K)),
Error::IdentityMismatch,
&refusals,
);
refused(
parts.pack(&scope, retained(&rival, &x, DownSelection::Routed(0), 0)),
Error::IdentityMismatch,
&refusals,
);
assert_eq!(parts.next, 0);
assert_eq!(ctx.allocated_bytes(), charge);
parts
.pack(&scope, retained(&scope, &x, DownSelection::Routed(0), 0))
.unwrap();
refused(
parts.pack(&scope, retained(&scope, &x, DownSelection::Routed(0), 0)),
Error::IdentityMismatch,
&refusals,
);
assert_eq!(parts.next, 1);
refused(
retained(&scope, &x, DownSelection::Shared, K).scale(&scope, &rival_scalar),
Error::IdentityMismatch,
&refusals,
);
let scaled = retained(&scope, &x, DownSelection::Shared, K)
.scale(&scope, &scalar)
.unwrap();
let weights = upload_f32(&ctx, &route).unwrap();
refused(
parts.combine(&scope, &weights, &scaled),
Error::IdentityMismatch,
&refusals,
);
let called = Cell::new(false);
refused(
scope.project(DownSelection::Routed(K), |_| {
called.set(true);
unreachable!()
}),
Error::InvalidExpert,
&refusals,
);
assert!(!called.get());
let malformed = upload_bytes(&ctx, &[0; 2]).unwrap();
let charge = ctx.allocated_bytes();
refused(
scope.project(DownSelection::Routed(1), |out| {
project(&ctx, &malformed, &x, out)
}),
Error::InvalidDimension,
&refusals,
);
refused(
scope.shared_scalar(&input, &malformed),
Error::InvalidDimension,
&refusals,
);
assert_eq!(ctx.allocated_bytes(), charge);
malformed.release().unwrap();
let mut bad_down = down_weights(1);
let end = bad_down.len();
bad_down[end - 34..end - 32].copy_from_slice(&0x7c00u16.to_le_bytes());
let bad = upload_bytes(&ctx, &bad_down).unwrap();
let charge = ctx.allocated_bytes();
refused(
scope.project(DownSelection::Routed(1), |out| project(&ctx, &bad, &x, out)),
Error::NonFinite,
&refusals,
);
assert_eq!(ctx.allocated_bytes(), charge);
bad.release().unwrap();
// Actual scalar kernel refuses malformed raw operands and finite F32_MAX
// that rounds to BF16 infinity; DOUBLE-dot overflow is not alleged.
for value in [f32::NAN, f32::INFINITY, f32::MAX] {
let mut raw = vec![0.125; N];
raw[N - 1] = value;
let bad = upload_bytes(
&ctx,
&raw.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>(),
)
.unwrap();
let charge = ctx.allocated_bytes();
refused(
scope.shared_scalar(&bad, &matrix),
Error::NonFinite,
&refusals,
);
assert_eq!(ctx.allocated_bytes(), charge);
bad.release().unwrap();
}
let foreign = device.create_context(144 * 1024 * 1024).unwrap();
let foreign_scope = DownScope::new(&foreign, Rc::new(Cell::new(false)));
let foreign_x = upload_f32(&foreign, &[0.125; 640]).unwrap();
let charge = ctx.allocated_bytes();
refused(
parts.pack(
&scope,
retained(&foreign_scope, &foreign_x, DownSelection::Routed(1), 1),
),
Error::IdentityMismatch,
&refusals,
);
assert_eq!(ctx.allocated_bytes(), charge);
assert_eq!(foreign.allocated_bytes(), 640 * 4);
foreign_x.release().unwrap();
assert_eq!(foreign.allocated_bytes(), 0);
// Partial packed and completed-but-unconsumed products are aborted. No new
// scope can consume their prior epoch; Drop frees genuine outputs once.
drop(parts);
let aborted = retained(&scope, &x, DownSelection::Routed(1), 1);
let charge = ctx.allocated_bytes();
drop(aborted);
assert_eq!(ctx.allocated_bytes(), charge - N * 4);
let mut partial = PackedDown::new(&scope).unwrap();
let pending = retained(&scope, &x, DownSelection::Routed(0), 0);
failed.set(true); // Explicit shared policy only; never clear it.
refused(PackedDown::new(&scope), Error::CudaExecution, &refusals);
refused(scope.upload(&[0.]), Error::CudaExecution, &refusals);
refused(
partial.pack(&scope, pending),
Error::CudaExecution,
&refusals,
);
refused(
partial.combine(&scope, &weights, &scaled),
Error::CudaExecution,
&refusals,
);
assert_eq!(partial.close(), Err(Error::CudaExecution));
assert_eq!(scalar.close(), Err(Error::CudaExecution));
assert_eq!(rival_scalar.close(), Err(Error::CudaExecution));
assert_eq!(scaled.close(), Err(Error::CudaExecution));
weights.release().unwrap();
matrix.release().unwrap();
input.release().unwrap();
x.release().unwrap();
assert!(failed.get());
assert_eq!(ctx.allocated_bytes(), 0);
assert_eq!(refusals.get(), 21);
ctx.synchronize().unwrap();
ctx.close().unwrap();
foreign.close().unwrap();
println!(
"MOE_DOWN_RETAINED COMPLETE finite_cases=2 exact_words=117762 unique_words=66562 refusals=21 abort_cleanup=2 allocated=0"
);
}
@@ -13,6 +13,10 @@ use leleka_cuda_driver::{
Context, DenseFormat, DeviceBuffer, Error as DriverError, ProjectionKind, ProjectionSpec,
Q5KProjectionShape, Q6KProjectionShape, RoutedFormat, RoutedGateUpQ8,
};
use std::{cell::Cell, rc::Rc};
#[path = "moe_down.rs"]
mod moe_down;
use moe_down::{DownScope, DownSelection, PackedDown, RetainedDown, TransportBuffer};
const N: usize = 2560;
const FF: usize = 640;
const K: usize = 10;
@@ -20,7 +24,9 @@ const K: usize = 10;
const TILE: usize = 64;
// Largest complete matrix is shared Down Q8_0 (1740800B). Including the
// original activation, hidden, output and projection scratch/status requires
// at most 1764564B above previously resident allocations; no bank is resident.
// at most 1764564B above previously resident allocations on the legacy path.
// Cached Down packing adds at most 102400B + one 10240B retained Down;
// resident matrices remain separately charged and the 2MiB gate is unchanged.
const DEVICE_PEAK: usize = 2 * 1024 * 1024;
pub(super) struct ExpertReady {
binding: BindingIdentity,
@@ -132,6 +138,11 @@ fn execute_cuda(
mut cache: Option<&mut MoeWeightCache<'_>>,
prepared: Option<&RoutedGateUpQ8<'_>>,
) -> Result<Box<[f32]>> {
if let Some(cache) = cache.as_deref_mut() {
return execute_cuda_cached(
context, binding, weights, activation, route, cache, prepared,
);
}
let mut parts = Vec::new();
parts
.try_reserve_exact(K * N)
@@ -204,6 +215,280 @@ fn execute_cuda(
}
Ok(result)
}
// Provenance cannot be supplied by a downstream caller: one fresh origin is
// created only inside the already validated current execution step.
struct DownOrigin {
binding: BindingIdentity,
identity: TokenLayer,
}
struct ActualDown<'ctx> {
origin: Rc<DownOrigin>,
selection: MoeExpertSelection,
output: RetainedDown<'ctx>,
}
impl<'ctx> ActualDown<'ctx> {
fn take(
self,
origin: &Rc<DownOrigin>,
binding: &ModelBinding,
identity: TokenLayer,
selection: MoeExpertSelection,
) -> Result<RetainedDown<'ctx>> {
if !Rc::ptr_eq(&self.origin, origin)
|| !self.origin.binding.matches(&binding.identity())
|| self.origin.identity != identity
|| self.selection != selection
{
return Err(Error::IdentityMismatch);
}
validate_values(self.output.values(), N)?;
Ok(self.output)
}
}
#[allow(clippy::too_many_arguments)]
fn execute_cuda_cached(
context: &Context<'_>,
binding: &ModelBinding,
weights: &MoeExpertWeights,
activation: &DeviceBuffer<'_>,
route: &RoutedExperts,
cache: &mut MoeWeightCache<'_>,
prepared: Option<&RoutedGateUpQ8<'_>>,
) -> Result<Box<[f32]>> {
cache.validate(binding, context)?;
route.validate_binding(&binding.identity())?;
if !weights.matches(&binding.identity(), route.identity().layer().get()) {
return Err(Error::IdentityMismatch);
}
let origin = Rc::new(DownOrigin {
binding: binding.identity(),
identity: route.identity(),
});
let failed = Rc::new(Cell::new(false));
let scope = DownScope::new(context, Rc::clone(&failed));
let mut parts = None;
let mut shared = None;
let mut scalar = None;
let mut scaled = None;
let mut route_weights = None;
let result = (|| {
// Charge the single destination before any cache miss/eviction, so
// the existing Context-aware room policy accounts for its lifetime.
parts = Some(PackedDown::new(&scope)?);
for slot in 0..K {
let selection = MoeExpertSelection::Routed { slot };
let down = cached_mlp_down(
context, binding, weights, selection, activation, cache, prepared, &scope, &origin,
)?;
parts.as_mut().ok_or(Error::IdentityMismatch)?.pack(
&scope,
down.take(&origin, binding, route.identity(), selection)?,
)?;
}
let selection = MoeExpertSelection::Shared;
shared = Some(
cached_mlp_down(
context, binding, weights, selection, activation, cache, None, &scope, &origin,
)?
.take(&origin, binding, route.identity(), selection)?,
);
let scalar_weights = cache.shared_scalar(binding, weights)?;
scalar = Some(scope.shared_scalar(activation, scalar_weights)?);
scaled = Some(
shared
.take()
.ok_or(Error::IdentityMismatch)?
.scale(&scope, scalar.as_ref().ok_or(Error::IdentityMismatch)?)?,
);
scalar.take().ok_or(Error::IdentityMismatch)?.close()?;
let route_values: [f32; K] = std::array::from_fn(|i| route.weights()[i].get());
route_weights = Some(scope.upload(&route_values)?);
parts.as_ref().ok_or(Error::IdentityMismatch)?.combine(
&scope,
route_weights
.as_ref()
.ok_or(Error::IdentityMismatch)?
.buffer()?,
scaled.as_ref().ok_or(Error::IdentityMismatch)?,
)
})();
scope.record(&result);
// Attempt every partial owner explicitly before selecting a primary.
let shared_close = shared.map_or(Ok(()), |owner| owner.close());
let scalar_close = scalar.map_or(Ok(()), |owner| owner.close());
let weights_close = route_weights.map_or(Ok(()), |owner| owner.close());
let parts_close = parts.map_or(Ok(()), |owner| owner.close());
let scaled_close = scaled.map_or(Ok(()), |owner| owner.close());
// Preserve the primary numeric error while fencing future cache use.
if failed.get() {
cache.note_transport_failure();
}
let values = result?;
shared_close?;
scalar_close?;
weights_close?;
parts_close?;
scaled_close?;
Ok(values)
}
#[allow(clippy::too_many_arguments)]
fn cached_mlp_down<'ctx>(
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
weights: &MoeExpertWeights,
selection: MoeExpertSelection,
activation: &DeviceBuffer<'_>,
cache: &mut MoeWeightCache<'_>,
prepared: Option<&RoutedGateUpQ8<'_>>,
scope: &DownScope<'ctx>,
origin: &Rc<DownOrigin>,
) -> Result<ActualDown<'ctx>> {
if !origin.binding.matches(&binding.identity())
|| !weights.matches(&binding.identity(), origin.identity.layer().get())
{
return Err(Error::IdentityMismatch);
}
let gate = cached_gate_up_scoped(
context,
binding,
weights,
selection,
MoeMatrixRole::Gate,
activation,
cache,
prepared,
scope,
)?;
let up = match cached_gate_up_scoped(
context,
binding,
weights,
selection,
MoeMatrixRole::Up,
activation,
cache,
prepared,
scope,
) {
Ok(up) => up,
Err(primary) => {
let _ = gate.close();
return Err(primary);
}
};
let mut hidden = match scope.allocate(FF * 4) {
Ok(hidden) => hidden,
Err(primary) => {
let _ = gate.close();
let _ = up.close();
return Err(primary);
}
};
let result = (|| {
let swiglu = context
.moe_swiglu_f32(gate.buffer()?, up.buffer()?, hidden.buffer_mut()?)
.map_err(driver_error);
scope.record(&swiglu);
swiglu?;
let readback = download_f32(hidden.buffer()?, FF);
scope.record(&readback);
readback?;
cache.validate(binding, context)?;
let (columns, rows) = weights
.shape(selection, MoeMatrixRole::Down)
.map_err(binding_error)?;
let kind = weights
.kind(selection, MoeMatrixRole::Down)
.map_err(binding_error)?;
if columns != FF || rows != N {
return Err(Error::InvalidDimension);
}
let matrix = cache.matrix(binding, weights, selection, MoeMatrixRole::Down)?;
let numeric_selection = match selection {
MoeExpertSelection::Routed { slot } => DownSelection::Routed(slot),
MoeExpertSelection::Shared => DownSelection::Shared,
};
scope.project(numeric_selection, |output| {
launch_projection(
context,
kind,
matrix,
hidden.buffer()?,
output,
rows,
columns,
)
})
})();
scope.record(&result);
let gate_close = gate.close();
let up_close = up.close();
let hidden_close = hidden.close();
let output = result?;
gate_close?;
up_close?;
hidden_close?;
Ok(ActualDown {
origin: Rc::clone(origin),
selection,
output,
})
}
#[allow(clippy::too_many_arguments)]
fn cached_gate_up_scoped<'ctx>(
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
weights: &MoeExpertWeights,
selection: MoeExpertSelection,
role: MoeMatrixRole,
activation: &DeviceBuffer<'_>,
cache: &mut MoeWeightCache<'_>,
prepared: Option<&RoutedGateUpQ8<'_>>,
scope: &DownScope<'ctx>,
) -> Result<TransportBuffer<'ctx>> {
let (columns, rows) = weights.shape(selection, role).map_err(binding_error)?;
let kind = weights.kind(selection, role).map_err(binding_error)?;
if !matches!(role, MoeMatrixRole::Gate | MoeMatrixRole::Up) || rows != FF || columns != N {
return Err(Error::InvalidDimension);
}
cache.validate(binding, context)?;
let matrix = cache.matrix(binding, weights, selection, role)?;
let mut output = scope.allocate(FF * 4)?;
let result = (|| {
if let Some(prepared) = prepared {
if !matches!(selection, MoeExpertSelection::Routed { .. }) {
return Err(Error::InvalidDimension);
}
let format = match kind {
MoeMatrixKind::Iq3Xxs => RoutedFormat::IQ3_XXS,
MoeMatrixKind::Iq3S => RoutedFormat::IQ3_S,
MoeMatrixKind::Iq2S => RoutedFormat::IQ2_S,
MoeMatrixKind::RoutedIq4Xs => RoutedFormat::IQ4_XS,
_ => return Err(Error::Unsupported(Stage::MoeExpert)),
};
context
.project_routed_gate_up_prepared(matrix, prepared, output.buffer_mut()?, format)
.map_err(driver_error)?;
} else {
launch_projection(
context,
kind,
matrix,
activation,
output.buffer_mut()?,
rows,
columns,
)?;
}
download_f32(output.buffer()?, FF).map(|_| ())
})();
scope.record(&result);
if let Err(primary) = result {
let _ = output.close();
return Err(primary);
}
Ok(output)
}
fn expert_mlp(
context: &Context<'_>,
binding: &ModelBinding,
@@ -62,6 +62,9 @@ pub(crate) struct MoeWeightCache<'ctx> {
mtp_hits: Cell<u64>,
}
impl<'ctx> MoeWeightCache<'ctx> {
pub(super) fn note_transport_failure(&mut self) {
self.failed = true;
}
pub(crate) fn new(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result<Self> {
let mut cache = Self {
context,