Files
leleka/crates/cuda-driver/src/kar_decode_levels_gpu.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 7e24f41e34 feat(runtime): KAR routed-expert weight source wired into Load and the MoE stage
KarExpertSource (pinned base + optional overlay, levels 2..=5) verifies whole
archives on the retained descriptor, validates the 48-layer expert map at load,
stages exact ranges and runs one-drain device expert FFNs; ModelBinding gains a
consuming with_kar_expert_source builder, MoeExpertStage routes experts through
it (shared expert/combine unchanged, MMQ cache refused), and NativeBackendConfig
gets kar_expert_source with identity-mixed mode digest and a Load-time probe.
The pure selection, stager, expert map and CPU reference move to model-format
so they run on macOS; the CUDA program gains a SwiGLU entry and a per-context
cached module. Linux-target type-checked only; nvcc/GPU unverified, PTX unpinned.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 14:55:34 +02:00

524 lines
20 KiB
Rust

//! Closed CUDA program for KAR NESTED level decode (levels 2..=5), the plain
//! F32 row multiply that follows it, and a SwiGLU for routed-expert FFNs.
//! Linux 64-bit + `cuda-driver` only.
//!
//! Contract, in the style of the neighbouring closed programs:
//! - the PTX is a compiled-in asset that must match a Root-frozen pin; with the
//! shipped zero pin the first use fails closed before any driver call;
//! - the module is loaded once per context and cached like every other fixed
//! kernel (`Context::close` unloads it);
//! - callers pass only admitted buffers and a validated geometry; entry names,
//! block size and argument layout are fixed constants;
//! - every attempted launch sequence is drained with exactly ONE
//! `cuCtxSynchronize`; an uncertain completion poisons the context and leaks
//! the raw-owned argument tables (never freed while the device may read them);
//! - device status bits (bad argument, non-finite scale/book, non-finite
//! product) and a host finite scan both gate every returned value.
//!
//! STATUS: compiled only by `cargo check --target x86_64-unknown-linux-gnu`.
//! No PTX exists yet and no GPU run has happened; see
//! `docs/experiments/2026-10-14-kar-levels-gpu-port.md`.
use crate::{
Context, DeviceBuffer, Error, combine, ffi,
kar_decode_levels::{
BLOCK_THREADS, DecodeGeometry, ENTRY_DECODE, ENTRY_MULTIPLY, ENTRY_SWIGLU, ExpertShape,
KAR_DECODE_LEVELS_PIN, KAR_DECODE_LEVELS_PTX, KarDecodeError, KarLevelsKernels,
MultiplyGeometry, Result, STATUS_BYTES, admit_ptx, check_status,
},
};
use std::rc::Rc;
type DriverResult<T> = std::result::Result<T, Error>;
impl Context<'_> {
/// Admit the PTX against the pin, then load and cache the module once.
/// Refuses (`Unpinned`) without touching the driver while the pin is zero.
pub(crate) fn kar_levels_kernels(&self) -> Result<KarLevelsKernels> {
if let Some(kernels) = self.kar_levels.get() {
return Ok(kernels);
}
admit_ptx(KAR_DECODE_LEVELS_PTX, &KAR_DECODE_LEVELS_PIN)?;
if self.poisoned.get() {
return Err(Error::ContextPoisoned.into());
}
let api = &self.driver.api;
let guard = self.enter()?;
let module = match api.load_kar_levels_module(KAR_DECODE_LEVELS_PTX) {
Ok(module) => module,
Err(error) => return Err(failure(error, guard.finish())),
};
let resolved = api
.kar_levels_function(module, ENTRY_DECODE)
.and_then(|decode| {
api.kar_levels_function(module, ENTRY_MULTIPLY)
.map(|multiply| (decode, multiply))
})
.and_then(|(decode, multiply)| {
api.kar_levels_function(module, ENTRY_SWIGLU)
.map(|swiglu| (decode, multiply, swiglu))
});
match resolved {
Ok((decode, multiply, swiglu)) => {
// Nothing is published until every entry resolves and the
// context restore succeeds (a failed pop poisons the context).
guard.finish()?;
let kernels = KarLevelsKernels {
module,
decode,
multiply,
swiglu,
};
self.kar_levels.set(Some(kernels));
Ok(kernels)
}
Err(error) => {
let cleanup = api.unload(module);
if cleanup.is_err() {
self.poisoned.set(true);
std::mem::forget(Rc::clone(api));
}
let primary =
combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary");
Err(failure(primary, guard.finish()))
}
}
}
}
/// A handle to the context's cached KAR level-decode program.
pub struct KarDecodeLevels<'c> {
context: &'c Context<'c>,
kernels: KarLevelsKernels,
}
struct Admitted {
handle: ffi::BufferHandle,
bytes: usize,
}
type Launch = (ffi::FunctionHandle, [u32; 3], [u32; 3], ffi::KarLevelsArgs);
/// One expert matrix: its decode window, its multiply shape and its staged
/// packet bytes (exactly `geometry.packet_len()`).
pub struct KarMatrix<'a> {
pub geometry: DecodeGeometry,
pub shape: MultiplyGeometry,
pub packet: &'a [u8],
}
impl<'c> KarDecodeLevels<'c> {
/// Load (once) and return the cached program. Fails closed with
/// `Unpinned` while the PTX pin is zero.
pub fn open(context: &'c Context<'c>) -> Result<Self> {
let kernels = context.kar_levels_kernels()?;
Ok(Self { context, kernels })
}
/// The module is owned by the context and unloaded by `Context::close`.
pub fn close(self) -> Result<()> {
Ok(())
}
// ------------------------------------------------------------ admission
fn admit(&self, buffer: &DeviceBuffer<'_>, bytes: usize, exact: bool) -> Result<Admitted> {
if self.context.poisoned.get() {
return Err(Error::ContextPoisoned.into());
}
if !std::ptr::eq(self.context, buffer.context) {
return Err(Error::ContextMismatch.into());
}
let handle = buffer.handle.ok_or(Error::ContextPoisoned)?;
if bytes == 0
|| if exact {
buffer.bytes != bytes
} else {
buffer.bytes < bytes
}
{
return Err(KarDecodeError::Invalid(
"KAR buffer is smaller than (or differs from) the geometry requires",
));
}
handle.validate_projection_extent(buffer.bytes, 16)?;
Ok(Admitted {
handle,
bytes: buffer.bytes,
})
}
fn disjoint(buffers: &[&Admitted]) -> Result<()> {
for (i, a) in buffers.iter().enumerate() {
for b in &buffers[i + 1..] {
if a.handle.overlaps(a.bytes, b.handle, b.bytes) {
return Err(Error::OutputAliasesInput.into());
}
}
}
Ok(())
}
// --------------------------------------------------------------- launch
/// Launch every entry in order and drain with exactly one synchronize.
/// A launch error stops further launches but still drains and restores.
fn launch_all(&self, mut launches: Vec<Launch>) -> Result<()> {
let context = self.context;
if context.poisoned.get() {
return Err(Error::ContextPoisoned.into());
}
let guard = context.enter()?;
let mut launch = Ok(());
for (function, grid, block, arguments) in &mut launches {
launch = context
.driver
.api
.launch_kar_levels(*function, *grid, *block, arguments);
if launch.is_err() {
break;
}
}
// Single drain; on sync/restore uncertainty the context is poisoned and
// the argument tables are forgotten (leaked), not freed.
context
.complete_launch(launch, launches, guard)
.map_err(Into::into)
}
fn arguments(pointers: &[&Admitted], scalars: &[u32]) -> Result<ffi::KarLevelsArgs> {
let mut all: Vec<ffi::KarArgument> = pointers
.iter()
.map(|p| ffi::KarArgument::Pointer(p.handle))
.collect();
all.extend(scalars.iter().copied().map(ffi::KarArgument::Scalar));
Ok(ffi::KarLevelsArgs::new(&all)?)
}
fn decode_launch(
&self,
packet: &Admitted,
output: &Admitted,
status: &Admitted,
g: &DecodeGeometry,
) -> Result<Launch> {
Ok((
self.kernels.decode,
[g.grid(), 1, 1],
[BLOCK_THREADS, 1, 1],
Self::arguments(&[packet, output, status], &g.scalars())?,
))
}
fn multiply_launch(
&self,
weights: &Admitted,
input: &Admitted,
output: &Admitted,
status: &Admitted,
m: &MultiplyGeometry,
) -> Result<Launch> {
Ok((
self.kernels.multiply,
[m.rows, m.tokens, 1],
[BLOCK_THREADS, 1, 1],
Self::arguments(&[weights, input, output, status], &[m.columns, m.rows])?,
))
}
/// Decode the staged packet into `output` (F32). `status` must be a zeroed
/// 4-byte buffer; bits accumulate across launches until the host reads and
/// clears it. Returns after the single drain; the caller must still read
/// the status before trusting `output`.
pub fn decode(
&self,
packet: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
status: &mut DeviceBuffer<'_>,
geometry: &DecodeGeometry,
) -> Result<()> {
geometry.validate()?;
let packet = self.admit(packet, geometry.packet_len(), false)?;
let output = self.admit(output, geometry.output_len(), false)?;
let status = self.admit(status, STATUS_BYTES, true)?;
Self::disjoint(&[&packet, &output, &status])?;
let launch = self.decode_launch(&packet, &output, &status, geometry)?;
self.launch_all(vec![launch])
}
/// Decode a whole-row window into `weights` and multiply it by `input`
/// (`[tokens][columns]`) into `output` (`[tokens][rows]`), both kernels
/// under one drain. `decode.count` must equal `columns * rows`.
#[allow(clippy::too_many_arguments)] // closed ABI operands, not caller-selected geometry
pub fn decode_multiply(
&self,
packet: &DeviceBuffer<'_>,
weights: &mut DeviceBuffer<'_>,
input: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
status: &mut DeviceBuffer<'_>,
decode: &DecodeGeometry,
multiply: &MultiplyGeometry,
) -> Result<()> {
decode.validate()?;
multiply.validate()?;
if u64::from(decode.count) != u64::from(multiply.columns) * u64::from(multiply.rows) {
return Err(KarDecodeError::Invalid(
"KAR decode window is not exactly columns * rows weights",
));
}
let packet = self.admit(packet, decode.packet_len(), false)?;
let weights = self.admit(weights, multiply.weights_len(), false)?;
let input = self.admit(input, multiply.input_len(), false)?;
let output = self.admit(output, multiply.output_len(), false)?;
let status = self.admit(status, STATUS_BYTES, true)?;
Self::disjoint(&[&packet, &weights, &input, &output, &status])?;
let first = self.decode_launch(&packet, &weights, &status, decode)?;
let second = self.multiply_launch(&weights, &input, &output, &status, multiply)?;
self.launch_all(vec![first, second])
}
/// Zero the 4-byte status word.
pub fn clear_status(&self, status: &mut DeviceBuffer<'_>) -> Result<()> {
self.admit(status, STATUS_BYTES, true)?;
status.copy_from(&[0; STATUS_BYTES])?;
Ok(())
}
/// Read the raw status bits (does not interpret them).
pub fn read_status(&self, status: &DeviceBuffer<'_>) -> Result<u32> {
self.admit(status, STATUS_BYTES, true)?;
let mut bytes = [0u8; STATUS_BYTES];
status.copy_to(&mut bytes)?;
Ok(u32::from_le_bytes(bytes))
}
// ------------------------------------------------------- host-visible API
/// Stage a packet, decode it and return the F32 window. Allocates and
/// releases its own scratch (charged to the context budget). Nothing is
/// returned unless the device status is zero and every value is finite.
pub fn decode_to_host(&self, geometry: &DecodeGeometry, packet: &[u8]) -> Result<Vec<f32>> {
geometry.validate()?;
if packet.len() != geometry.packet_len() {
return Err(KarDecodeError::Invalid(
"KAR packet byte length differs from the geometry",
));
}
let context = self.context;
let mut packet_buffer = context.allocate(geometry.packet_len())?;
let mut output_buffer = context.allocate(geometry.output_len())?;
let mut status_buffer = context.allocate(STATUS_BYTES)?;
packet_buffer.copy_from(packet)?;
status_buffer.copy_from(&[0; STATUS_BYTES])?;
self.decode(
&packet_buffer,
&mut output_buffer,
&mut status_buffer,
geometry,
)?;
let flags = self.read_status(&status_buffer)?;
let bytes = download(&output_buffer, geometry.output_len())?;
release_all([packet_buffer, output_buffer, status_buffer])?;
check_status(flags)?;
finite_f32(&bytes)
}
/// `decode_to_host` plus the F32 multiply, one drain; returns
/// `[tokens][rows]`. `input` is `[tokens][columns]` F32.
pub fn decode_multiply_to_host(
&self,
decode: &DecodeGeometry,
multiply: &MultiplyGeometry,
packet: &[u8],
input: &[f32],
) -> Result<Vec<f32>> {
decode.validate()?;
multiply.validate()?;
if packet.len() != decode.packet_len()
|| input.len() * 4 != multiply.input_len()
|| input.iter().any(|v| !v.is_finite())
{
return Err(KarDecodeError::Invalid(
"KAR packet or finite input length differs from the geometry",
));
}
let context = self.context;
let mut packet_buffer = context.allocate(decode.packet_len())?;
let mut weights = context.allocate(multiply.weights_len())?;
let mut input_buffer = context.allocate(multiply.input_len())?;
let mut output_buffer = context.allocate(multiply.output_len())?;
let mut status_buffer = context.allocate(STATUS_BYTES)?;
packet_buffer.copy_from(packet)?;
input_buffer.copy_from(&f32_bytes(input))?;
status_buffer.copy_from(&[0; STATUS_BYTES])?;
self.decode_multiply(
&packet_buffer,
&mut weights,
&input_buffer,
&mut output_buffer,
&mut status_buffer,
decode,
multiply,
)?;
let flags = self.read_status(&status_buffer)?;
let bytes = download(&output_buffer, multiply.output_len())?;
release_all([
packet_buffer,
weights,
input_buffer,
output_buffer,
status_buffer,
])?;
check_status(flags)?;
finite_f32(&bytes)
}
/// One routed expert FFN for a single token, entirely on the device and
/// under one drain: `down(silu(gate(x)) * up(x))`, every matrix decoded
/// from KAR at its own planned level into one reused F32 scratch. Returns
/// the `hidden` outputs only if the device status is zero and every value
/// is finite. Scratch is allocated and released here (budget charged).
pub fn expert_mlp_to_host(
&self,
gate: &KarMatrix<'_>,
up: &KarMatrix<'_>,
down: &KarMatrix<'_>,
input: &[f32],
) -> Result<Vec<f32>> {
let ExpertShape { hidden, ff } =
ExpertShape::from_matrices(&gate.shape, &up.shape, &down.shape)?;
for matrix in [gate, up, down] {
matrix.geometry.validate()?;
matrix.shape.validate()?;
if matrix.packet.len() != matrix.geometry.packet_len()
|| u64::from(matrix.geometry.count)
!= u64::from(matrix.shape.columns) * u64::from(matrix.shape.rows)
{
return Err(KarDecodeError::Invalid(
"KAR expert packet or window differs from its matrix shape",
));
}
}
if input.len() != hidden as usize || input.iter().any(|v| !v.is_finite()) {
return Err(KarDecodeError::Invalid(
"KAR expert input must be exactly `hidden` finite values",
));
}
let context = self.context;
let weights_bytes = [gate, up, down]
.iter()
.map(|m| m.shape.weights_len())
.max()
.unwrap_or(0);
let (hidden_bytes, ff_bytes) = (hidden as usize * 4, ff as usize * 4);
let mut packets = [
context.allocate(gate.geometry.packet_len())?,
context.allocate(up.geometry.packet_len())?,
context.allocate(down.geometry.packet_len())?,
];
let weights = context.allocate(weights_bytes)?;
let mut x = context.allocate(hidden_bytes)?;
let gate_out = context.allocate(ff_bytes)?;
let up_out = context.allocate(ff_bytes)?;
let act = context.allocate(ff_bytes)?;
let out = context.allocate(hidden_bytes)?;
let mut status = context.allocate(STATUS_BYTES)?;
for (buffer, matrix) in packets.iter_mut().zip([gate, up, down]) {
buffer.copy_from(matrix.packet)?;
}
x.copy_from(&f32_bytes(input))?;
status.copy_from(&[0; STATUS_BYTES])?;
let [p_gate, p_up, p_down] = &packets;
let a_gate_p = self.admit(p_gate, gate.geometry.packet_len(), false)?;
let a_up_p = self.admit(p_up, up.geometry.packet_len(), false)?;
let a_down_p = self.admit(p_down, down.geometry.packet_len(), false)?;
let a_weights = self.admit(&weights, weights_bytes, false)?;
let a_x = self.admit(&x, hidden_bytes, false)?;
let a_gate_out = self.admit(&gate_out, ff_bytes, false)?;
let a_up_out = self.admit(&up_out, ff_bytes, false)?;
let a_act = self.admit(&act, ff_bytes, false)?;
let a_out = self.admit(&out, hidden_bytes, false)?;
let a_status = self.admit(&status, STATUS_BYTES, true)?;
Self::disjoint(&[
&a_gate_p,
&a_up_p,
&a_down_p,
&a_weights,
&a_x,
&a_gate_out,
&a_up_out,
&a_act,
&a_out,
&a_status,
])?;
let swiglu = (
self.kernels.swiglu,
[ff.div_ceil(BLOCK_THREADS), 1, 1],
[BLOCK_THREADS, 1, 1],
Self::arguments(&[&a_gate_out, &a_up_out, &a_act, &a_status], &[ff])?,
);
// Stream order serializes the shared weight scratch: each multiply
// finishes reading it before the next decode overwrites it.
let launches = vec![
self.decode_launch(&a_gate_p, &a_weights, &a_status, &gate.geometry)?,
self.multiply_launch(&a_weights, &a_x, &a_gate_out, &a_status, &gate.shape)?,
self.decode_launch(&a_up_p, &a_weights, &a_status, &up.geometry)?,
self.multiply_launch(&a_weights, &a_x, &a_up_out, &a_status, &up.shape)?,
swiglu,
self.decode_launch(&a_down_p, &a_weights, &a_status, &down.geometry)?,
self.multiply_launch(&a_weights, &a_act, &a_out, &a_status, &down.shape)?,
];
self.launch_all(launches)?;
let flags = self.read_status(&status)?;
let bytes = download(&out, hidden_bytes)?;
let [p0, p1, p2] = packets;
release_all([p0, p1, p2, weights, x, gate_out, up_out, act, out, status])?;
check_status(flags)?;
finite_f32(&bytes)
}
}
fn f32_bytes(values: &[f32]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
fn download(buffer: &DeviceBuffer<'_>, len: usize) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
bytes
.try_reserve_exact(len)
.map_err(|_| Error::HostAllocation)?;
bytes.resize(len, 0);
buffer.copy_to(&mut bytes)?;
Ok(bytes)
}
/// A primary driver failure plus the outcome of the mandatory context restore.
fn failure(primary: Error, restore: DriverResult<()>) -> KarDecodeError {
combine::<()>(Err(primary), restore)
.expect_err("a primary failure always stays an error")
.into()
}
fn release_all<const N: usize>(buffers: [DeviceBuffer<'_>; N]) -> Result<()> {
let mut result: DriverResult<()> = Ok(());
for buffer in buffers {
result = combine(result, buffer.release());
}
result.map_err(Into::into)
}
fn finite_f32(bytes: &[u8]) -> Result<Vec<f32>> {
let values: Vec<f32> = bytes
.as_chunks::<4>()
.0
.iter()
.map(|word| f32::from_le_bytes(*word))
.collect();
if values.iter().any(|v| !v.is_finite()) {
return Err(KarDecodeError::NonFinite);
}
Ok(values)
}