Files
leleka/crates/model-format/src/kar_levels.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

667 lines
23 KiB
Rust

//! Pure KAR level selection for the CUDA expert/dense decode path.
//!
//! Given the NESTED records of an already verified base archive, an optional
//! higher-precision overlay archive, and a per-tensor-class level policy, this
//! module resolves for one tensor exactly which archive supplies it, at which
//! runtime level (2..=5), which archive byte ranges the stager must copy for a
//! bounded window or expert matrix, the resulting device launch geometry, and
//! the scratch bytes it costs against a budget.
//!
//! It performs no I/O, owns no CUDA state and verifies nothing about archive
//! contents: archive identity, payload CRCs and overlay provenance (see
//! `strata-next model resolve-kar-overlay`) are the loader's responsibility
//! and must have succeeded before records are handed in. An overlay replaces a
//! base record by name; it is never an additive residual.
//!
//! Nothing here claims a speed or quality outcome; levels are policy inputs
//! and lower tensor error alone does not pass the model-quality gate.
use crate::kar::{KarInspection, KarNestedRecord};
use crate::kar_kernel_model::{
self as model, KernelModelError, MAX_LEVEL, MAX_TOKENS, MIN_LEVEL, RowPlan, WindowPlan,
};
use std::{collections::BTreeMap, fmt};
/// Bytes of the device status word.
pub const STATUS_BYTES: u64 = 4;
/// Granularity `cuMemAlloc` budgets are accounted at here (a conservative
/// planning constant, not a measured allocator property).
pub const SCRATCH_ALIGN: u64 = 256;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KarLevelsError {
Policy(&'static str),
UnknownTensor(String),
/// The kernel-model planner refused the window (level/dial/range/layout).
Window {
tensor: String,
reason: KernelModelError,
},
Overlay(&'static str),
Budget {
needed: u64,
available: u64,
},
/// An archive range could not be read (truncated, changed or unreadable).
Read,
HostAllocation,
/// Expert map or packet layout violation.
Layout(&'static str),
/// The CPU reference saw a device-style status or a non-finite value.
NonFinite,
}
impl fmt::Display for KarLevelsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Policy(reason) | Self::Overlay(reason) => f.write_str(reason),
Self::UnknownTensor(name) => write!(f, "KAR tensor {name} is not a NESTED record"),
Self::Window { tensor, reason } => write!(f, "{tensor}: {reason}"),
Self::Read => f.write_str("KAR archive range read failed"),
Self::HostAllocation => f.write_str("KAR host packet allocation failed"),
Self::Layout(reason) => f.write_str(reason),
Self::NonFinite => f.write_str("KAR expert computation produced a non-finite value"),
Self::Budget { needed, available } => write!(
f,
"KAR scratch needs {needed} bytes but only {available} remain"
),
}
}
}
impl std::error::Error for KarLevelsError {}
type Result<T> = std::result::Result<T, KarLevelsError>;
// ------------------------------------------------------------------ classes
/// Tensor classes a level policy distinguishes. Classification is by the
/// GGUF-style tensor name suffix and is deliberately coarse.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TensorClass {
RoutedExpert,
SharedExpert,
DenseFfn,
Attention,
Embedding,
Output,
Other,
}
impl TensorClass {
pub const ALL: [TensorClass; 7] = [
Self::RoutedExpert,
Self::SharedExpert,
Self::DenseFfn,
Self::Attention,
Self::Embedding,
Self::Output,
Self::Other,
];
pub fn classify(name: &str) -> Self {
let tail = name.rsplit('.').nth(1).unwrap_or(name);
if tail.ends_with("_exps") {
Self::RoutedExpert
} else if tail.ends_with("_shexp") {
Self::SharedExpert
} else if matches!(tail, "ffn_gate" | "ffn_up" | "ffn_down") {
Self::DenseFfn
} else if tail.starts_with("attn_") || tail.starts_with("ssm_") {
Self::Attention
} else if tail.ends_with("token_embd") {
Self::Embedding
} else if name == "output.weight" {
Self::Output
} else {
Self::Other
}
}
fn index(self) -> usize {
Self::ALL
.iter()
.position(|c| *c == self)
.expect("class is in ALL")
}
}
/// A level per class with a fallback. Every level is bounded to 2..=5 at
/// construction, so an unrepresentable policy cannot exist.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ClassLevels {
default: u8,
per_class: [Option<u8>; 7],
}
impl ClassLevels {
pub fn uniform(level: u8) -> Result<Self> {
check_level(level)?;
Ok(Self {
default: level,
per_class: [None; 7],
})
}
pub fn with(mut self, class: TensorClass, level: u8) -> Result<Self> {
check_level(level)?;
self.per_class[class.index()] = Some(level);
Ok(self)
}
pub fn level_for(&self, class: TensorClass) -> u8 {
self.per_class[class.index()].unwrap_or(self.default)
}
}
fn check_level(level: u8) -> Result<()> {
if (MIN_LEVEL..=MAX_LEVEL).contains(&level) {
Ok(())
} else {
Err(KarLevelsError::Policy("KAR policy level must be 2..=5"))
}
}
/// Levels for tensors served from the base archive and from the overlay.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LevelPolicy {
pub base: ClassLevels,
pub overlay: ClassLevels,
}
// ----------------------------------------------------------------- archives
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ArchiveSlot {
Base,
Overlay,
}
/// NESTED records of one archive the loader has already verified.
pub struct ArchiveView {
sha256: [u8; 32],
archive_bytes: u64,
records: BTreeMap<String, KarNestedRecord>,
}
impl ArchiveView {
/// `records` must come from an archive whose payload CRCs and full SHA-256
/// were verified by the caller; this only re-validates record layouts.
pub fn from_records(
sha256: [u8; 32],
archive_bytes: u64,
records: Vec<KarNestedRecord>,
) -> Result<Self> {
let mut map = BTreeMap::new();
for record in records {
let section_end = record
.section_offset
.checked_add(record.section_bytes)
.ok_or(KarLevelsError::Overlay("KAR section overflows"))?;
if record.validate().is_err() || section_end > archive_bytes {
return Err(KarLevelsError::Overlay(
"KAR record layout is invalid or outside its archive",
));
}
if map.insert(record.name.clone(), record).is_some() {
return Err(KarLevelsError::Overlay("duplicate KAR record name"));
}
}
Ok(Self {
sha256,
archive_bytes,
records: map,
})
}
pub fn from_inspection(
inspection: &KarInspection,
sha256: [u8; 32],
) -> std::result::Result<Self, Box<dyn std::error::Error>> {
let records = inspection.nested_records()?;
Ok(Self::from_records(
sha256,
inspection.summary().archive_bytes,
records,
)?)
}
pub fn records(&self) -> impl Iterator<Item = &KarNestedRecord> {
self.records.values()
}
pub fn sha256(&self) -> &[u8; 32] {
&self.sha256
}
pub fn archive_bytes(&self) -> u64 {
self.archive_bytes
}
}
// ----------------------------------------------------------------- selector
pub struct KarLevelSelector {
base: ArchiveView,
overlay: Option<ArchiveView>,
policy: LevelPolicy,
}
impl KarLevelSelector {
/// Overlay records must replace same-named base records with identical
/// shape; anything else is a mapping the resolver should have rejected.
pub fn new(
base: ArchiveView,
overlay: Option<ArchiveView>,
policy: LevelPolicy,
) -> Result<Self> {
if let Some(overlay) = &overlay {
if overlay.sha256 == base.sha256 {
return Err(KarLevelsError::Overlay(
"overlay archive is the base archive",
));
}
for (name, replacement) in &overlay.records {
let Some(original) = base.records.get(name) else {
return Err(KarLevelsError::Overlay(
"overlay record has no base record to replace",
));
};
if original.dimensions != replacement.dimensions
|| original.n_elements != replacement.n_elements
{
return Err(KarLevelsError::Overlay(
"overlay record shape differs from its base record",
));
}
}
}
Ok(Self {
base,
overlay,
policy,
})
}
/// Which archive serves `name` and at which level, per class policy.
pub fn resolve(&self, name: &str) -> Result<Selection<'_>> {
let class = TensorClass::classify(name);
let (slot, record, level) = match self.overlay.as_ref().and_then(|o| o.records.get(name)) {
Some(record) => (
ArchiveSlot::Overlay,
record,
self.policy.overlay.level_for(class),
),
None => {
let record = self
.base
.records
.get(name)
.ok_or_else(|| KarLevelsError::UnknownTensor(name.to_owned()))?;
(ArchiveSlot::Base, record, self.policy.base.level_for(class))
}
};
Ok(Selection {
class,
slot,
level,
record,
})
}
pub fn archive(&self, slot: ArchiveSlot) -> Option<&ArchiveView> {
match slot {
ArchiveSlot::Base => Some(&self.base),
ArchiveSlot::Overlay => self.overlay.as_ref(),
}
}
/// Compressed bytes if every named tensor stayed resident at its selected
/// level (the libkar `kar_reserve` prefix), checked against a budget.
pub fn resident_bytes<'a>(
&self,
names: impl IntoIterator<Item = &'a str>,
budget: u64,
) -> Result<u64> {
let mut total = 0u64;
for name in names {
total = total
.checked_add(self.resolve(name)?.resident_prefix_bytes()?)
.ok_or(KarLevelsError::Budget {
needed: u64::MAX,
available: budget,
})?;
}
if total > budget {
return Err(KarLevelsError::Budget {
needed: total,
available: budget,
});
}
Ok(total)
}
}
/// One resolved tensor: archive, level and record. Cheap to copy around.
#[derive(Clone, Copy)]
pub struct Selection<'a> {
pub class: TensorClass,
pub slot: ArchiveSlot,
pub level: u8,
pub record: &'a KarNestedRecord,
}
impl Selection<'_> {
fn window_error(&self, reason: KernelModelError) -> KarLevelsError {
KarLevelsError::Window {
tensor: self.record.name.clone(),
reason,
}
}
/// Bytes the whole level-`level` prefix of this record occupies when kept
/// resident compressed (section start through the last used plane).
pub fn resident_prefix_bytes(&self) -> Result<u64> {
let r = self.record;
if !(r.planes_min..=r.planes_max).contains(&self.level) {
return Err(self.window_error(KernelModelError::Rejected(
"KAR level is outside the record's certified dial",
)));
}
r.planes_offset
.checked_sub(r.section_offset)
.and_then(|prefix| {
prefix.checked_add(u64::from(self.level) * u64::from(r.plane_stride_bytes))
})
.filter(|bytes| *bytes <= r.section_bytes)
.ok_or(KarLevelsError::Overlay("invalid KAR resident prefix size"))
}
/// Bounded flat element window `[start, start + count)`.
pub fn window(&self, start: u64, count: u64) -> Result<GpuWindow> {
let plan = model::plan_window(self.record, self.level, start, count)
.map_err(|reason| self.window_error(reason))?;
Ok(GpuWindow::new(self.slot, plan))
}
/// `rows` complete rows from `first_row`, ready for the F32 multiply.
pub fn rows(&self, first_row: u64, rows: u64, tokens: u32) -> Result<GpuRows> {
let plan = model::plan_rows(self.record, self.level, first_row, rows)
.map_err(|reason| self.window_error(reason))?;
GpuRows::new(self.slot, plan, tokens)
}
/// One expert matrix of a `[cols, rows, experts]` record.
pub fn expert(&self, expert: u64, tokens: u32) -> Result<GpuRows> {
let (first, rows) =
model::expert_rows(self.record, expert).map_err(|reason| self.window_error(reason))?;
self.rows(first, rows, tokens)
}
}
// ---------------------------------------------------------------- GPU plans
fn align(bytes: u64) -> u64 {
bytes.div_ceil(SCRATCH_ALIGN) * SCRATCH_ALIGN
}
/// Everything needed to stage and launch one decode window. The driver
/// derives its own `DecodeGeometry` from `plan.params`; the runtime checks the
/// two for equality before any launch.
#[derive(Clone, Debug)]
pub struct GpuWindow {
pub slot: ArchiveSlot,
pub plan: WindowPlan,
}
impl GpuWindow {
fn new(slot: ArchiveSlot, plan: WindowPlan) -> Self {
Self { slot, plan }
}
/// Archive bytes the stager copies into the packet (no padding).
pub fn staged_source_bytes(&self) -> u64 {
self.plan.staged_source_bytes()
}
/// Device scratch for decode only: packet + F32 output + status word.
pub fn scratch(&self) -> ScratchBytes {
ScratchBytes::of(&[
u64::from(self.plan.params.packet_bytes),
u64::from(self.plan.params.count) * 4,
STATUS_BYTES,
])
}
}
/// `[tokens][columns]` input times `[rows][columns]` weights.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RowShape {
pub columns: u32,
pub rows: u32,
pub tokens: u32,
}
impl RowShape {
pub fn weights_bytes(&self) -> u64 {
u64::from(self.columns) * u64::from(self.rows) * 4
}
pub fn input_bytes(&self) -> u64 {
u64::from(self.columns) * u64::from(self.tokens) * 4
}
pub fn output_bytes(&self) -> u64 {
u64::from(self.rows) * u64::from(self.tokens) * 4
}
}
/// A whole-row window plus the multiply shape and its extra buffers.
#[derive(Clone, Debug)]
pub struct GpuRows {
pub window: GpuWindow,
pub shape: RowShape,
}
impl GpuRows {
fn new(slot: ArchiveSlot, plan: RowPlan, tokens: u32) -> Result<Self> {
if tokens == 0 || tokens > MAX_TOKENS {
return Err(KarLevelsError::Policy("KAR multiply tokens must be 1..=8"));
}
Ok(Self {
window: GpuWindow::new(slot, plan.window),
shape: RowShape {
columns: plan.columns,
rows: plan.rows,
tokens,
},
})
}
/// packet + decoded F32 weights + input + output + status, each aligned.
pub fn scratch(&self) -> ScratchBytes {
ScratchBytes::of(&[
u64::from(self.window.plan.params.packet_bytes),
self.shape.weights_bytes(),
self.shape.input_bytes(),
self.shape.output_bytes(),
STATUS_BYTES,
])
}
}
// ------------------------------------------------------------------- budget
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ScratchBytes {
/// Sum of the raw buffer sizes.
pub raw: u64,
/// Sum with each buffer rounded up to `SCRATCH_ALIGN`.
pub aligned: u64,
}
impl ScratchBytes {
pub fn of(buffers: &[u64]) -> Self {
Self {
raw: buffers.iter().sum(),
aligned: buffers.iter().map(|b| align(*b)).sum(),
}
}
}
/// Simple additive scratch ledger. Reuse across sequential windows is modeled
/// by `peak`, concurrent use by reserving each window.
#[derive(Debug)]
pub struct ScratchBudget {
limit: u64,
reserved: u64,
}
impl ScratchBudget {
pub fn new(limit: u64) -> Self {
Self { limit, reserved: 0 }
}
pub fn remaining(&self) -> u64 {
self.limit - self.reserved
}
pub fn reserve(&mut self, scratch: ScratchBytes) -> Result<()> {
let available = self.remaining();
if scratch.aligned > available {
return Err(KarLevelsError::Budget {
needed: scratch.aligned,
available,
});
}
self.reserved += scratch.aligned;
Ok(())
}
pub fn release(&mut self, scratch: ScratchBytes) {
self.reserved = self.reserved.saturating_sub(scratch.aligned);
}
/// Largest single-window requirement when one scratch set is reused.
pub fn peak(scratch: impl IntoIterator<Item = ScratchBytes>) -> u64 {
scratch.into_iter().map(|s| s.aligned).max().unwrap_or(0)
}
}
#[cfg(test)]
#[path = "../tests/kar_levels/mod.rs"]
mod tests;
// -------------------------------------------------- expert map and staging
pub const EXPERT_ROLES: [&str; 3] = ["ffn_gate_exps", "ffn_up_exps", "ffn_down_exps"];
/// GGUF-style tensor name of one routed-expert bank (`role` 0 gate, 1 up, 2 down).
pub fn expert_tensor_name(layer: u32, role: usize) -> String {
format!("blk.{layer}.{}.weight", EXPERT_ROLES[role])
}
impl KarLevelSelector {
/// Every layer x gate/up/down bank exists with exactly `[hidden, ff,
/// experts]` (down: `[ff, hidden, experts]`) and the first and last expert
/// are plannable at the selected level. Called at load, never lazily.
pub fn validate_expert_map(
&self,
layers: u32,
experts: u32,
hidden: u64,
ff: u64,
) -> Result<()> {
for layer in 0..layers {
for role in 0..3 {
let selection = self.resolve(&expert_tensor_name(layer, role))?;
let want = if role == 2 {
[ff, hidden, u64::from(experts)]
} else {
[hidden, ff, u64::from(experts)]
};
if selection.record.dimensions != want {
return Err(KarLevelsError::Layout("KAR expert tensor shape differs"));
}
for expert in [0, u64::from(experts) - 1] {
selection.expert(expert, 1)?;
}
}
}
Ok(())
}
/// Plan the three matrices of one routed expert at their policy levels.
pub fn plan_expert(&self, layer: u32, expert: u32) -> Result<[GpuRows; 3]> {
let plan = |role| -> Result<GpuRows> {
self.resolve(&expert_tensor_name(layer, role))?
.expert(u64::from(expert), 1)
};
Ok([plan(0)?, plan(1)?, plan(2)?])
}
}
/// Read access to an archive's bytes: the retained verified descriptor in
/// production, an in-memory image in tests.
pub trait RangeSource {
fn read_exact_at(&self, offset: u64, out: &mut [u8]) -> std::result::Result<(), KarError>;
}
use crate::kar::KarError;
#[cfg(unix)]
impl RangeSource for KarInspection {
fn read_exact_at(&self, offset: u64, out: &mut [u8]) -> std::result::Result<(), KarError> {
KarInspection::read_exact_at(self, offset, out)
}
}
impl RangeSource for [u8] {
fn read_exact_at(&self, offset: u64, out: &mut [u8]) -> std::result::Result<(), KarError> {
let end = offset
.checked_add(out.len() as u64)
.filter(|end| *end <= self.len() as u64)
.ok_or(KarError::Range("image read exceeds the archive"))?;
out.copy_from_slice(&self[offset as usize..end as usize]);
Ok(())
}
}
/// Copy exactly the planned archive ranges into a zeroed packet.
pub fn stage_window<S: RangeSource + ?Sized>(source: &S, plan: &WindowPlan) -> Result<Vec<u8>> {
let len = plan.packet_bytes() as usize;
let mut packet = Vec::new();
packet
.try_reserve_exact(len)
.map_err(|_| KarLevelsError::HostAllocation)?;
packet.resize(len, 0);
for range in plan.ranges() {
let (at, size) = (range.packet_offset as usize, range.len as usize);
let slot = packet.get_mut(at..at + size).ok_or(KarLevelsError::Layout(
"KAR packet range escapes its packet",
))?;
source
.read_exact_at(range.archive_offset, slot)
.map_err(|_| KarLevelsError::Read)?;
}
Ok(packet)
}
/// Device scratch of one expert FFN as the closed CUDA program allocates it:
/// three packets, one reused F32 weight matrix, input, gate/up/act
/// intermediates, output and the status word, each rounded to the granularity.
pub fn expert_scratch(rows: &[GpuRows; 3]) -> ScratchBytes {
let weights = rows
.iter()
.map(|r| r.shape.weights_bytes())
.max()
.unwrap_or(0);
let hidden = u64::from(rows[0].shape.columns) * 4;
let ff = u64::from(rows[0].shape.rows) * 4;
let mut buffers: Vec<u64> = rows
.iter()
.map(|r| u64::from(r.window.plan.params.packet_bytes))
.collect();
buffers.extend([weights, hidden, ff, ff, ff, hidden, STATUS_BYTES]);
ScratchBytes::of(&buffers)
}
/// CPU transcription of what the device pipeline computes for one expert, built
/// from the kernel model (decode, F32 multiply, SwiGLU). It is the reference a
/// GPU smoke compares against; the SwiGLU stage differs from the device `expf`
/// by libm rounding only, so a device comparison uses a stated tolerance there.
pub fn cpu_reference_mlp(
rows: &[GpuRows; 3],
packets: &[Vec<u8>; 3],
input: &[f32],
) -> Result<Vec<f32>> {
let apply = |index: usize, x: &[f32]| -> Result<Vec<f32>> {
let r = &rows[index];
let mut weights = vec![0f32; r.window.plan.params.count as usize];
if model::kernel_decode(&r.window.plan.params, &packets[index], &mut weights) != 0 {
return Err(KarLevelsError::NonFinite);
}
let mut out = vec![0f32; r.shape.rows as usize];
if model::kernel_multiply(&weights, x, r.shape.columns, r.shape.rows, 1, &mut out) != 0 {
return Err(KarLevelsError::NonFinite);
}
Ok(out)
};
let gate = apply(0, input)?;
let up = apply(1, input)?;
let mut act = vec![0f32; gate.len()];
if model::kernel_swiglu(&gate, &up, &mut act) != 0 {
return Err(KarLevelsError::NonFinite);
}
apply(2, &act)
}