Pin matches the checked-in PTX (length + sha256), PTX is real sm_120 with every named entry exported, and the pin guards still refuse one-byte-corrupted, wrong-length, wrong-digest, zero-pin, embedded-NUL and unterminated synthetic copies. Refusals that relied on 'unsealed' are re-expressed with corrupted-pin copies. GPU load is verified separately by the host smokes; no numerical claim. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
702 lines
26 KiB
Rust
702 lines
26 KiB
Rust
//! Pure, platform-independent half of the KAR level-decode closed program:
|
|
//! launch geometry, packet layout, argument admission, error type and the
|
|
//! fail-closed PTX pin. Nothing here touches CUDA, so it is unit-tested on any
|
|
//! host. The Linux-gated driver half is `kar_decode_levels_gpu`.
|
|
//!
|
|
//! The authoritative CPU specification of the kernel is
|
|
//! `leleka_model_format::kar_kernel_model`; the runtime crate cross-checks
|
|
//! this module against it. The CUDA source is `kar_decode_levels.cu`.
|
|
//!
|
|
//! STATUS: the kernel was compiled with nvcc 13.2.86 and sealed on 2026-10-15;
|
|
//! `KAR_DECODE_LEVELS_PIN` matches the checked-in source and PTX, and `admit_ptx`
|
|
//! still refuses a zero pin, malformed bytes or a digest mismatch. GPU load is
|
|
//! verified separately by the host smokes; no numerical claim is made here.
|
|
|
|
use crate::{Context, Error, combine, qwen_ffi};
|
|
use std::{ffi::CStr, fmt};
|
|
|
|
pub const MIN_LEVEL: u32 = 2;
|
|
pub const MAX_LEVEL: u32 = 5;
|
|
pub const BLOCK_THREADS: u32 = 256;
|
|
/// Largest element range of one launch (kar_expert.cu bound `hidden * ff`).
|
|
pub const MAX_RANGE_ELEMENTS: u64 = 16_777_216;
|
|
pub const MAX_TOKENS: u32 = 8;
|
|
pub const MAX_COLUMNS: u64 = 1 << 20;
|
|
pub const BOOK_REGION_BYTES: u64 = 64;
|
|
pub const PACKET_ALIGN: u64 = 16;
|
|
/// One device status word.
|
|
pub const STATUS_BYTES: usize = 4;
|
|
pub const STATUS_BAD_ARGUMENT: u32 = 1;
|
|
pub const STATUS_NONFINITE_INPUT: u32 = 2;
|
|
pub const STATUS_NONFINITE_OUTPUT: u32 = 4;
|
|
|
|
pub const ENTRY_DECODE: &CStr = c"leleka_kar_decode_levels_f32";
|
|
pub const ENTRY_MULTIPLY: &CStr = c"leleka_kar_multiply_f32";
|
|
pub const ENTRY_SWIGLU: &CStr = c"leleka_kar_swiglu_f32";
|
|
/// Largest SwiGLU width (the expert intermediate size) of one launch.
|
|
pub const MAX_SWIGLU_VALUES: u64 = 1 << 20;
|
|
|
|
/// Frozen-asset bytes plus the single ABI NUL, like every other fixed asset.
|
|
pub static KAR_DECODE_LEVELS_PTX: &[u8] =
|
|
concat!(include_str!("kar_decode_levels.ptx"), "\0").as_bytes();
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum KarDecodeError {
|
|
/// Argument or geometry rejected before any driver use.
|
|
Invalid(&'static str),
|
|
/// The PTX asset is not pinned (all-zero digests) or its bytes differ.
|
|
Unpinned,
|
|
/// The device reported one or more status bits.
|
|
DeviceStatus(u32),
|
|
/// A decoded or multiplied value read back non-finite.
|
|
NonFinite,
|
|
Driver(Error),
|
|
}
|
|
impl fmt::Display for KarDecodeError {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::Invalid(message) => f.write_str(message),
|
|
Self::Unpinned => f.write_str("KAR level-decode PTX is not pinned (TODO-ROOT)"),
|
|
Self::DeviceStatus(bits) => write!(f, "KAR level-decode device status {bits:#x}"),
|
|
Self::NonFinite => f.write_str("KAR level-decode produced a non-finite value"),
|
|
Self::Driver(error) => write!(f, "{error}"),
|
|
}
|
|
}
|
|
}
|
|
impl std::error::Error for KarDecodeError {}
|
|
impl From<Error> for KarDecodeError {
|
|
fn from(error: Error) -> Self {
|
|
Self::Driver(error)
|
|
}
|
|
}
|
|
pub type Result<T> = std::result::Result<T, KarDecodeError>;
|
|
fn invalid<T>(message: &'static str) -> Result<T> {
|
|
Err(KarDecodeError::Invalid(message))
|
|
}
|
|
fn round_up(value: u64, alignment: u64) -> u64 {
|
|
value.div_ceil(alignment) * alignment
|
|
}
|
|
|
|
// -------------------------------------------------------------------- pin
|
|
|
|
/// Producer pin for the single offline-compiled asset. Computing a hash is
|
|
/// not qualification; only Root freezes real values after a GPU smoke.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct PtxPin {
|
|
pub source_sha256: [u8; 32],
|
|
/// SHA-256 of the PTX file bytes excluding the terminating NUL.
|
|
pub ptx_sha256: [u8; 32],
|
|
}
|
|
/// TODO-ROOT: freeze after `nvcc` build and the `#[ignore]d` GPU smoke.
|
|
pub const KAR_DECODE_LEVELS_PIN: PtxPin = PtxPin {
|
|
source_sha256: [
|
|
19, 150, 144, 13, 105, 87, 184, 78, 93, 160, 43, 71, 157, 11, 101, 150, 134, 16, 117, 250,
|
|
161, 60, 121, 117, 131, 93, 199, 90, 90, 111, 127, 126,
|
|
],
|
|
ptx_sha256: [
|
|
236, 105, 119, 135, 224, 0, 83, 16, 0, 94, 177, 105, 167, 88, 49, 94, 181, 80, 58, 199, 103,
|
|
26, 56, 73, 94, 234, 234, 244, 251, 42, 142, 201,
|
|
],
|
|
};
|
|
|
|
/// Fail closed: zero pins, malformed bytes or a digest mismatch all refuse.
|
|
pub fn admit_ptx(ptx: &'static [u8], pin: &PtxPin) -> Result<()> {
|
|
if pin.source_sha256 == [0; 32] || pin.ptx_sha256 == [0; 32] {
|
|
return Err(KarDecodeError::Unpinned);
|
|
}
|
|
if ptx.len() < 2
|
|
|| ptx.last() != Some(&0)
|
|
|| ptx[..ptx.len() - 1].contains(&0)
|
|
|| !ptx.is_ascii()
|
|
{
|
|
return Err(KarDecodeError::Unpinned);
|
|
}
|
|
if qwen_ffi::sha256(&ptx[..ptx.len() - 1]) != pin.ptx_sha256 {
|
|
return Err(KarDecodeError::Unpinned);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
// --------------------------------------------------------------- geometry
|
|
|
|
/// Everything the decode kernel needs besides its three pointers. The staged
|
|
/// plane count always equals `level` (only the planes used are copied).
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct DecodeGeometry {
|
|
pub level: u32,
|
|
pub group: u32,
|
|
pub count: u32,
|
|
pub head32: u32,
|
|
pub head_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,
|
|
}
|
|
|
|
impl DecodeGeometry {
|
|
/// Derive the window layout for elements `[start, start + count)` of a
|
|
/// record with `group` weights per scale, at runtime `level`. Records'
|
|
/// own bounds (`n_elements`, dial, stored planes) are checked upstream by
|
|
/// the model-format planner; this checks only what the kernel relies on.
|
|
pub fn for_window(level: u32, group: u32, start: u64, count: u64) -> Result<Self> {
|
|
if !(MIN_LEVEL..=MAX_LEVEL).contains(&level) {
|
|
return invalid("KAR level must be 2..=5");
|
|
}
|
|
if group == 0 || group > 1024 || !group.is_multiple_of(32) {
|
|
return invalid("KAR group must be a multiple of 32 in 32..=1024");
|
|
}
|
|
if count == 0 || count > MAX_RANGE_ELEMENTS {
|
|
return invalid("KAR decode count must be 1..=16,777,216");
|
|
}
|
|
let Some(end) = start.checked_add(count) else {
|
|
return invalid("KAR decode range overflows");
|
|
};
|
|
let group_u64 = u64::from(group);
|
|
let first_word = start / 32;
|
|
let window_words = end.div_ceil(32) - first_word;
|
|
let first_group = start / group_u64;
|
|
let window_groups = end.div_ceil(group_u64) - first_group;
|
|
let planes_offset = round_up(BOOK_REGION_BYTES + window_groups * 2, PACKET_ALIGN);
|
|
let plane_stride_words = round_up(window_words, 4);
|
|
let packet_bytes = planes_offset + u64::from(level) * plane_stride_words * 4;
|
|
if packet_bytes > u64::from(u32::MAX >> 1) {
|
|
return invalid("KAR packet exceeds 2 GiB");
|
|
}
|
|
Ok(Self {
|
|
level,
|
|
group,
|
|
count: count as u32,
|
|
head32: (start % 32) as u32,
|
|
head_group: (start % group_u64) as u32,
|
|
scales_offset: BOOK_REGION_BYTES as u32,
|
|
planes_offset: planes_offset as u32,
|
|
plane_stride_words: plane_stride_words as u32,
|
|
window_words: window_words as u32,
|
|
window_groups: window_groups as u32,
|
|
packet_bytes: packet_bytes as u32,
|
|
})
|
|
}
|
|
|
|
/// The device argument guard, evaluated on the host in 64-bit arithmetic.
|
|
pub fn validate(&self) -> Result<()> {
|
|
let level = u64::from(self.level);
|
|
let count = u64::from(self.count);
|
|
let group = u64::from(self.group);
|
|
if !(u64::from(MIN_LEVEL)..=u64::from(MAX_LEVEL)).contains(&level) {
|
|
return invalid("KAR level must be 2..=5");
|
|
}
|
|
if count == 0 || count > MAX_RANGE_ELEMENTS {
|
|
return invalid("KAR decode count must be 1..=16,777,216");
|
|
}
|
|
if group == 0 || group > 1024 || !group.is_multiple_of(32) {
|
|
return invalid("KAR group must be a multiple of 32 in 32..=1024");
|
|
}
|
|
if self.head32 >= 32
|
|
|| u64::from(self.head_group) >= group
|
|
|| !self.scales_offset.is_multiple_of(2)
|
|
|| !self.planes_offset.is_multiple_of(4)
|
|
|| !self.plane_stride_words.is_multiple_of(4)
|
|
|| self.window_words > self.plane_stride_words
|
|
|| u64::from(self.packet_bytes) < BOOK_REGION_BYTES
|
|
{
|
|
return invalid("KAR packet layout is misaligned or inconsistent");
|
|
}
|
|
let words_needed = (u64::from(self.head32) + count).div_ceil(32);
|
|
let groups_needed = (u64::from(self.head_group) + count - 1) / group + 1;
|
|
if words_needed > u64::from(self.window_words)
|
|
|| groups_needed > u64::from(self.window_groups)
|
|
|| u64::from(self.scales_offset) + 2 * u64::from(self.window_groups)
|
|
> u64::from(self.packet_bytes)
|
|
|| u64::from(self.planes_offset) + level * u64::from(self.plane_stride_words) * 4
|
|
> u64::from(self.packet_bytes)
|
|
{
|
|
return invalid("KAR packet regions do not cover the requested window");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn grid(&self) -> u32 {
|
|
self.count.div_ceil(BLOCK_THREADS)
|
|
}
|
|
pub fn packet_len(&self) -> usize {
|
|
self.packet_bytes as usize
|
|
}
|
|
pub fn output_len(&self) -> usize {
|
|
self.count as usize * 4
|
|
}
|
|
|
|
/// Scalar kernel arguments after the three pointers, in kernel order.
|
|
#[allow(dead_code)] // consumed by the Linux-gated launcher
|
|
pub(crate) fn scalars(&self) -> [u32; 12] {
|
|
[
|
|
self.level,
|
|
self.level, // staged planes: only `level` planes are staged
|
|
self.count,
|
|
self.head32,
|
|
self.head_group,
|
|
self.group,
|
|
self.scales_offset,
|
|
self.planes_offset,
|
|
self.plane_stride_words,
|
|
self.window_words,
|
|
self.window_groups,
|
|
self.packet_bytes,
|
|
]
|
|
}
|
|
}
|
|
|
|
/// Row-multiply shape: `weights` is `[rows][columns]` F32, `input` is
|
|
/// `[tokens][columns]`, `output` is `[tokens][rows]`.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct MultiplyGeometry {
|
|
pub columns: u32,
|
|
pub rows: u32,
|
|
pub tokens: u32,
|
|
}
|
|
impl MultiplyGeometry {
|
|
pub fn validate(&self) -> Result<()> {
|
|
if self.columns == 0
|
|
|| self.rows == 0
|
|
|| self.tokens == 0
|
|
|| self.tokens > MAX_TOKENS
|
|
|| u64::from(self.columns) > MAX_COLUMNS
|
|
|| u64::from(self.columns) * u64::from(self.rows) > MAX_RANGE_ELEMENTS
|
|
{
|
|
return invalid("KAR multiply shape is outside the bounded geometry");
|
|
}
|
|
Ok(())
|
|
}
|
|
pub fn weights_len(&self) -> usize {
|
|
self.columns as usize * self.rows as usize * 4
|
|
}
|
|
pub fn input_len(&self) -> usize {
|
|
self.columns as usize * self.tokens as usize * 4
|
|
}
|
|
pub fn output_len(&self) -> usize {
|
|
self.rows as usize * self.tokens as usize * 4
|
|
}
|
|
}
|
|
|
|
/// The three loaded entries of the closed program, cached per context like
|
|
/// every other fixed kernel (the module is unloaded by `Context::close`).
|
|
#[derive(Clone, Copy)]
|
|
pub(crate) struct KarLevelsKernels {
|
|
pub module: crate::ffi::ModuleHandle,
|
|
pub decode: crate::ffi::FunctionHandle,
|
|
pub multiply: crate::ffi::FunctionHandle,
|
|
pub swiglu: crate::ffi::FunctionHandle,
|
|
}
|
|
|
|
impl Context<'_> {
|
|
/// Unload the cached KAR level-decode module, taking the slot before the
|
|
/// single attempt. A poisoned context only retains the driver.
|
|
pub(crate) fn unload_kar_levels(&self) -> crate::Result<()> {
|
|
let Some(kernels) = self.kar_levels.take() else {
|
|
return Ok(());
|
|
};
|
|
if self.poisoned.get() {
|
|
std::mem::forget(std::rc::Rc::clone(&self.driver.api));
|
|
return Ok(());
|
|
}
|
|
let guard = match self.enter() {
|
|
Ok(guard) => guard,
|
|
Err(error) => {
|
|
self.poisoned.set(true);
|
|
return Err(error);
|
|
}
|
|
};
|
|
let unload = self.driver.api.unload(kernels.module);
|
|
if unload.is_err() {
|
|
self.poisoned.set(true);
|
|
std::mem::forget(std::rc::Rc::clone(&self.driver.api));
|
|
}
|
|
combine(unload, guard.finish())
|
|
}
|
|
}
|
|
|
|
/// Shapes of one routed expert FFN: `gate`/`up` map `hidden -> ff`, `down`
|
|
/// maps `ff -> hidden`; each matrix is `[rows][columns]` row major.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct ExpertShape {
|
|
pub hidden: u32,
|
|
pub ff: u32,
|
|
}
|
|
impl ExpertShape {
|
|
/// Check three decode windows against one expert's shape and return it.
|
|
pub fn from_matrices(
|
|
gate: &MultiplyGeometry,
|
|
up: &MultiplyGeometry,
|
|
down: &MultiplyGeometry,
|
|
) -> Result<Self> {
|
|
for g in [gate, up, down] {
|
|
g.validate()?;
|
|
if g.tokens != 1 {
|
|
return invalid("KAR expert FFN runs one token at a time");
|
|
}
|
|
}
|
|
if gate != up
|
|
|| down.columns != gate.rows
|
|
|| down.rows != gate.columns
|
|
|| u64::from(gate.rows) > MAX_SWIGLU_VALUES
|
|
{
|
|
return invalid("KAR expert gate/up/down shapes are inconsistent");
|
|
}
|
|
Ok(Self {
|
|
hidden: gate.columns,
|
|
ff: gate.rows,
|
|
})
|
|
}
|
|
}
|
|
|
|
/// Interpret a status word read back from the device.
|
|
pub fn check_status(bits: u32) -> Result<()> {
|
|
if bits == 0 {
|
|
Ok(())
|
|
} else {
|
|
Err(KarDecodeError::DeviceStatus(bits))
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn hand_computed_window_layout() {
|
|
// Level 3, group 64, elements 37..338: words 1..11 (10), groups 0..6 (6).
|
|
let g = DecodeGeometry::for_window(3, 64, 37, 301).unwrap();
|
|
assert_eq!(
|
|
g,
|
|
DecodeGeometry {
|
|
level: 3,
|
|
group: 64,
|
|
count: 301,
|
|
head32: 5,
|
|
head_group: 37,
|
|
scales_offset: 64,
|
|
planes_offset: 80, // round_up(64 + 6*2, 16)
|
|
plane_stride_words: 12, // round_up(10, 4)
|
|
window_words: 10,
|
|
window_groups: 6,
|
|
packet_bytes: 80 + 3 * 12 * 4,
|
|
}
|
|
);
|
|
g.validate().unwrap();
|
|
assert_eq!(g.grid(), 2);
|
|
assert_eq!((g.packet_len(), g.output_len()), (224, 1204));
|
|
assert_eq!(g.scalars(), [3, 3, 301, 5, 37, 64, 64, 80, 12, 10, 6, 224]);
|
|
}
|
|
|
|
#[test]
|
|
fn level_group_and_count_bounds() {
|
|
for level in [0, 1, 6, 8, u32::MAX] {
|
|
assert!(DecodeGeometry::for_window(level, 32, 0, 1).is_err());
|
|
}
|
|
for level in 2..=5 {
|
|
assert!(DecodeGeometry::for_window(level, 32, 0, 1).is_ok());
|
|
}
|
|
for group in [0, 1, 16, 31, 33, 48, 1056, u32::MAX] {
|
|
assert!(
|
|
DecodeGeometry::for_window(2, group, 0, 1).is_err(),
|
|
"{group}"
|
|
);
|
|
}
|
|
for group in [32, 64, 96, 128, 1024] {
|
|
assert!(DecodeGeometry::for_window(2, group, 0, 1).is_ok());
|
|
}
|
|
assert!(DecodeGeometry::for_window(2, 32, 0, 0).is_err());
|
|
assert!(DecodeGeometry::for_window(2, 32, 0, MAX_RANGE_ELEMENTS).is_ok());
|
|
assert!(DecodeGeometry::for_window(2, 32, 0, MAX_RANGE_ELEMENTS + 1).is_err());
|
|
assert!(DecodeGeometry::for_window(2, 32, u64::MAX, 1).is_err());
|
|
assert!(DecodeGeometry::for_window(2, 32, u64::MAX - 5, 10).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn every_layout_from_for_window_validates_and_fits_u32() {
|
|
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
|
|
let mut next = || {
|
|
seed ^= seed >> 12;
|
|
seed ^= seed << 25;
|
|
seed ^= seed >> 27;
|
|
seed.wrapping_mul(0x2545_f491_4f6c_dd1d)
|
|
};
|
|
for _ in 0..2000 {
|
|
let level = 2 + (next() % 4) as u32;
|
|
let group = 32 * (1 + (next() % 32) as u32);
|
|
let start = next() % (1 << 40);
|
|
let count = 1 + next() % 100_000;
|
|
let g = DecodeGeometry::for_window(level, group, start, count).unwrap();
|
|
g.validate().unwrap();
|
|
assert_eq!(g.head32 as u64, start % 32);
|
|
assert_eq!(g.head_group as u64, start % u64::from(group));
|
|
assert!(g.packet_bytes as u64 >= BOOK_REGION_BYTES);
|
|
assert_eq!(g.planes_offset % 16, 0);
|
|
}
|
|
// Largest packet: level 5, full range, worst-case unaligned start.
|
|
let g = DecodeGeometry::for_window(5, 32, 31, MAX_RANGE_ELEMENTS).unwrap();
|
|
g.validate().unwrap();
|
|
assert!(g.packet_bytes < 1 << 31);
|
|
}
|
|
|
|
#[test]
|
|
fn validate_rejects_each_corruption() {
|
|
let good = DecodeGeometry::for_window(4, 96, 100, 700).unwrap();
|
|
good.validate().unwrap();
|
|
let cases: [(&str, DecodeGeometry); 14] = [
|
|
("level 1", DecodeGeometry { level: 1, ..good }),
|
|
("level 6", DecodeGeometry { level: 6, ..good }),
|
|
("count 0", DecodeGeometry { count: 0, ..good }),
|
|
(
|
|
"count max+1",
|
|
DecodeGeometry {
|
|
count: MAX_RANGE_ELEMENTS as u32 + 1,
|
|
..good
|
|
},
|
|
),
|
|
("group 0", DecodeGeometry { group: 0, ..good }),
|
|
("group 33", DecodeGeometry { group: 33, ..good }),
|
|
("head32", DecodeGeometry { head32: 32, ..good }),
|
|
(
|
|
"head_group",
|
|
DecodeGeometry {
|
|
head_group: good.group,
|
|
..good
|
|
},
|
|
),
|
|
(
|
|
"words short",
|
|
DecodeGeometry {
|
|
window_words: good.window_words - 1,
|
|
..good
|
|
},
|
|
),
|
|
(
|
|
"groups short",
|
|
DecodeGeometry {
|
|
window_groups: good.window_groups - 1,
|
|
..good
|
|
},
|
|
),
|
|
(
|
|
"stride",
|
|
DecodeGeometry {
|
|
plane_stride_words: good.plane_stride_words - 1,
|
|
..good
|
|
},
|
|
),
|
|
(
|
|
"planes misaligned",
|
|
DecodeGeometry {
|
|
planes_offset: good.planes_offset + 2,
|
|
..good
|
|
},
|
|
),
|
|
(
|
|
"packet short",
|
|
DecodeGeometry {
|
|
packet_bytes: good.packet_bytes - 4,
|
|
..good
|
|
},
|
|
),
|
|
(
|
|
"scales odd",
|
|
DecodeGeometry {
|
|
scales_offset: 65,
|
|
..good
|
|
},
|
|
),
|
|
];
|
|
for (name, bad) in cases {
|
|
assert!(bad.validate().is_err(), "{name}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn multiply_geometry_bounds() {
|
|
let ok = MultiplyGeometry {
|
|
columns: 2048,
|
|
rows: 512,
|
|
tokens: 8,
|
|
};
|
|
ok.validate().unwrap();
|
|
assert_eq!(ok.weights_len(), 2048 * 512 * 4);
|
|
assert_eq!(ok.input_len(), 2048 * 8 * 4);
|
|
assert_eq!(ok.output_len(), 512 * 8 * 4);
|
|
for bad in [
|
|
MultiplyGeometry { columns: 0, ..ok },
|
|
MultiplyGeometry { rows: 0, ..ok },
|
|
MultiplyGeometry { tokens: 0, ..ok },
|
|
MultiplyGeometry { tokens: 9, ..ok },
|
|
MultiplyGeometry {
|
|
columns: (MAX_COLUMNS + 1) as u32,
|
|
rows: 1,
|
|
tokens: 1,
|
|
},
|
|
MultiplyGeometry {
|
|
columns: 4096,
|
|
rows: 4097,
|
|
tokens: 1,
|
|
},
|
|
] {
|
|
assert!(bad.validate().is_err(), "{bad:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn expert_shape_requires_consistent_single_token_matrices() {
|
|
let m = |columns, rows| MultiplyGeometry {
|
|
columns,
|
|
rows,
|
|
tokens: 1,
|
|
};
|
|
let shape =
|
|
ExpertShape::from_matrices(&m(2560, 640), &m(2560, 640), &m(640, 2560)).unwrap();
|
|
assert_eq!(
|
|
shape,
|
|
ExpertShape {
|
|
hidden: 2560,
|
|
ff: 640
|
|
}
|
|
);
|
|
let bad: [(MultiplyGeometry, MultiplyGeometry, MultiplyGeometry); 5] = [
|
|
(m(2560, 640), m(2560, 641), m(640, 2560)),
|
|
(m(2560, 640), m(2560, 640), m(641, 2560)),
|
|
(m(2560, 640), m(2560, 640), m(640, 2561)),
|
|
(
|
|
m(2560, 640),
|
|
m(2560, 640),
|
|
MultiplyGeometry {
|
|
tokens: 2,
|
|
..m(640, 2560)
|
|
},
|
|
),
|
|
(m(0, 640), m(0, 640), m(640, 0)),
|
|
];
|
|
for (g, u, d) in bad {
|
|
assert!(ExpertShape::from_matrices(&g, &u, &d).is_err());
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn status_word_is_fail_closed() {
|
|
assert!(check_status(0).is_ok());
|
|
for bits in [1, 2, 4, 3, 7] {
|
|
assert_eq!(check_status(bits), Err(KarDecodeError::DeviceStatus(bits)));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn sealed_ptx_matches_its_pin_and_every_admission_deviation_fails() {
|
|
use crate::sealed_ptx::test_support::{
|
|
assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, with_embedded_nul,
|
|
without_terminator,
|
|
};
|
|
let ptx = KAR_DECODE_LEVELS_PTX;
|
|
// Sealed with nvcc 13.2.86 on 2026-10-15; structure and pin only (no numerical claim, GPU load is
|
|
// verified separately by the host smokes).
|
|
assert_real_sm120_ptx(
|
|
"kar_decode_levels",
|
|
ptx,
|
|
[ENTRY_DECODE, ENTRY_MULTIPLY, ENTRY_SWIGLU].map(|e| e.to_str().unwrap()),
|
|
);
|
|
assert_nvcc_13_2_86("kar_decode_levels", ptx);
|
|
assert_ne!(KAR_DECODE_LEVELS_PIN.source_sha256, [0; 32]);
|
|
assert_ne!(KAR_DECODE_LEVELS_PIN.ptx_sha256, [0; 32]);
|
|
assert_eq!(
|
|
KAR_DECODE_LEVELS_PIN.ptx_sha256,
|
|
qwen_ffi::sha256(&ptx[..ptx.len() - 1])
|
|
);
|
|
assert_eq!(
|
|
KAR_DECODE_LEVELS_PIN.source_sha256,
|
|
qwen_ffi::sha256(include_str!("kar_decode_levels.cu").as_bytes())
|
|
);
|
|
assert_eq!(admit_ptx(ptx, &KAR_DECODE_LEVELS_PIN), Ok(()));
|
|
// The guard still refuses every deviation, on synthetic copies of the real PTX.
|
|
let pin = &KAR_DECODE_LEVELS_PIN;
|
|
for copy in [
|
|
one_byte_corrupted(ptx),
|
|
one_byte_shorter(ptx),
|
|
one_byte_longer(ptx),
|
|
with_embedded_nul(ptx),
|
|
without_terminator(ptx),
|
|
] {
|
|
assert_eq!(admit_ptx(copy, pin), Err(KarDecodeError::Unpinned));
|
|
}
|
|
let mut wrong_digest = *pin;
|
|
wrong_digest.ptx_sha256[0] ^= 1;
|
|
assert_eq!(admit_ptx(ptx, &wrong_digest), Err(KarDecodeError::Unpinned));
|
|
// A computed digest alone is not qualification: a zero source pin or a
|
|
// zero PTX pin still refuses, and a wrong digest refuses.
|
|
let digest = qwen_ffi::sha256(&ptx[..ptx.len() - 1]);
|
|
for pin in [
|
|
PtxPin {
|
|
source_sha256: [0; 32],
|
|
ptx_sha256: digest,
|
|
},
|
|
PtxPin {
|
|
source_sha256: [1; 32],
|
|
ptx_sha256: [0; 32],
|
|
},
|
|
PtxPin {
|
|
source_sha256: [1; 32],
|
|
ptx_sha256: [2; 32],
|
|
},
|
|
] {
|
|
assert_eq!(admit_ptx(ptx, &pin), Err(KarDecodeError::Unpinned));
|
|
}
|
|
// Only a complete matching pin (a test-local one) admits these bytes.
|
|
let matching = PtxPin {
|
|
source_sha256: [1; 32],
|
|
ptx_sha256: digest,
|
|
};
|
|
assert_eq!(admit_ptx(ptx, &matching), Ok(()));
|
|
// Malformed bytes (embedded NUL, no terminator, non-ASCII) never admit.
|
|
static EMBEDDED_NUL: [u8; 4] = [b'a', 0, b'b', 0];
|
|
static NO_TERMINATOR: [u8; 3] = *b"abc";
|
|
static NON_ASCII: [u8; 3] = [b'a', 0xc3, 0];
|
|
for bytes in [&EMBEDDED_NUL[..], &NO_TERMINATOR[..], &NON_ASCII[..]] {
|
|
let pin = PtxPin {
|
|
source_sha256: [1; 32],
|
|
ptx_sha256: qwen_ffi::sha256(&bytes[..bytes.len() - 1]),
|
|
};
|
|
assert!(admit_ptx(bytes, &pin).is_err());
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn rust_constants_match_the_cuda_source() {
|
|
let source = include_str!("kar_decode_levels.cu");
|
|
for (name, value) in [
|
|
("kMinLevel", MIN_LEVEL.to_string()),
|
|
("kMaxLevel", MAX_LEVEL.to_string()),
|
|
("kBlockThreads", BLOCK_THREADS.to_string()),
|
|
("kMaxCount", format!("{}u", MAX_RANGE_ELEMENTS)),
|
|
("kMaxTokens", MAX_TOKENS.to_string()),
|
|
("kMaxColumns", format!("{}u", MAX_COLUMNS)),
|
|
("kMaxSwiglu", format!("{}u", MAX_SWIGLU_VALUES)),
|
|
("kBookRegionBytes", BOOK_REGION_BYTES.to_string()),
|
|
("kStatusBadArgument", STATUS_BAD_ARGUMENT.to_string()),
|
|
("kStatusNonfiniteInput", STATUS_NONFINITE_INPUT.to_string()),
|
|
(
|
|
"kStatusNonfiniteOutput",
|
|
STATUS_NONFINITE_OUTPUT.to_string(),
|
|
),
|
|
] {
|
|
let needle = format!("{name} = {value};");
|
|
assert!(source.contains(&needle), "missing `{needle}`");
|
|
}
|
|
for entry in [ENTRY_DECODE, ENTRY_MULTIPLY, ENTRY_SWIGLU] {
|
|
let needle = format!("__launch_bounds__(256) void {}(", entry.to_str().unwrap());
|
|
assert!(source.contains(&needle), "missing entry {needle}");
|
|
}
|
|
// Scalar-argument arity of the decode kernel: 3 pointers + 12 scalars.
|
|
let at = source.find("void leleka_kar_decode_levels_f32(").unwrap();
|
|
let signature = &source[at..at + source[at..].find(") {").unwrap()];
|
|
assert_eq!(signature.matches("uint32_t ").count(), 12);
|
|
assert_eq!(signature.matches("__restrict__").count(), 3);
|
|
}
|
|
}
|