//! Literal CPU transcription of the planned CUDA KAR level-decode kernels. //! //! This module is the macOS-verifiable specification of //! `crates/cuda-driver/src/kar_decode_levels.cu`: the same window planning, //! packet layout, thread/block decomposition, plane-word addressing and group //! scale lookup, written as plain Rust loops with the same integer widths and //! the same guard order. Passing its tests proves the *addressing and //! arithmetic specification*; it does not prove that any CUDA build of the //! kernel matches it. That needs an nvcc build and a GPU run (still open). //! //! Format ground truth: `r08/docs/format-kar-v2.md` as mirrored by //! `control-plane/src/kar_codec.rs::decode_range`, the inspector in `kar.rs`, //! and `gpu/kar/src/kar_expert.cu` (decode then plain F32 row multiply). //! //! Window model. A decode request is a flat element range `[start, start+count)` //! of one NESTED record at runtime level `L` in 2..=5. Only the bytes that //! range can touch are staged into one device "packet": //! //! ```text //! packet+0 book: 2^L f16 (level-L table), 64-byte region //! packet+64 scales: window_groups f16, from group start/group //! packet+planes_offset plane p (p) -> fmt::Result { let Self::Rejected(message) = self; f.write_str(message) } } impl std::error::Error for KernelModelError {} type Result = std::result::Result; fn reject(message: &'static str) -> Result { Err(KernelModelError::Rejected(message)) } fn round_up(value: u64, alignment: u64) -> u64 { value.div_ceil(alignment) * alignment } /// One archive byte range and where it lands in the device packet. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ByteRange { pub archive_offset: u64, pub len: u64, pub packet_offset: u64, } /// The scalar arguments of `leleka_kar_decode_levels_f32`, in launch order /// after the three pointers (packet, out, status). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct DecodeParams { pub level: u32, pub staged_planes: u32, pub count: u32, pub head32: u32, pub head_group: u32, pub group: u32, pub scales_offset: u32, pub planes_offset: u32, pub plane_stride_words: u32, pub window_words: u32, pub window_groups: u32, pub packet_bytes: u32, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct WindowPlan { pub level: u8, pub group: u32, pub start: u64, pub count: u32, pub first_word: u64, pub first_group: u64, pub book: ByteRange, pub scales: ByteRange, /// Exactly `level` entries. pub planes: Vec, pub params: DecodeParams, } impl WindowPlan { pub fn packet_bytes(&self) -> u64 { u64::from(self.params.packet_bytes) } pub fn output_bytes(&self) -> u64 { u64::from(self.count) * 4 } pub fn grid_blocks(&self) -> u32 { self.count.div_ceil(BLOCK_THREADS) } /// Every archive range the stager must read, in packet order. pub fn ranges(&self) -> impl Iterator { [&self.book, &self.scales] .into_iter() .chain(self.planes.iter()) } /// Total archive bytes copied into the packet (excludes padding). pub fn staged_source_bytes(&self) -> u64 { self.ranges().map(|r| r.len).sum() } } /// Plan one bounded window of a NESTED record at `level`. pub fn plan_window( record: &KarNestedRecord, level: u8, start: u64, count: u64, ) -> Result { if record.validate().is_err() { return reject("KAR nested record layout is invalid"); } if record.nesting != NESTING_TOPDOWN { return reject("KAR GPU decode supports top-down nesting only"); } if !(MIN_LEVEL..=MAX_LEVEL).contains(&level) { return reject("KAR GPU level must be 2..=5"); } if level > record.planes_stored { return reject("KAR level exceeds the planes stored in the record"); } if level < record.planes_min || level > record.planes_max { return reject("KAR level is outside the record's certified dial"); } if count == 0 || count > MAX_RANGE_ELEMENTS { return reject("KAR decode count must be 1..=16,777,216"); } let end = start .checked_add(count) .filter(|end| *end <= record.n_elements); let Some(end) = end else { return reject("KAR decode range exceeds the tensor"); }; let group = u64::from(record.group); let first_word = start / 32; let window_words = end.div_ceil(32) - first_word; let first_group = start / group; let window_groups = end.div_ceil(group) - first_group; let head32 = start % 32; let head_group = start % group; let level_u64 = u64::from(level); // Book for level L sits after the tables for levels 1..L-1: (2^L - 2) f16. let book_skip = ((1u64 << level) - 2) * 2; let book_len = (1u64 << level) * 2; if book_skip + book_len > record.books_bytes { return reject("KAR book range exceeds the record"); } let scales_len = window_groups * 2; if (first_group + window_groups) * 2 > record.scales_bytes { return reject("KAR scale range exceeds the record"); } let stride = u64::from(record.plane_stride_bytes); let words_len = window_words * 4; if (first_word + window_words) * 4 > stride { return reject("KAR plane word range exceeds the plane stride"); } let scales_packet = BOOK_REGION_BYTES; let planes_packet = round_up(scales_packet + scales_len, PACKET_ALIGN); let plane_stride_words = round_up(window_words, 4); let packet_bytes = planes_packet + level_u64 * plane_stride_words * 4; if packet_bytes > u64::from(u32::MAX >> 1) { return reject("KAR packet exceeds 2 GiB"); } let planes = (0..level_u64) .map(|plane| ByteRange { archive_offset: record.planes_offset + plane * stride + first_word * 4, len: words_len, packet_offset: planes_packet + plane * plane_stride_words * 4, }) .collect(); // All values below were bounded above (count <= 2^24, packet < 2^31). let to_u32 = |v: u64| v as u32; Ok(WindowPlan { level, group: record.group, start, count: to_u32(count), first_word, first_group, book: ByteRange { archive_offset: record.books_offset + book_skip, len: book_len, packet_offset: 0, }, scales: ByteRange { archive_offset: record.scales_offset + first_group * 2, len: scales_len, packet_offset: scales_packet, }, planes, params: DecodeParams { level: u32::from(level), staged_planes: u32::from(level), count: to_u32(count), head32: to_u32(head32), head_group: to_u32(head_group), group: record.group, scales_offset: to_u32(scales_packet), planes_offset: to_u32(planes_packet), plane_stride_words: to_u32(plane_stride_words), window_words: to_u32(window_words), window_groups: to_u32(window_groups), packet_bytes: to_u32(packet_bytes), }, }) } /// A whole-row window plus the geometry the multiply kernel needs. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RowPlan { pub window: WindowPlan, pub columns: u32, pub rows: u32, } /// Plan `rows` complete rows starting at `first_row`. A row is `dims[0]` /// consecutive weights; rows of higher dimensions are flattened in order, so /// expert `e` of a `[cols, rows, experts]` tensor starts at row `e * rows`. pub fn plan_rows( record: &KarNestedRecord, level: u8, first_row: u64, rows: u64, ) -> Result { let Some(&columns) = record.dimensions.first() else { return reject("KAR record has no dimensions"); }; if columns == 0 || columns > MAX_COLUMNS || rows == 0 { return reject("KAR row length or row count is out of range"); } let total_rows = record.n_elements / columns; if first_row .checked_add(rows) .is_none_or(|end| end > total_rows) { return reject("KAR row range exceeds the tensor"); } let (Some(start), Some(count)) = (first_row.checked_mul(columns), rows.checked_mul(columns)) else { return reject("KAR row range overflows"); }; let window = plan_window(record, level, start, count)?; Ok(RowPlan { window, columns: columns as u32, rows: rows as u32, }) } /// Row range of one expert in a `[cols, rows, experts]` record. pub fn expert_rows(record: &KarNestedRecord, expert: u64) -> Result<(u64, u64)> { if record.dimensions.len() != 3 { return reject("KAR expert tensor must have three dimensions"); } let (rows, experts) = (record.dimensions[1], record.dimensions[2]); if expert >= experts { return reject("KAR expert index is outside the tensor"); } Ok((expert * rows, rows)) } // ---------------------------------------------------------------- f16 -> f32 /// Exact binary16 -> binary32 widening (the device uses `__half2float`). pub fn f16_to_f32(bits: u16) -> f32 { let sign = u32::from(bits & 0x8000) << 16; let exponent = u32::from((bits >> 10) & 0x1f); let mantissa = u32::from(bits & 0x3ff); let out = match exponent { 0 if mantissa == 0 => sign, 0 => { let shift = mantissa.leading_zeros() - 21; sign | ((113 - shift) << 23) | (((mantissa << shift) & 0x3ff) << 13) } 31 => sign | 0x7f80_0000 | (mantissa << 13), _ => sign | ((exponent + 112) << 23) | (mantissa << 13), }; f32::from_bits(out) } fn nonfinite_f16(bits: u16) -> bool { bits & 0x7c00 == 0x7c00 } const NAN_BITS: u32 = 0x7fc0_0000; fn le16(bytes: &[u8], at: usize) -> u16 { u16::from_le_bytes([bytes[at], bytes[at + 1]]) } fn le32(bytes: &[u8], at: usize) -> u32 { u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) } /// The argument guard at the top of `leleka_kar_decode_levels_f32`. It runs in /// 64-bit arithmetic before any packet byte is read, so a corrupt parameter /// block cannot cause an out-of-bounds device read. pub fn decode_params_valid(p: &DecodeParams) -> bool { let level = u64::from(p.level); let count = u64::from(p.count); let group = u64::from(p.group); if !(u64::from(MIN_LEVEL)..=u64::from(MAX_LEVEL)).contains(&level) || level > u64::from(p.staged_planes) || count == 0 || count > MAX_RANGE_ELEMENTS || group == 0 || group > 1024 || !group.is_multiple_of(32) || p.head32 >= 32 || u64::from(p.head_group) >= group || !p.scales_offset.is_multiple_of(2) || !p.planes_offset.is_multiple_of(4) || !p.plane_stride_words.is_multiple_of(4) || p.window_words > p.plane_stride_words || u64::from(p.packet_bytes) < BOOK_REGION_BYTES { return false; } // Every staged word / group the loop can touch exists, and every region // lies inside the packet. let words_needed = (u64::from(p.head32) + count).div_ceil(32); let groups_needed = (u64::from(p.head_group) + count - 1) / group + 1; words_needed <= u64::from(p.window_words) && groups_needed <= u64::from(p.window_groups) && u64::from(p.scales_offset) + 2 * u64::from(p.window_groups) <= u64::from(p.packet_bytes) && u64::from(p.planes_offset) + level * u64::from(p.plane_stride_words) * 4 <= u64::from(p.packet_bytes) } /// `gridDim.x` for a decode of `count` elements. pub fn decode_grid(count: u32) -> u32 { count.div_ceil(BLOCK_THREADS) } /// Literal model of `leleka_kar_decode_levels_f32`: block loop, shared book /// load plus barrier, then one thread per output element. Returns the status /// word. On `STATUS_BAD_ARGUMENT` no output element is written. pub fn kernel_decode(p: &DecodeParams, packet: &[u8], out: &mut [f32]) -> u32 { let mut status = 0u32; if !decode_params_valid(p) || packet.len() < p.packet_bytes as usize || out.len() < p.count as usize { return STATUS_BAD_ARGUMENT; } let level = p.level; for block in 0..decode_grid(p.count) { // Shared-memory book as f32, loaded by the first 2^L threads, then // __syncthreads(). Any non-finite table entry flags the launch. let mut book = [0f32; 32]; for thread in 0..BLOCK_THREADS { if thread < (1 << level) { let bits = le16(packet, 2 * thread as usize); if nonfinite_f16(bits) { status |= STATUS_NONFINITE_INPUT; } book[thread as usize] = f16_to_f32(bits); } } // ---- barrier ---- for thread in 0..BLOCK_THREADS { let i = block * BLOCK_THREADS + thread; if i >= p.count { continue; } let position = p.head32 + i; let word = position / 32; let bit = position % 32; let group_index = (p.head_group + i) / p.group; let mut code = 0u32; for plane in 0..level { let at = p.planes_offset as usize + (plane as usize * p.plane_stride_words as usize + word as usize) * 4; code = (code << 1) | ((le32(packet, at) >> bit) & 1); } let scale_bits = le16(packet, p.scales_offset as usize + 2 * group_index as usize); if nonfinite_f16(scale_bits) { status |= STATUS_NONFINITE_INPUT; out[i as usize] = f32::from_bits(NAN_BITS); continue; } // Single binary32 multiply (device: __fmul_rn), as in kar_codec. out[i as usize] = book[code as usize] * f16_to_f32(scale_bits); } } status } /// Literal model of `leleka_kar_multiply_f32`: one block per (row, token), /// 256 lanes striding the columns with separately rounded multiply/add, then /// the fixed 128..1 shared-memory tree. Output is `[token][row]`. #[allow(clippy::needless_range_loop)] // lane indices mirror threadIdx.x pub fn kernel_multiply( weights: &[f32], input: &[f32], columns: u32, rows: u32, tokens: u32, out: &mut [f32], ) -> u32 { let (cols, nrows) = (columns as usize, rows as usize); if columns == 0 || rows == 0 || tokens == 0 || tokens > MAX_TOKENS || u64::from(columns) > MAX_COLUMNS || u64::from(columns) * u64::from(rows) > MAX_RANGE_ELEMENTS || weights.len() < cols * nrows || input.len() < cols * tokens as usize || out.len() < nrows * tokens as usize { return STATUS_BAD_ARGUMENT; } let mut status = 0u32; for token in 0..tokens as usize { for row in 0..nrows { let mut partial = [0f32; BLOCK_THREADS as usize]; for lane in 0..BLOCK_THREADS as usize { let mut sum = 0f32; let mut column = lane; while column < cols { sum += weights[row * cols + column] * input[token * cols + column]; column += BLOCK_THREADS as usize; } partial[lane] = sum; } let mut stride = (BLOCK_THREADS / 2) as usize; while stride > 0 { for lane in 0..stride { partial[lane] += partial[lane + stride]; } stride >>= 1; } if !partial[0].is_finite() { status |= STATUS_NONFINITE_OUTPUT; } out[token * nrows + row] = partial[0]; } } status } /// Largest SwiGLU width of one launch. pub const MAX_SWIGLU_VALUES: u64 = 1 << 20; /// Model of `leleka_kar_swiglu_f32`: `silu(gate) * up` in binary32. The device /// uses `expf`, which is not guaranteed to match Rust's `exp` bit for bit; the /// GPU smoke compares this stage with a tolerance, never as a bit claim. pub fn kernel_swiglu(gate: &[f32], up: &[f32], act: &mut [f32]) -> u32 { let values = gate.len(); if values == 0 || values as u64 > MAX_SWIGLU_VALUES || up.len() != values || act.len() < values { return STATUS_BAD_ARGUMENT; } let mut status = 0; for ((out, g), u) in act.iter_mut().zip(gate).zip(up) { let result = (g / (1.0 + (-g).exp())) * u; if !result.is_finite() { status |= STATUS_NONFINITE_OUTPUT; } *out = result; } status } /// Copy the planned ranges out of an in-memory archive image into a zeroed /// packet. Production stages from a verified mapping through the same /// `WindowPlan::ranges`; this is the reference stager. pub fn stage_packet(plan: &WindowPlan, archive: &[u8]) -> Result> { let mut packet = vec![0u8; plan.packet_bytes() as usize]; for range in plan.ranges() { let (Some(source_end), Some(packet_end)) = ( range.archive_offset.checked_add(range.len), range.packet_offset.checked_add(range.len), ) else { return reject("KAR stage range overflows"); }; if source_end > archive.len() as u64 || packet_end > packet.len() as u64 { return reject("KAR stage range is outside the archive or packet"); } packet[range.packet_offset as usize..packet_end as usize] .copy_from_slice(&archive[range.archive_offset as usize..source_end as usize]); } Ok(packet) } #[cfg(test)] #[path = "../tests/kar_kernel_model/mod.rs"] mod tests;