Files
leleka/crates/model-format/src/native_dense_plan.rs
T

385 lines
14 KiB
Rust

//! Literal host port of the Original `src/core/native_dense.cpp` (`NativeDense::served_names`,
//! `keep_unquantized_ple_key`, and the whole planning/validation half of `NativeDense::load`): which GGUF tensors are
//! served natively, split-shard consistency, payload span validation, bytes per matrix and the shared Q8_1 scratch
//! size.
//! The device upload (`cudaMalloc` + `cudaMemcpy` + attaching `native_data`/`native_type`/`native_q8_1`) is the
//! runtime's; this module produces the exact list it must perform and refuses with the Original's messages.
//!
//! "Experimental GDN/QSA/shared-expert projection overrides. Upload unchanged native GGUF blocks once, then attach them
//! to the matching canonical WeightRef." Types without a native MMVQ kernel keep their canonical paths.
use std::collections::{BTreeMap, BTreeSet};
/// `native_mmvq_supported(ggml_type)`.
pub fn native_mmvq_supported(ggml_type: u32) -> bool {
matches!(ggml_type, 2 | 6 | 7 | 8 | 11 | 12 | 13 | 14 | 20 | 23 | 42 | 16 | 17 | 18 | 21 | 22 | 29)
}
/// The `(block_elems, block_bytes)` table of `native_mmvq_weight_bytes` (the i-quant rows come from `iq_row_bytes` at
/// 256 elements: IQ2_XXS 66, IQ2_XS 74, IQ3_XXS 98, IQ3_S 110, IQ2_S 82, IQ4_XS-family type 29 = 56 bytes).
const WEIGHT_BLOCKS: &[(u32, u64, u64)] = &[
(2, 32, 18),
(20, 32, 18),
(6, 32, 22),
(7, 32, 24),
(8, 32, 34),
(11, 256, 110),
(12, 256, 144),
(13, 256, 176),
(14, 256, 210),
(23, 256, 136),
(42, 64, 18),
(16, 256, 66),
(17, 256, 74),
(18, 256, 98),
(21, 256, 110),
(22, 256, 82),
(29, 256, 56),
];
fn weight_block(ggml_type: u32) -> Option<(u64, u64)> {
WEIGHT_BLOCKS.iter().find(|entry| entry.0 == ggml_type).map(|entry| (entry.1, entry.2))
}
/// `native_mmvq_weight_bytes`; the error texts are the exceptions the Original throws.
pub fn native_mmvq_weight_bytes(ggml_type: u32, n_in: i64, n_out: i64) -> Result<u64, &'static str> {
let (elems, bytes) = weight_block(ggml_type).ok_or("unsupported native MMVQ GGML type")?;
if n_in <= 0 || !(n_in as u64).is_multiple_of(elems) {
return Err("native MMVQ requires n_in > 0 and divisible by its block element count");
}
if n_out <= 0 {
return Err("native MMVQ requires n_out > 0");
}
let row_bytes = (n_in as u64 / elems) * bytes;
row_bytes.checked_mul(n_out as u64).ok_or("native MMVQ weight byte count overflows size_t")
}
/// `native_q8_1_bytes(n_in)` with one column: 36 bytes (`half2` + 32 `int8`) per 32 elements.
pub fn native_q8_1_bytes(n_in: i64) -> Result<u64, &'static str> {
if n_in <= 0 || n_in % 32 != 0 {
return Err("native MMVQ requires n_in > 0 and divisible by its block element count");
}
Ok((n_in as u64 / 32) * 36)
}
/// `strata::block_geometry` (gguf_reader.hpp): elements and bytes per block, the dense-file table.
fn block_geometry(kind: u32) -> Option<(u64, u64)> {
crate::gguf::block_geometry(kind)
}
/// One tensor of a shard's directory.
#[derive(Clone, Debug)]
pub struct TensorRow {
pub name: String,
/// GGUF order, dimension zero varies fastest.
pub shape: Vec<u64>,
pub kind: u32,
/// Offset from the shard's data section.
pub offset: u64,
}
/// What `load` reads of one `GgufFile`.
#[derive(Clone, Debug, Default)]
pub struct ShardInfo {
/// `general.architecture` is present.
pub has_architecture: bool,
/// `check_architecture(gguf)`: empty string = ok (only consulted when `has_architecture`).
pub architecture_error: String,
pub split_count: Option<u64>,
pub split_no: Option<u64>,
pub split_tensors: Option<u64>,
pub data_start: u64,
pub file_size: u64,
pub tensors: Vec<TensorRow>,
}
/// `eligible(tensor, include_ple_key)`.
pub fn eligible(row: &TensorRow, include_ple_key: bool) -> bool {
let name = &row.name;
if !name.starts_with("blk.") {
return false;
}
// Match the native PLE kernel: Q2_0, IQ3_XXS, IQ4_XS and Q8_0 (UD-Q4_K_XL). Other keys retain the packed BF16
// fallback.
if name == "blk.1.ple_key.weight" {
return include_ple_key && matches!(row.kind, 42 | 18 | 23 | 8);
}
const SUFFIXES: [&str; 10] = [
".attn_qkv.weight",
".attn_gate.weight",
".ssm_out.weight",
".attn_q.weight",
".attn_k.weight",
".attn_v.weight",
".attn_output.weight",
".ffn_gate_shexp.weight",
".ffn_up_shexp.weight",
".ffn_down_shexp.weight",
];
SUFFIXES.iter().any(|s| name.ends_with(s))
}
/// `NativeDense::served_names`: the canonical tensor names `load` would serve natively (eligible name, supported
/// type, two-dimensional), from the GGUF headers only.
pub fn served_names(shards: &[ShardInfo], include_ple_key: bool) -> BTreeSet<String> {
let mut out = BTreeSet::new();
for shard in shards {
for row in &shard.tensors {
if eligible(row, include_ple_key) && native_mmvq_supported(row.kind) && row.shape.len() == 2 {
out.insert(row.name.clone());
}
}
}
out
}
/// `keep_unquantized_ple_key`: a pack whose `blk.1.ple_key.weight` row is unquantized (`code_bits == 0`, #326) serves
/// the PLE from that row, so the key is taken out of `skip`. `code_bits` is the pack index's value for that tensor.
pub fn keep_unquantized_ple_key(skip: &mut BTreeSet<String>, code_bits: Option<i32>) {
const KEY: &str = "blk.1.ple_key.weight";
if !skip.contains(KEY) {
return;
}
if code_bits == Some(0) {
skip.remove(KEY);
}
}
/// The canonical `WeightRef` fields `load` consults.
#[derive(Clone, Copy, Debug)]
pub struct Canonical {
pub quantized: bool,
pub ne0: i64,
pub ne1: i64,
/// `ref.native_data != nullptr`.
pub native_attached: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DenseItem {
pub name: String,
pub ggml_type: u32,
pub bytes: u64,
pub ne0: i64,
pub ne1: i64,
/// Index of the shard holding the payload.
pub shard: usize,
/// Byte offset of the payload in the shard file (`data_start + offset`).
pub file_offset: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DensePlan {
pub items: Vec<DenseItem>,
pub max_in: i64,
pub total_bytes: u64,
/// `native_q8_1_bytes(max_in)`: the one Q8_1 scratch shared by every attached matrix.
pub scratch_bytes: u64,
}
fn fail<T>(message: impl Into<String>) -> Result<T, String> {
Err(message.into())
}
/// The state of `plan_load` while it walks the shards.
#[derive(Default)]
struct Planner {
items: Vec<DenseItem>,
seen: BTreeSet<String>,
max_in: i64,
total: u64,
split_count: u64,
split_tensors: u64,
split_numbers: BTreeSet<u64>,
have_architecture: bool,
}
const KEY: &str = "blk.1.ple_key.weight";
impl Planner {
/// Architecture and split metadata of the shard: the first shard defines them, the others must match.
fn check_split(&mut self, shard: &ShardInfo) -> Result<(), String> {
if shard.has_architecture {
self.first_shard(shard)?;
} else if !self.additional_shard_matches(shard) {
return fail(
"native dense: additional shard must match the architecture-validated first shard's split metadata",
);
}
if let Some(n) = shard.split_no
&& !self.split_numbers.insert(n)
{
return fail("native dense: duplicate split shard number");
}
Ok(())
}
fn first_shard(&mut self, shard: &ShardInfo) -> Result<(), String> {
if !shard.architecture_error.is_empty() {
return Err(shard.architecture_error.clone());
}
self.have_architecture = true;
if let (Some(c), Some(0), Some(t)) = (shard.split_count, shard.split_no, shard.split_tensors)
&& c > 1
{
self.split_count = c;
self.split_tensors = t;
}
Ok(())
}
fn additional_shard_matches(&self, shard: &ShardInfo) -> bool {
self.have_architecture
&& self.split_count != 0
&& shard.split_count == Some(self.split_count)
&& shard.split_no.is_some_and(|n| n != 0 && n < self.split_count)
&& shard.split_tensors == Some(self.split_tensors)
}
/// The served matrices of one shard, appended to the plan.
fn collect_items<F: Fn(&str) -> Option<Canonical> + ?Sized>(
&mut self,
shard_index: usize,
shard: &ShardInfo,
canonical: &F,
include_ple_key: bool,
) -> Result<(), String> {
for tensor in &shard.tensors {
if eligible(tensor, include_ple_key) {
self.add_tensor(shard_index, shard, tensor, canonical)?;
}
}
Ok(())
}
fn add_tensor<F: Fn(&str) -> Option<Canonical> + ?Sized>(
&mut self,
shard_index: usize,
shard: &ShardInfo,
tensor: &TensorRow,
canonical: &F,
) -> Result<(), String> {
if !self.seen.insert(tensor.name.clone()) {
return fail(format!("native dense: duplicate tensor {}", tensor.name));
}
let Some(reference) = canonical(&tensor.name) else {
return fail(format!("native dense: tensor absent from canonical table: {}", tensor.name));
};
if reference.native_attached {
return fail("native dense: override already attached");
}
// #326: the pack keeps an unquantized (--compat-bf16) key, which the PLE reads from the arena
if !native_mmvq_supported(tensor.kind) || (tensor.name == KEY && !reference.quantized) {
return Ok(());
}
if !matrix_compatible(tensor, &reference) {
return fail(format!("native dense: incompatible matrix {}", tensor.name));
}
self.push_matrix(shard_index, shard, tensor, &reference)
}
/// Adds the compatible matrix to the plan, with its native byte count.
fn push_matrix(
&mut self,
shard_index: usize,
shard: &ShardInfo,
tensor: &TensorRow,
reference: &Canonical,
) -> Result<(), String> {
let bytes = native_mmvq_weight_bytes(tensor.kind, reference.ne0, reference.ne1)
.map_err(|e| format!("native dense: {e}"))?;
self.max_in = self.max_in.max(reference.ne0);
self.total += bytes;
self.items.push(DenseItem {
name: tensor.name.clone(),
ggml_type: tensor.kind,
bytes,
ne0: reference.ne0,
ne1: reference.ne1,
shard: shard_index,
file_offset: shard.data_start + tensor.offset,
});
Ok(())
}
fn finish(self) -> Result<DensePlan, String> {
if self.items.is_empty() {
return fail("native dense: no supported GDN/QSA matrices in supplied shards");
}
let scratch_bytes = native_q8_1_bytes(self.max_in).map_err(|e| format!("native dense scratch: {e}"))?;
Ok(DensePlan { items: self.items, max_in: self.max_in, total_bytes: self.total, scratch_bytes })
}
}
/// The directory tensor is a two-dimensional quantized matrix of the canonical shape, within int32 dimensions.
fn matrix_compatible(tensor: &TensorRow, reference: &Canonical) -> bool {
let int32 = 1..=i64::from(i32::MAX);
reference.quantized
&& tensor.shape.len() == 2
&& int32.contains(&reference.ne0)
&& int32.contains(&reference.ne1)
&& tensor.shape[0] == reference.ne0 as u64
&& tensor.shape[1] == reference.ne1 as u64
}
/// Everything `NativeDense::load` does before its first `cudaMalloc`, in the Original's order and with its messages.
pub fn plan_load(
shards: &[ShardInfo],
canonical: &dyn Fn(&str) -> Option<Canonical>,
include_ple_key: bool,
) -> Result<DensePlan, String> {
if shards.is_empty() {
return fail("native dense: at least one GGUF shard is required");
}
let mut planner = Planner::default();
for (shard_index, shard) in shards.iter().enumerate() {
planner.check_split(shard)?;
check_payload_spans(shard)?;
planner.collect_items(shard_index, shard, canonical, include_ple_key)?;
}
planner.finish()
}
/// The payload offsets of a shard are distinct, and every directory span, including tensors we do not upload, lies
/// in the payload and overlaps no other: an ignored tensor must not overlap the native matrix that follows it.
fn check_payload_spans(shard: &ShardInfo) -> Result<(), String> {
let mut offsets: Vec<u64> = shard.tensors.iter().map(|t| t.offset).collect();
offsets.sort_unstable();
if offsets.windows(2).any(|w| w[0] == w[1]) {
return fail("native dense: tensor payload offsets overlap");
}
let payload = shard.file_size.saturating_sub(shard.data_start);
for tensor in &shard.tensors {
let bytes = tensor_payload_bytes(tensor)?;
if tensor.offset > payload || bytes > payload - tensor.offset {
return fail(format!("native dense: truncated payload {}", tensor.name));
}
// std::upper_bound: the first offset strictly greater than this tensor's
let next = offsets.partition_point(|o| *o <= tensor.offset);
if next != offsets.len() && bytes > offsets[next] - tensor.offset {
return fail(format!("native dense: overlapping payload {}", tensor.name));
}
}
Ok(())
}
/// The bytes of a directory tensor by its block geometry, refusing a bad geometry, extent or byte count.
fn tensor_payload_bytes(tensor: &TensorRow) -> Result<u64, String> {
let geometry = block_geometry(tensor.kind);
let ok_geometry = geometry.is_some_and(|(elems, _)| !tensor.shape.is_empty() && tensor.shape[0] % elems == 0);
let (block_elements, block_bytes) = match geometry {
Some(g) if ok_geometry => g,
_ => return fail(format!("native dense: invalid block geometry {}", tensor.name)),
};
let mut elements = 1u64;
for &dimension in &tensor.shape {
if dimension == 0 || elements > u64::MAX / dimension {
return fail(format!("native dense: invalid tensor extent {}", tensor.name));
}
elements *= dimension;
}
let blocks = elements / block_elements;
if blocks > u64::MAX / block_bytes {
return fail(format!("native dense: tensor byte count overflow {}", tensor.name));
}
Ok(blocks * block_bytes)
}
/// Name -> attached type, as the runtime reports it after publishing (`ref.native_type`).
pub fn attached_types(plan: &DensePlan) -> BTreeMap<&str, u32> {
plan.items.iter().map(|i| (i.name.as_str(), i.ggml_type)).collect()
}
#[cfg(test)]
mod tests;