keyless.rs: SKLROUT1 artifact admission (layout cross-read against prepare-keyless-routing.py), fmaf-order query routing, positional key reconstruction. cvec.rs: GGUF v3 parsing and the load_control_vectors table builder (19 golden cases incl. the Original's error texts, bit-exact, from the Original function extracted verbatim) and a reduction-tree twin of cvec_kernel. attn.rs: scratch arithmetic and an f64 GQA reference. The emulated kernel text reproduces routing and cvec bit for bit and attention modes 2/3/4 (incl. M-RoPE) to 1.6e-7 relative L2. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
468 lines
21 KiB
Rust
468 lines
21 KiB
Rust
//! The literal experimental kernel text (`crates/cuda-driver/src/experimental_*.cu`), executed on the CPU by
|
|
//! `oracle/run_emulated_kernels.sh`, against the Rust references. The scenarios' inputs are regenerated here with
|
|
//! the mirrored generator, so a fixture/generator mismatch is caught by the input checksum first.
|
|
|
|
mod common;
|
|
|
|
use common::*;
|
|
use leleka_experimental_ref::{
|
|
cache::{self, PoolSet},
|
|
fwht,
|
|
layout::{KvFormat, QsaShapes},
|
|
q4_0::Contraction,
|
|
};
|
|
|
|
const S: QsaShapes = QsaShapes::real();
|
|
// the harness compiles with -ffp-contract=off: separate multiply and add
|
|
const C: Contraction = Contraction::Separate;
|
|
|
|
fn rotate(x: &[f32]) -> Vec<f32> {
|
|
let mut v = x.to_vec();
|
|
fwht::fwht256_rows_in_place(&mut v);
|
|
v
|
|
}
|
|
|
|
fn input_fnv(k: &[f32], v: &[f32]) -> u64 {
|
|
fnv1a(&f32_bytes(k)) ^ fnv1a(&f32_bytes(v)).wrapping_mul(31)
|
|
}
|
|
|
|
#[test]
|
|
fn fwht_kernel_matches_the_reference_bit_for_bit() {
|
|
let fx = fixture("emulated_kernels.json");
|
|
let f = &fx["fwht"];
|
|
let mut g = Lcg::new(11);
|
|
let scale = [1.0f32, 20.0, 0.02];
|
|
let rows = f["rows"].as_u64().unwrap() as usize;
|
|
let mut input = Vec::new();
|
|
for r in 0..rows {
|
|
for _ in 0..256 {
|
|
input.push(g.soft() * scale[r % 3]);
|
|
}
|
|
}
|
|
assert_eq!(fnv1a(&f32_bytes(&input)) as i64, f["input_fnv"].as_i64().unwrap());
|
|
assert_hex_eq("fwht", &f32_bytes(&rotate(&input)), &f["out"]);
|
|
}
|
|
|
|
fn cells(seed: u64, n: usize, scale: f32) -> (Vec<Vec<f32>>, Vec<Vec<f32>>) {
|
|
let mut g = Lcg::new(seed);
|
|
let (mut ks, mut vs) = (Vec::new(), Vec::new());
|
|
for _ in 0..n {
|
|
ks.push((0..512).map(|_| g.soft() * scale).collect::<Vec<_>>());
|
|
vs.push((0..512).map(|_| g.soft() * scale).collect::<Vec<_>>());
|
|
}
|
|
(ks, vs)
|
|
}
|
|
|
|
#[test]
|
|
fn q4_0_append_batch_and_gather_match_the_reference() {
|
|
let fx = fixture("emulated_kernels.json");
|
|
let f = &fx["q4"];
|
|
let table = [2i32, -1, 0];
|
|
let rows = 3 * S.rows_per_page();
|
|
let (ks, vs) = cells(21, 12, 3.0);
|
|
let all_k: Vec<f32> = ks.concat();
|
|
let all_v: Vec<f32> = vs.concat();
|
|
assert_eq!(input_fnv(&all_k, &all_v) as i64, f["input_fnv"].as_i64().unwrap());
|
|
|
|
let mut pools = PoolSet::new(KvFormat::Q4_0, &S, rows).unwrap();
|
|
let mut host = PoolSet::new(KvFormat::Q4_0, &S, rows).unwrap();
|
|
for pos in 0..12 {
|
|
let (k, v) = (rotate(&ks[pos]), rotate(&vs[pos]));
|
|
cache::append_cell(KvFormat::Q4_0, &mut pools, Some(&mut host), &table, pos as i64, &k, &v, &S, C).unwrap();
|
|
}
|
|
assert_hex_eq("k", &pools.k_q4, &f["k"]);
|
|
assert_hex_eq("v", &pools.v_q4, &f["v"]);
|
|
assert_hex_eq("host_k", &host.k_q4, &f["host_k"]);
|
|
assert_hex_eq("host_v", &host.v_q4, &f["host_v"]);
|
|
|
|
// the prompt path: 6 cells from position 3, host copy and staging pool
|
|
let mut g = Lcg::new(31);
|
|
let big_k: Vec<f32> = (0..6 * 512).map(|_| g.soft() * 3.0).collect();
|
|
let big_v: Vec<f32> = (0..6 * 512).map(|_| g.soft() * 3.0).collect();
|
|
assert_eq!(input_fnv(&big_k, &big_v) as i64, f["batch_input_fnv"].as_i64().unwrap());
|
|
let (kr, vr) = (rotate(&big_k), rotate(&big_v));
|
|
let mut batch = PoolSet::new(KvFormat::Q4_0, &S, rows).unwrap();
|
|
let mut bhost = PoolSet::new(KvFormat::Q4_0, &S, rows).unwrap();
|
|
for t in 0..6 {
|
|
cache::append_cell(
|
|
KvFormat::Q4_0,
|
|
&mut batch,
|
|
Some(&mut bhost),
|
|
&table,
|
|
3 + t as i64,
|
|
&kr[t * 512..(t + 1) * 512],
|
|
&vr[t * 512..(t + 1) * 512],
|
|
&S,
|
|
C,
|
|
)
|
|
.unwrap();
|
|
}
|
|
assert_hex_eq("batch_k", &batch.k_q4, &f["batch_k"]);
|
|
assert_hex_eq("batch_v", &batch.v_q4, &f["batch_v"]);
|
|
assert_hex_eq("batch_host_k", &bhost.k_q4, &f["batch_host_k"]);
|
|
assert_hex_eq("batch_host_v", &bhost.v_q4, &f["batch_host_v"]);
|
|
// the staging pool has the identity layout of the host copy and receives every cell
|
|
assert_hex_eq("batch_stage_k", &bhost.k_q4, &f["batch_stage_k"]);
|
|
assert_hex_eq("batch_stage_v", &bhost.v_q4, &f["batch_stage_v"]);
|
|
|
|
let ids = [0i32, 1, 3, 8, 10, 11];
|
|
assert_hex_eq("gather_k", &u16_bytes(&cache::gather_q4(&pools.k_q4, &table, &ids, &S).unwrap()), &f["gather_k"]);
|
|
assert_hex_eq("gather_v", &u16_bytes(&cache::gather_q4(&pools.v_q4, &table, &ids, &S).unwrap()), &f["gather_v"]);
|
|
}
|
|
|
|
#[test]
|
|
fn int8_valueonly_and_k8v4_append_and_gather_match_the_reference() {
|
|
let fx = fixture("emulated_kernels.json");
|
|
let f = &fx["q8"];
|
|
let rows = 3 * S.rows_per_page();
|
|
let (ks, vs) = cells(41, 12, 2.0);
|
|
assert_eq!(input_fnv(&ks.concat(), &vs.concat()) as i64, f["input_fnv"].as_i64().unwrap());
|
|
let table = [1i32, 2, 0];
|
|
let stream = [2i32, -1, 0];
|
|
let ids = [0i32, 1, 3, 8, 10, 11];
|
|
|
|
// 1. INT8 K+V resident
|
|
let mut p = PoolSet::new(KvFormat::Int8, &S, rows).unwrap();
|
|
for pos in 0..12 {
|
|
cache::append_cell(KvFormat::Int8, &mut p, None, &table, pos as i64, &ks[pos], &vs[pos], &S, C).unwrap();
|
|
}
|
|
assert_hex_eq("int8_kq", &p.k_q, &f["int8_kq"]);
|
|
assert_hex_eq("int8_vq", &p.v_q, &f["int8_vq"]);
|
|
assert_hex_eq("int8_ks", &p.k_scale, &f["int8_ks"]);
|
|
assert_hex_eq("int8_vs", &p.v_scale, &f["int8_vs"]);
|
|
assert_hex_eq("int8_gather_k", &u16_bytes(&cache::gather_q8(&p.k_q, &p.k_scale, &table, &ids, &S).unwrap()), &f["int8_gather_k"]);
|
|
assert_hex_eq("int8_gather_v", &u16_bytes(&cache::gather_q8(&p.v_q, &p.v_scale, &table, &ids, &S).unwrap()), &f["int8_gather_v"]);
|
|
|
|
// 2. INT8 with the streaming host copy
|
|
let mut sp = PoolSet::new(KvFormat::Int8, &S, rows).unwrap();
|
|
let mut sh = PoolSet::new(KvFormat::Int8, &S, rows).unwrap();
|
|
for pos in 0..12 {
|
|
cache::append_cell(KvFormat::Int8, &mut sp, Some(&mut sh), &stream, pos as i64, &ks[pos], &vs[pos], &S, C).unwrap();
|
|
}
|
|
for (name, got) in [("stream_kq", &sp.k_q), ("stream_vq", &sp.v_q), ("stream_ks", &sp.k_scale), ("stream_vs", &sp.v_scale),
|
|
("stream_host_kq", &sh.k_q), ("stream_host_vq", &sh.v_q), ("stream_host_ks", &sh.k_scale), ("stream_host_vs", &sh.v_scale)] {
|
|
assert_hex_eq(name, got, &f[name]);
|
|
}
|
|
|
|
// 3. V-only
|
|
let mut vo = PoolSet::new(KvFormat::Int8Keyless, &S, rows).unwrap();
|
|
for pos in 0..12 {
|
|
cache::append_cell(KvFormat::Int8Keyless, &mut vo, None, &table, pos as i64, &ks[pos], &vs[pos], &S, C).unwrap();
|
|
}
|
|
assert_hex_eq("vonly_vq", &vo.v_q, &f["vonly_vq"]);
|
|
assert_hex_eq("vonly_vs", &vo.v_scale, &f["vonly_vs"]);
|
|
|
|
// 4. K8V4
|
|
let mut h = PoolSet::new(KvFormat::K8V4, &S, rows).unwrap();
|
|
for pos in 0..12 {
|
|
cache::append_cell(KvFormat::K8V4, &mut h, None, &table, pos as i64, &ks[pos], &rotate(&vs[pos]), &S, C).unwrap();
|
|
}
|
|
assert_hex_eq("k8v4_kq", &h.k_q, &f["k8v4_kq"]);
|
|
assert_hex_eq("k8v4_ks", &h.k_scale, &f["k8v4_ks"]);
|
|
assert_hex_eq("k8v4_v4", &h.v_q4, &f["k8v4_v4"]);
|
|
assert_hex_eq("k8v4_gather_k", &u16_bytes(&cache::gather_q8(&h.k_q, &h.k_scale, &table, &ids, &S).unwrap()), &f["k8v4_gather_k"]);
|
|
assert_hex_eq("k8v4_gather_v", &u16_bytes(&cache::gather_q4(&h.v_q4, &table, &ids, &S).unwrap()), &f["k8v4_gather_v"]);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------- KV streaming
|
|
|
|
use leleka_experimental_ref::{
|
|
kv_stream::{self, MissOrder, StreamMap},
|
|
layout::StreamFormat,
|
|
};
|
|
use std::collections::BTreeSet;
|
|
|
|
fn host_byte(array: usize, i: usize) -> u8 {
|
|
((((i + array * 7919) as u32).wrapping_mul(2_654_435_761)) >> 24) as u8
|
|
}
|
|
|
|
fn state_hash(m: &StreamMap, placed: usize) -> u64 {
|
|
let mut bytes = Vec::new();
|
|
for v in [&m.page_table, &m.slot_block, &m.slot_stamp, &m.slot_ref] {
|
|
bytes.extend(v.iter().flat_map(|x| x.to_le_bytes()));
|
|
}
|
|
bytes.extend(m.miss_slot[..placed].iter().flat_map(|x| x.to_le_bytes()));
|
|
bytes.extend(m.ctl.iter().flat_map(|x| x.to_le_bytes()));
|
|
fnv1a(&bytes)
|
|
}
|
|
|
|
#[test]
|
|
fn kv_stream_resolver_copy_and_ring_match_the_model() {
|
|
let fx = fixture("emulated_kernels.json");
|
|
let f = &fx["stream"];
|
|
let (n_blocks, n_slots, cap, n_q, calls) = (1600usize, 1030usize, 76usize, 3usize, 45usize);
|
|
let mut map = StreamMap::new(n_blocks, n_slots);
|
|
assert_eq!(state_hash(&map, 0) as i64, f["reset_state_fnv"].as_i64().unwrap());
|
|
|
|
let rows = S.rows_per_page();
|
|
let mut host = PoolSet::new(KvFormat::Int8, &S, n_blocks as u64 * rows).unwrap();
|
|
let mut slots = PoolSet::new(KvFormat::Int8, &S, n_slots as u64 * rows).unwrap();
|
|
for (a, name) in ["k_q", "v_q", "k_scale", "v_scale"].iter().enumerate() {
|
|
for (i, b) in host.array_mut(name).unwrap().iter_mut().enumerate() {
|
|
*b = host_byte(a, i);
|
|
}
|
|
}
|
|
|
|
let mut g = Lcg::new(51);
|
|
let recorded = f["calls"].as_array().unwrap();
|
|
assert_eq!(recorded.len(), calls);
|
|
let mut seen_evictions = false;
|
|
for (call, rec) in recorded.iter().enumerate() {
|
|
let mut ids = vec![0i32; n_q * cap];
|
|
let mut steps = vec![0i32; n_q * 4];
|
|
for q in 0..n_q {
|
|
let mut blocks = BTreeSet::new();
|
|
while blocks.len() < cap / 4 {
|
|
let b = if g.below(2) != 0 { g.below(n_blocks as u32) } else { (call as u32 * 7 + g.below(120)) % n_blocks as u32 };
|
|
blocks.insert(b);
|
|
}
|
|
let mut w = 0;
|
|
for b in blocks {
|
|
for i in 0..4 {
|
|
ids[q * cap + w] = (b * 4 + i) as i32;
|
|
w += 1;
|
|
}
|
|
}
|
|
steps[q * 4 + 3] = w as i32;
|
|
}
|
|
let order: Vec<i32> = rec["order"].as_array().unwrap().iter().map(|x| x.as_i64().unwrap() as i32).collect();
|
|
let report = map.resolve(&ids, &steps, n_q, cap, 4, &MissOrder::Observed(order.clone())).unwrap();
|
|
assert_eq!(report.placed, order.len(), "call {call}");
|
|
map.copy_missed(&mut slots, &host, &S, StreamFormat::Int8);
|
|
let ctl: Vec<i32> = rec["ctl"].as_array().unwrap().iter().map(|x| x.as_i64().unwrap() as i32).collect();
|
|
assert_eq!(map.ctl.to_vec(), ctl, "ctl after call {call}");
|
|
assert_eq!(state_hash(&map, report.placed) as i64, rec["state_fnv"].as_i64().unwrap(), "state after call {call}");
|
|
assert!(map.is_consistent());
|
|
seen_evictions |= map.resident_blocks() == n_slots;
|
|
}
|
|
assert!(seen_evictions, "the scenario must fill every slot so that later calls evict");
|
|
for (name, key) in [("k_q", "slots_fnv_k_q"), ("v_q", "slots_fnv_v_q"), ("k_scale", "slots_fnv_k_scale"), ("v_scale", "slots_fnv_v_scale")] {
|
|
assert_eq!(fnv1a(slots.array(name).unwrap()) as i64, f[key].as_i64().unwrap(), "{name}");
|
|
}
|
|
|
|
let ring: Vec<i64> = f["ring_table"].as_array().unwrap().iter().map(|x| x.as_i64().unwrap()).collect();
|
|
assert_eq!(kv_stream::ring_table(37, 8).iter().map(|x| i64::from(*x)).collect::<Vec<_>>(), ring);
|
|
assert_eq!(f["copy_u4_equal"].as_i64(), Some(1));
|
|
|
|
map.reset();
|
|
assert_eq!(state_hash(&map, 0) as i64, f["final_reset_state_fnv"].as_i64().unwrap());
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------- keyless routing
|
|
|
|
use leleka_experimental_ref::{
|
|
attn,
|
|
cvec::{self, CvecMode, CvecTables},
|
|
keyless,
|
|
};
|
|
|
|
fn routing_matrices(heads: usize) -> Vec<f32> {
|
|
let mut m = vec![0.0f32; heads * 256 * 256];
|
|
for h in 0..heads {
|
|
for d in 0..256 {
|
|
for j in 0..256 {
|
|
let a = if d == j { 0.8f32 } else { 0.0 };
|
|
m[(h * 256 + d) * 256 + j] = a + ((((h * 19 + d * 3 + j * 11) % 17) as i32 - 8) as f32) * 0.001f32;
|
|
}
|
|
}
|
|
}
|
|
m
|
|
}
|
|
|
|
#[test]
|
|
fn keyless_query_routing_kernel_matches_the_fmaf_reference_bit_for_bit() {
|
|
let fx = fixture("emulated_kernels.json");
|
|
let f = &fx["route"];
|
|
let (tokens, heads) = (f["tokens"].as_u64().unwrap() as usize, f["heads"].as_u64().unwrap() as usize);
|
|
let mut g = Lcg::new(61);
|
|
let mut q: Vec<f32> = (0..tokens * heads * 256).map(|_| g.soft()).collect();
|
|
keyless::route_query(&mut q, &routing_matrices(heads), tokens, heads).unwrap();
|
|
assert_hex_eq("routed", &f32_bytes(&q), &f["routed"]);
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------ control vector
|
|
|
|
#[test]
|
|
fn cvec_kernel_matches_the_reduction_tree_twin() {
|
|
let fx = fixture("emulated_kernels.json");
|
|
let f = &fx["cvec"];
|
|
let (n, hc, t_count, layer, l) = (
|
|
f["n"].as_u64().unwrap() as usize,
|
|
f["hc"].as_u64().unwrap() as usize,
|
|
f["T"].as_u64().unwrap() as usize,
|
|
f["layer"].as_u64().unwrap() as usize,
|
|
f["L"].as_u64().unwrap() as usize,
|
|
);
|
|
let unit = hex_f32(f["unit"].as_str().unwrap());
|
|
let add_dir = hex_f32(f["add_dir"].as_str().unwrap());
|
|
let r0 = hex_f32(f["r0"].as_str().unwrap());
|
|
let bo = hex_f32(f["bo"].as_str().unwrap());
|
|
let inj = hex_f32(f["inj"].as_str().unwrap());
|
|
// regenerate and cross-check the inputs
|
|
let mut g = Lcg::new(71);
|
|
let v: Vec<f32> = (0..n).map(|_| g.soft()).collect();
|
|
assert_eq!(v.iter().map(|x| x.to_bits()).collect::<Vec<_>>(), add_dir.iter().map(|x| x.to_bits()).collect::<Vec<_>>());
|
|
let r_ld = hc * n;
|
|
let table = |mode: CvecMode, dirv: &[f32], s_val: f32| {
|
|
let mut dir = vec![0.0f32; l * n];
|
|
let mut s = vec![0.0f32; l];
|
|
dir[layer * n..(layer + 1) * n].copy_from_slice(dirv);
|
|
s[layer] = s_val;
|
|
let steered = s.iter().map(|x| *x != 0.0).collect();
|
|
CvecTables { dir, s, mode, first: 1, last: l as i64 - 1, n_embd: n as i64, hc: hc as i64, steered, summary: String::new() }
|
|
};
|
|
let run = |t: &CvecTables, on: bool, layer_used: usize, write: bool| {
|
|
let mut r = r0.clone();
|
|
let pending = if write { Some((&bo[..], n, &inj[..], hc)) } else { None };
|
|
cvec::apply(&mut r, t, on, layer_used, t_count, r_ld, pending);
|
|
r
|
|
};
|
|
let cases: [(&str, Vec<f32>, bool); 8] = [
|
|
("project_s1", run(&table(CvecMode::Project, &unit, 1.0), true, layer, false), false),
|
|
("project_s2", run(&table(CvecMode::Project, &unit, 2.0), true, layer, false), false),
|
|
("add", run(&table(CvecMode::Add, &add_dir, 1.0), true, layer, false), false),
|
|
("off", run(&table(CvecMode::Project, &unit, 1.0), false, layer, false), false),
|
|
("off_write", run(&table(CvecMode::Project, &unit, 1.0), false, layer, true), true),
|
|
("project_write", run(&table(CvecMode::Project, &unit, 1.0), true, layer, true), true),
|
|
("add_write", run(&table(CvecMode::Add, &add_dir, 1.0), true, layer, true), true),
|
|
("no_direction_layer", run(&table(CvecMode::Project, &unit, 1.0), true, 1, false), false),
|
|
];
|
|
for (name, got, uses_sigmoid) in cases {
|
|
if !uses_sigmoid {
|
|
// no exp involved: bit-exact, including the dot reduction tree
|
|
assert_hex_eq(name, &f32_bytes(&got), &f[name]);
|
|
} else {
|
|
// the pending write evaluates sigmoid(): libm expf here, the device's __expf there. The harness and
|
|
// this test both use the platform libm, so they agree to a few ULP, not necessarily bit for bit.
|
|
let want = hex_f32(f[name].as_str().unwrap());
|
|
let mut worst = 0.0f32;
|
|
for (a, b) in got.iter().zip(&want) {
|
|
worst = worst.max((a - b).abs() / b.abs().max(1.0));
|
|
}
|
|
assert!(worst < 1e-5, "{name}: worst relative difference {worst}");
|
|
}
|
|
}
|
|
assert_eq!(f32_bytes(&r0), f32_bytes(&hex_f32(f["r0"].as_str().unwrap())));
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------ attention
|
|
|
|
const CELLS: usize = 70;
|
|
const NQ: usize = 2;
|
|
const NH: usize = 24;
|
|
|
|
fn gqa_tensors(
|
|
ids: &[i32],
|
|
deq: &dyn Fn(&[i32]) -> Vec<f32>,
|
|
) -> Vec<f32> {
|
|
deq(ids)
|
|
}
|
|
|
|
fn check_attention(name: &str, got: &[f32], q: &[Vec<f32>], selections: &[Vec<i32>], k: &dyn Fn(&[i32]) -> Vec<f32>, v: &dyn Fn(&[i32]) -> Vec<f32>) {
|
|
assert_eq!(got.len(), NQ * NH * 256);
|
|
for b in 0..NQ {
|
|
let ids = &selections[b];
|
|
let want = attn::reference(&q[b], &gqa_tensors(ids, k), &gqa_tensors(ids, v), NH, 2, ids.len());
|
|
let (l2, max) = attn::errors(&got[b * NH * 256..(b + 1) * NH * 256], &want);
|
|
eprintln!("{name} query {b}: relative L2 {l2:e}, max abs {max:e}");
|
|
assert!(l2 < 1e-5 && max < 1e-5, "{name} query {b}: relative L2 {l2:e}, max abs {max:e}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn quantized_attention_kernels_match_the_double_precision_reference() {
|
|
let fx = fixture("emulated_kernels.json");
|
|
let f = &fx["attn"];
|
|
let table: Vec<i32> = (0..18).map(|i| (i * 5 + 3) % 18).collect();
|
|
let rows = 18 * S.rows_per_page();
|
|
let mut g = Lcg::new(81);
|
|
let (mut kc, mut vc) = (Vec::new(), Vec::new());
|
|
for _ in 0..CELLS {
|
|
kc.push((0..512).map(|_| g.soft() * 1.5).collect::<Vec<f32>>());
|
|
vc.push((0..512).map(|_| g.soft() * 1.5).collect::<Vec<f32>>());
|
|
}
|
|
let q: Vec<f32> = (0..NQ * NH * 256).map(|_| g.soft()).collect();
|
|
let fnv = fnv1a(&f32_bytes(&q)) ^ fnv1a(&f32_bytes(&kc[0])).wrapping_mul(3) ^ fnv1a(&f32_bytes(&vc[CELLS - 1])).wrapping_mul(5);
|
|
assert_eq!(fnv as i64, f["input_fnv"].as_i64().unwrap());
|
|
let sel_full: Vec<i32> = (0..CELLS as i32).collect();
|
|
let sel_short: Vec<i32> = (0..66).collect();
|
|
let selections = vec![sel_full, sel_short];
|
|
let per_q = |x: &[f32]| -> Vec<Vec<f32>> { (0..NQ).map(|b| x[b * NH * 256..(b + 1) * NH * 256].to_vec()).collect() };
|
|
|
|
// ---- mode 2: Q4_0 K and V rotated, rotated query
|
|
{
|
|
let mut pools = PoolSet::new(KvFormat::Q4_0, &S, rows).unwrap();
|
|
for c in 0..CELLS {
|
|
cache::append_cell(KvFormat::Q4_0, &mut pools, None, &table, c as i64, &rotate(&kc[c]), &rotate(&vc[c]), &S, C).unwrap();
|
|
}
|
|
let qr = per_q(&rotate(&q));
|
|
let got = hex_f32(f["m2"]["out"].as_str().unwrap());
|
|
check_attention(
|
|
"mode 2",
|
|
&got,
|
|
&qr,
|
|
&selections,
|
|
&|ids| cache::dequant_q4(&pools.k_q4, &table, ids, &S).unwrap(),
|
|
&|ids| cache::dequant_q4(&pools.v_q4, &table, ids, &S).unwrap(),
|
|
);
|
|
}
|
|
// ---- mode 3: INT8 K (unrotated), Q4_0 V (rotated)
|
|
{
|
|
let mut pools = PoolSet::new(KvFormat::K8V4, &S, rows).unwrap();
|
|
for c in 0..CELLS {
|
|
cache::append_cell(KvFormat::K8V4, &mut pools, None, &table, c as i64, &kc[c], &rotate(&vc[c]), &S, C).unwrap();
|
|
}
|
|
let got = hex_f32(f["m3"]["out"].as_str().unwrap());
|
|
check_attention(
|
|
"mode 3",
|
|
&got,
|
|
&per_q(&q),
|
|
&selections,
|
|
&|ids| cache::dequant_q8(&pools.k_q, &pools.k_scale, &table, ids, &S).unwrap(),
|
|
&|ids| cache::dequant_q4(&pools.v_q4, &table, ids, &S).unwrap(),
|
|
);
|
|
}
|
|
// ---- mode 4: V-only, routed + position-encoded queries, keys rebuilt from V
|
|
{
|
|
let mut pools = PoolSet::new(KvFormat::Int8Keyless, &S, rows).unwrap();
|
|
for c in 0..CELLS {
|
|
cache::append_cell(KvFormat::Int8Keyless, &mut pools, None, &table, c as i64, &kc[c], &vc[c], &S, C).unwrap();
|
|
}
|
|
let cos = hex_f32(f["cos"].as_str().unwrap());
|
|
let sin = hex_f32(f["sin"].as_str().unwrap());
|
|
let mpos: Vec<i32> = (0..CELLS).flat_map(|cell| (0..3).map(move |sector| (cell / (sector + 2)) as i32)).collect();
|
|
let qpos = [CELLS as i32 - 1, 51];
|
|
let matrices = routing_matrices(NH);
|
|
let kids: Vec<Vec<i32>> = qpos.iter().map(|p| (0..=*p).filter(|c| c % 3 != 1).collect()).collect();
|
|
for (vision, key) in [(false, "m4"), (true, "m4_mrope")] {
|
|
let mut routed = q.clone();
|
|
keyless::route_query(&mut routed, &matrices, NQ, NH).unwrap();
|
|
for b in 0..NQ {
|
|
for h in 0..NH {
|
|
for d in 0..32 {
|
|
let i = (b * NH + h) * 256 + d;
|
|
let rp = if vision { mpos[qpos[b] as usize * 3 + d % 3] } else { qpos[b] } as usize;
|
|
let (a, v2, c, s) = (routed[i], routed[i + 32], cos[rp * 32 + d], sin[rp * 32 + d]);
|
|
routed[i] = a * c - v2 * s;
|
|
routed[i + 32] = a * s + v2 * c;
|
|
}
|
|
}
|
|
}
|
|
let got = hex_f32(f[key]["out"].as_str().unwrap());
|
|
let mrope = if vision { Some(&mpos[..]) } else { None };
|
|
let value = |ids: &[i32]| cache::dequant_q8(&pools.v_q, &pools.v_scale, &table, ids, &S).unwrap();
|
|
let keys = |ids: &[i32]| -> Vec<f32> {
|
|
let v = value(ids);
|
|
let mut out = Vec::with_capacity(v.len());
|
|
for (i, &cell) in ids.iter().enumerate() {
|
|
for kvh in 0..2 {
|
|
out.extend(keyless::key_from_value(&v[(i * 2 + kvh) * 256..][..256], cell, &cos, &sin, mrope));
|
|
}
|
|
}
|
|
out
|
|
};
|
|
check_attention(key, &got, &per_q(&routed), &kids, &keys, &value);
|
|
}
|
|
}
|
|
}
|