Files
leleka/crates/experimental-ref/src/layout.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 594146a79e feat(experimental-ref): CPU references of FWHT-256, Q4_0/INT8 KV quantizers and every KV cell layout
New pure crate with the arithmetic of f16_bits.hpp, kv_q4.cu and kv_q8.cu, the
cell layouts and byte sizes of fp16/INT8/rotated INT8/Q4_0/K8V4/keyless pools
(identical per-cell figures to the memory planner: 2048/1056/576/816/528), and
the generate.cpp format-selection rules. Golden fixtures are produced by the
Original's own host code extracted verbatim with awk (FWHT, Q4_0 quantizer
under separate and fused multiply-add, INT8 K, kv_pool_bytes, kv_block_bytes).
Experimental formats are explicit; nothing is enabled by default.

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

465 lines
18 KiB
Rust

//! KV cache cell layouts and byte sizes of every KV format of the Original (`src/core/layer.cpp`
//! `kv_pool_bytes` / `qsa_state_init`, `kernels/kv_q8.hpp`, `kernels/kv_q4.hpp`, `kernels/kv_stream.cu`
//! `kv_block_bytes`), plus the format-selection rules of `generate.cpp`.
//!
//! This is the *layout* half only. `crates/context` (`memory_plan.rs`, branch `claude/port-rope`) owns the
//! `strata-plan` admission arithmetic and carries its own golden tests of `kv_pool_bytes`; the per-cell
//! figures below (fp16 2048, INT8 1056, Q4_0 576, K8V4 816, keyless 528 bytes per cell and layer) are
//! asserted identical in the tests so the two stay consistent when the branches meet. Nothing is
//! re-derived from the plan; this module is what the CUDA programs index with.
//!
//! Pools are paged: `[page][kv_head][slot][...]` with one physical *row* per (page, head, slot):
//! `row = (page * n_head_kv + head) * page_size + slot`. A KV streaming host copy uses the identity page
//! table with the same row formula.
use crate::{kv_q8, q4_0};
/// Geometry of one QSA layer (`QsaShapes`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct QsaShapes {
pub n_head: i64,
pub n_head_kv: i64,
pub head_dim: i64,
pub n_rot: i64,
pub idx_n_head: i64,
pub idx_dim: i64,
pub idx_block: i64,
pub idx_top_k: i64,
pub page_size: i64,
}
impl QsaShapes {
/// `qsa_real_shapes()`: 24 query heads, 2 KV heads, head_dim 256, page = one indexer block of 4 cells.
pub const fn real() -> Self {
Self {
n_head: 24,
n_head_kv: 2,
head_dim: 256,
n_rot: 64,
idx_n_head: 4,
idx_dim: 128,
idx_block: 4,
idx_top_k: 2048,
page_size: 4,
}
}
/// Rows of one page (all KV heads x page cells).
pub const fn rows_per_page(&self) -> u64 {
(self.n_head_kv * self.page_size) as u64
}
}
/// The KV storage format of the QSA layers.
///
/// Only [`KvFormat::Fp16`] and [`KvFormat::Int8`] are the Original's non-experimental formats; the rest are
/// lossy or unqualified and are never a default: [`KvFormat::is_experimental`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KvFormat {
Fp16,
Int8,
/// INT8 K/V through the Hadamard rotation (`STRATA_KV_ROT=1`): the layout of INT8, rotated contents.
Int8Rotated,
/// `--kv q4_0`: rotated Q4_0 K and V, 576 B per cell.
Q4_0,
/// `--kv k8v4`: INT8 K (unrotated, exact scores) + rotated Q4_0 V, 816 B per cell. No KV streaming.
K8V4,
/// `STRATA_KEYLESS_ROUTING`: V-only INT8, no K store, 528 B per cell. Failed its model-quality gate.
Int8Keyless,
}
impl KvFormat {
pub const ALL: [KvFormat; 6] = [
Self::Fp16,
Self::Int8,
Self::Int8Rotated,
Self::Q4_0,
Self::K8V4,
Self::Int8Keyless,
];
pub const fn name(self) -> &'static str {
match self {
Self::Fp16 => "fp16",
Self::Int8 => "int8",
Self::Int8Rotated => "int8-rotated",
Self::Q4_0 => "q4_0",
Self::K8V4 => "k8v4",
Self::Int8Keyless => "int8-keyless",
}
}
/// Lossy or unqualified: must be named explicitly by the operator.
pub const fn is_experimental(self) -> bool {
!matches!(self, Self::Fp16 | Self::Int8)
}
/// K and V are written through the Hadamard rotation (`kv_rot`); K8V4 rotates only V.
pub const fn rotates_k(self) -> bool {
matches!(self, Self::Q4_0 | Self::Int8Rotated)
}
pub const fn rotates_v(self) -> bool {
matches!(self, Self::Q4_0 | Self::Int8Rotated | Self::K8V4)
}
/// The queries are rotated too (`kv_rot`), and the attention output rotated back.
pub const fn rotates_query(self) -> bool {
self.rotates_k()
}
pub const fn rotates_output(self) -> bool {
self.rotates_v()
}
pub const fn has_k_store(self) -> bool {
!matches!(self, Self::Int8Keyless)
}
/// The fused decode attention's `KV_MODE`: 0 fp16, 1 INT8, 2 Q4_0, 3 K8V4, 4 V-only.
pub const fn attention_mode(self) -> u32 {
match self {
Self::Fp16 => 0,
Self::Int8 | Self::Int8Rotated => 1,
Self::Q4_0 => 2,
Self::K8V4 => 3,
Self::Int8Keyless => 4,
}
}
/// Bytes per cell (one token, one layer, K and V of every KV head).
pub fn bytes_per_cell(self, s: &QsaShapes) -> u64 {
let (h, d) = (s.n_head_kv as usize, s.head_dim as usize);
match self {
Self::Fp16 => (h * d * 2 * 2) as u64,
Self::Int8 | Self::Int8Rotated => kv_q8::bytes_per_cell(h, d),
Self::Q4_0 => q4_0::bytes_per_cell(h, d),
Self::K8V4 => {
(h as u64) * (d as u64 + (d / kv_q8::KV_Q8_GROUP * 2) as u64 + q4_0::bytes_per_head(d))
}
Self::Int8Keyless => kv_q8::bytes_per_cell(h, d) / 2,
}
}
}
/// `--kv` plus the environment switches, as `generate.cpp` validates them. `keyless_routing` stands for a
/// set `STRATA_KEYLESS_ROUTING`; `kv_rot` for `STRATA_KV_ROT=1`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct KvRequest<'a> {
pub kv: &'a str,
pub kv_rot: bool,
pub keyless_routing: bool,
pub kv_resident: i64,
pub gpu_stages: bool,
pub diagnostic_dumps: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KvSelectionError {
UnknownFormat,
KeylessRequiresPlainInt8,
NegativeResident,
K8V4NotStreamable,
}
impl std::fmt::Display for KvSelectionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::UnknownFormat => "--kv must be fp16, int8, q4_0 or k8v4",
Self::KeylessRequiresPlainInt8 => {
"keyless requires INT8, no Hadamard rotation, one GPU stage and no diagnostic dumps"
}
Self::NegativeResident => "--kv-resident must be >= 0",
Self::K8V4NotStreamable => "--kv k8v4 does not support --kv-resident streaming (yet)",
})
}
}
impl std::error::Error for KvSelectionError {}
/// The Original's selection (`generate.cpp:1504-1531`). `q4` is accepted as `q4_0`.
pub fn select_format(r: &KvRequest<'_>) -> Result<KvFormat, KvSelectionError> {
let kv = if r.kv == "q4" { "q4_0" } else { r.kv };
if !matches!(kv, "fp16" | "int8" | "q4_0" | "k8v4") {
return Err(KvSelectionError::UnknownFormat);
}
if r.keyless_routing && (kv != "int8" || r.gpu_stages || r.diagnostic_dumps || r.kv_rot) {
return Err(KvSelectionError::KeylessRequiresPlainInt8);
}
if r.kv_resident < 0 {
return Err(KvSelectionError::NegativeResident);
}
if kv == "k8v4" && r.kv_resident > 0 {
return Err(KvSelectionError::K8V4NotStreamable);
}
Ok(match kv {
_ if r.keyless_routing => KvFormat::Int8Keyless,
"fp16" => KvFormat::Fp16,
"int8" if r.kv_rot => KvFormat::Int8Rotated,
"int8" => KvFormat::Int8,
"q4_0" => KvFormat::Q4_0,
_ => KvFormat::K8V4,
})
}
/// One array of a pool bundle and its place in the 16-byte-aligned arena (`Cursor::take`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PoolArray {
pub name: &'static str,
pub offset: u64,
pub bytes: u64,
}
fn align16(n: u64) -> u64 {
(n + 15) & !15
}
/// The arrays `qsa_state_init` takes for `slots` resident pages, in order, with the Original's
/// 16-byte cursor alignment. Total = last offset + bytes aligned up.
pub fn pool_arrays(fmt: KvFormat, s: &QsaShapes, slots: u64) -> Vec<PoolArray> {
let rows = slots * s.rows_per_page();
let hd = s.head_dim as u64;
let groups = hd / kv_q8::KV_Q8_GROUP as u64;
let q4_row = q4_0::bytes_per_head(hd as usize);
let spec: &[(&'static str, u64)] = &match fmt {
KvFormat::K8V4 => [
("k_q", rows * hd),
("k_scale", rows * groups * 2),
("v_q4", rows * q4_row),
("", 0),
],
KvFormat::Q4_0 => [("k_q4", rows * q4_row), ("v_q4", rows * q4_row), ("", 0), ("", 0)],
KvFormat::Int8 | KvFormat::Int8Rotated => [
("k_q", rows * hd),
("v_q", rows * hd),
("k_scale", rows * groups * 2),
("v_scale", rows * groups * 2),
],
KvFormat::Int8Keyless => [
("v_q", rows * hd),
("v_scale", rows * groups * 2),
("", 0),
("", 0),
],
KvFormat::Fp16 => [("k_pool", rows * hd * 2), ("v_pool", rows * hd * 2), ("", 0), ("", 0)],
};
let mut used = 0;
let mut out = Vec::new();
for (name, bytes) in spec.iter().filter(|(n, _)| !n.is_empty()) {
out.push(PoolArray { name, offset: used, bytes: *bytes });
used = align16(used + bytes);
}
out
}
/// Total aligned arena bytes of [`pool_arrays`].
pub fn pool_arena_bytes(fmt: KvFormat, s: &QsaShapes, slots: u64) -> u64 {
pool_arrays(fmt, s, slots)
.last()
.map_or(0, |a| align16(a.offset + a.bytes))
}
/// `kv_pool_bytes` of `layer.cpp` verbatim (including its `+ 64` slack on every format but fp16).
pub fn kv_pool_bytes(fmt: KvFormat, s: &QsaShapes, pages: u64) -> u64 {
let cell = |per_cell: u64| pages * s.page_size as u64 * per_cell + 64;
match fmt {
KvFormat::Int8Keyless => pages * s.page_size as u64 * kv_q8::bytes_per_cell(s.n_head_kv as usize, s.head_dim as usize) / 2 + 64,
KvFormat::K8V4 => {
let rows = pages * s.rows_per_page();
let hd = s.head_dim as u64;
rows * hd
+ rows * (hd / kv_q8::KV_Q8_GROUP as u64) * 2
+ rows * q4_0::bytes_per_head(hd as usize)
+ 64
}
KvFormat::Q4_0 => cell(q4_0::bytes_per_cell(s.n_head_kv as usize, s.head_dim as usize)),
KvFormat::Int8 | KvFormat::Int8Rotated => cell(kv_q8::bytes_per_cell(s.n_head_kv as usize, s.head_dim as usize)),
KvFormat::Fp16 => pages * s.n_head_kv as u64 * s.page_size as u64 * s.head_dim as u64 * 2 * 2,
}
}
/// The formats that kernels of `kv_stream.cu` can move, by their `KvFormat` enum values
/// (`kKvF16 = 0, kKvInt8 = 1, kKvQ4 = 2, kKvValueInt8 = 4`). Hybrid K8V4 has no streaming id.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StreamFormat {
F16 = 0,
Int8 = 1,
Q4 = 2,
ValueInt8 = 4,
}
impl StreamFormat {
pub fn of(fmt: KvFormat) -> Option<Self> {
match fmt {
KvFormat::Fp16 => Some(Self::F16),
KvFormat::Int8 | KvFormat::Int8Rotated => Some(Self::Int8),
KvFormat::Q4_0 => Some(Self::Q4),
KvFormat::Int8Keyless => Some(Self::ValueInt8),
KvFormat::K8V4 => None,
}
}
}
/// Bytes of one block (page) of K and V together (`kv_block_bytes` in `kv_stream.cu`).
pub fn kv_block_bytes(s: &QsaShapes, fmt: StreamFormat) -> u64 {
let rows = s.rows_per_page();
let hd = s.head_dim as u64;
let group = kv_q8::KV_Q8_GROUP as u64;
match fmt {
StreamFormat::ValueInt8 => rows * (hd + hd / group * 2),
StreamFormat::Q4 => rows * q4_0::bytes_per_head(hd as usize) * 2,
StreamFormat::Int8 => rows * hd * 2 + rows * (hd / group) * 2 * 2,
StreamFormat::F16 => rows * hd * 2 * 2,
}
}
/// Byte runs of a block, per pool array (`runs_of` in `kv_stream.cu`): block `b` of array `i` is bytes
/// `[b * len, (b + 1) * len)`. Array names are those of [`pool_arrays`].
pub fn stream_runs(s: &QsaShapes, fmt: StreamFormat) -> Vec<(&'static str, u64)> {
let rows = s.rows_per_page();
let hd = s.head_dim as u64;
let groups = hd / kv_q8::KV_Q8_GROUP as u64;
match fmt {
StreamFormat::ValueInt8 => vec![("v_q", rows * hd), ("v_scale", rows * groups * 2)],
StreamFormat::Q4 => {
let b = rows * q4_0::bytes_per_head(hd as usize);
vec![("k_q4", b), ("v_q4", b)]
}
StreamFormat::Int8 => {
let (codes, scales) = (rows * hd, rows * groups * 2);
vec![("k_q", codes), ("v_q", codes), ("k_scale", scales), ("v_scale", scales)]
}
StreamFormat::F16 => {
let b = rows * hd * 2;
vec![("k_pool", b), ("v_pool", b)]
}
}
}
/// The physical row of (page, head, slot) in a pool or an identity-layout host copy.
pub const fn physical_row(s: &QsaShapes, page: u64, head: u64, slot: u64) -> u64 {
(page * s.n_head_kv as u64 + head) * s.page_size as u64 + slot
}
#[cfg(test)]
mod tests {
use super::*;
const S: QsaShapes = QsaShapes::real();
#[test]
fn per_cell_bytes_are_the_documented_figures() {
// Identical to crates/context memory_plan.rs (branch claude/port-rope) golden `kv_pool_bytes` rows.
assert_eq!(KvFormat::Fp16.bytes_per_cell(&S), 2048);
assert_eq!(KvFormat::Int8.bytes_per_cell(&S), 1056);
assert_eq!(KvFormat::Int8Rotated.bytes_per_cell(&S), 1056);
assert_eq!(KvFormat::Q4_0.bytes_per_cell(&S), 576);
assert_eq!(KvFormat::K8V4.bytes_per_cell(&S), 816);
assert_eq!(KvFormat::Int8Keyless.bytes_per_cell(&S), 528);
}
#[test]
fn pool_arrays_sum_to_the_per_cell_cost() {
for fmt in KvFormat::ALL {
for slots in [1u64, 7, 5120] {
let cells = slots * S.page_size as u64;
let sum: u64 = pool_arrays(fmt, &S, slots).iter().map(|a| a.bytes).sum();
assert_eq!(sum, cells * fmt.bytes_per_cell(&S), "{fmt:?} {slots}");
// the Original's closed form stays within its `+ 64` slack plus the 4 x 16 cursor slack
let closed = kv_pool_bytes(fmt, &S, slots);
let arena = pool_arena_bytes(fmt, &S, slots);
assert!(arena <= closed + 4 * 16 && arena >= sum, "{fmt:?} {slots} {arena} {closed}");
}
}
}
#[test]
fn arrays_are_16_byte_aligned_and_disjoint() {
for fmt in KvFormat::ALL {
let a = pool_arrays(fmt, &S, 3);
for w in a.windows(2) {
assert!(w[0].offset + w[0].bytes <= w[1].offset);
}
assert!(a.iter().all(|x| x.offset % 16 == 0));
}
}
#[test]
fn array_order_matches_qsa_state_init() {
let names = |f| pool_arrays(f, &S, 1).iter().map(|a| a.name).collect::<Vec<_>>();
assert_eq!(names(KvFormat::K8V4), ["k_q", "k_scale", "v_q4"]);
assert_eq!(names(KvFormat::Q4_0), ["k_q4", "v_q4"]);
assert_eq!(names(KvFormat::Int8), ["k_q", "v_q", "k_scale", "v_scale"]);
assert_eq!(names(KvFormat::Int8Keyless), ["v_q", "v_scale"]);
assert_eq!(names(KvFormat::Fp16), ["k_pool", "v_pool"]);
}
#[test]
fn block_bytes_follow_kv_stream_cu() {
// a block is one page (4 cells): cells x per-cell bytes for the formats that stream
for fmt in [KvFormat::Fp16, KvFormat::Int8, KvFormat::Q4_0, KvFormat::Int8Keyless] {
let sf = StreamFormat::of(fmt).unwrap();
assert_eq!(kv_block_bytes(&S, sf), 4 * fmt.bytes_per_cell(&S), "{fmt:?}");
assert_eq!(
stream_runs(&S, sf).iter().map(|r| r.1).sum::<u64>(),
kv_block_bytes(&S, sf)
);
}
assert_eq!(kv_block_bytes(&S, StreamFormat::Int8), 4224); // the "4,224 B in int8" of kv_stream.hpp
assert!(StreamFormat::of(KvFormat::K8V4).is_none());
}
#[test]
fn stream_run_lengths_are_multiples_of_16_for_the_uint4_copy() {
for fmt in [StreamFormat::F16, StreamFormat::Int8, StreamFormat::Q4, StreamFormat::ValueInt8] {
assert!(stream_runs(&S, fmt).iter().all(|r| r.1 % 16 == 0), "{fmt:?}");
}
}
#[test]
fn selection_rules_are_those_of_generate_cpp() {
let req = |kv| KvRequest {
kv,
kv_rot: false,
keyless_routing: false,
kv_resident: 0,
gpu_stages: false,
diagnostic_dumps: false,
};
assert_eq!(select_format(&req("fp16")), Ok(KvFormat::Fp16));
assert_eq!(select_format(&req("q4")), Ok(KvFormat::Q4_0));
assert_eq!(select_format(&req("q4_0")), Ok(KvFormat::Q4_0));
assert_eq!(select_format(&req("k8v4")), Ok(KvFormat::K8V4));
assert_eq!(select_format(&req("bf16")), Err(KvSelectionError::UnknownFormat));
assert_eq!(
select_format(&KvRequest { kv_rot: true, ..req("int8") }),
Ok(KvFormat::Int8Rotated)
);
let keyless = KvRequest { keyless_routing: true, ..req("int8") };
assert_eq!(select_format(&keyless), Ok(KvFormat::Int8Keyless));
for bad in [
KvRequest { kv: "fp16", ..keyless },
KvRequest { kv: "q4_0", ..keyless },
KvRequest { gpu_stages: true, ..keyless },
KvRequest { diagnostic_dumps: true, ..keyless },
KvRequest { kv_rot: true, ..keyless },
] {
assert_eq!(select_format(&bad), Err(KvSelectionError::KeylessRequiresPlainInt8));
}
assert_eq!(
select_format(&KvRequest { kv_resident: -1, ..req("int8") }),
Err(KvSelectionError::NegativeResident)
);
assert_eq!(
select_format(&KvRequest { kv_resident: 20480, ..req("k8v4") }),
Err(KvSelectionError::K8V4NotStreamable)
);
assert_eq!(
select_format(&KvRequest { kv_resident: 20480, ..req("q4_0") }),
Ok(KvFormat::Q4_0)
);
}
#[test]
fn experimental_flags() {
assert!(!KvFormat::Fp16.is_experimental() && !KvFormat::Int8.is_experimental());
for f in [KvFormat::Int8Rotated, KvFormat::Q4_0, KvFormat::K8V4, KvFormat::Int8Keyless] {
assert!(f.is_experimental(), "{f:?}");
}
assert!(KvFormat::K8V4.rotates_v() && !KvFormat::K8V4.rotates_k());
assert!(KvFormat::K8V4.rotates_output() && !KvFormat::K8V4.rotates_query());
assert!(KvFormat::Q4_0.rotates_query() && KvFormat::Q4_0.rotates_output());
assert!(!KvFormat::Int8Keyless.has_k_store());
assert_eq!(KvFormat::ALL.map(KvFormat::attention_mode), [0, 1, 1, 2, 3, 4]);
}
}