STRA-338 size2 cd1: experimental and closed program GPU smokes split into cases

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 22:25:00 +01:00
parent 2d5215bcda
commit 00eb77d05c
3 changed files with 397 additions and 252 deletions
@@ -49,85 +49,18 @@ fn closed_gpu_native_flash_attn_matches_the_fp64_specification() {
let ctx = driver.device(0).unwrap().create_context(128 << 20).unwrap();
{
let gpu = open(&ctx, Program::NativeFlashAttn);
let capacity = 256usize;
let mut worst = 0f64;
for width in [1usize, 2, 5, 31, 32, 33, 100, 128, 129, 255, 256] {
for with_mask in [false, true] {
let mut rng = Rng(0xf1a5_0000 + width as u64 * 2 + u64::from(with_mask));
let q: Vec<f32> = (0..24 * 256).map(|_| 0.8 * rng.normal()).collect();
let k: Vec<u16> = (0..capacity * 512).map(|_| f16_bits(rng.normal())).collect();
let v: Vec<u16> = (0..capacity * 512).map(|_| f16_bits(rng.normal())).collect();
let mask: Vec<u16> =
(0..256).map(|c| f16_bits(if with_mask { ((c * 7) % 5) as f32 * -0.5 } else { 0.0 })).collect();
let step = [width as i32 - 1, width as i32, width as i32 / 4, width as i32];
let bytes = |h: &[u16]| h.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>();
let (q_b, k_b, v_b) = (
upload(&ctx, &q.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>()),
upload(&ctx, &bytes(&k)),
upload(&ctx, &bytes(&v)),
);
let step_b = upload(&ctx, &step.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>());
let mask_b = upload(&ctx, &bytes(&mask));
let mut out_b = upload(&ctx, &vec![0xffu8; 24 * 256 * 4]);
let mut status_b = upload(&ctx, &(-1i32).to_le_bytes());
gpu.native_flash_attn_short(
&q_b,
&k_b,
&v_b,
&step_b,
with_mask.then_some(&mask_b),
capacity as i64,
2051,
256,
&mut out_b,
&mut status_b,
)
.unwrap();
assert_eq!(
i32::from_le_bytes(download(&status_b, 4)[..4].try_into().unwrap()),
flash::STATUS_SUCCESS,
"width {width}"
);
let out = f32s(&download(&out_b, 24 * 256 * 4));
let h2f = |b: u16| sg::f16_to_f32(b);
for head in 0..24 {
let kv = head / 12;
let kk: Vec<Vec<f32>> =
(0..width).map(|c| (0..256).map(|d| h2f(k[(c * 2 + kv) * 256 + d])).collect()).collect();
let vv: Vec<Vec<f32>> =
(0..width).map(|c| (0..256).map(|d| h2f(v[(c * 2 + kv) * 256 + d])).collect()).collect();
let m: Vec<f32> = (0..width).map(|c| h2f(mask[c])).collect();
let want =
flash::reference_head(&q[head * 256..(head + 1) * 256], &kk, &vv, with_mask.then_some(&m[..]));
let magnitude = want.iter().fold(1e-6f64, |a, w| a.max(f64::from(w.abs())));
for d in 0..256 {
worst = worst.max(f64::from((out[head * 256 + d] - want[d]).abs()) / magnitude);
}
}
let case = cases::FlashCase::random(width, with_mask);
let (status, out) = case.run(&ctx, &gpu);
assert_eq!(status, flash::STATUS_SUCCESS, "width {width}");
worst = worst.max(case.worst_error(&out));
}
}
println!("CLOSED native_flash_attn worst relative error {worst:.3e}");
assert!(worst < 5e-5, "worst relative error {worst}");
// an invalid step record is refused on the device: status 1 and a NaN output
let zeros = vec![0u8; 24 * 256 * 4];
let (q_b, kv_b) = (upload(&ctx, &zeros), upload(&ctx, &vec![0u8; 256 * 1024]));
let step_b = upload(&ctx, &[0u8; 16]);
let (mut out_b, mut status_b) = (upload(&ctx, &zeros), upload(&ctx, &0i32.to_le_bytes()));
gpu.native_flash_attn_short(
&q_b,
&kv_b,
&zero_kv(&ctx),
&step_b,
None,
256,
2051,
256,
&mut out_b,
&mut status_b,
)
.unwrap();
assert_eq!(i32::from_le_bytes(download(&status_b, 4)[..4].try_into().unwrap()), flash::STATUS_UNSUPPORTED_STEP);
assert!(f32s(&download(&out_b, 24 * 256 * 4)).iter().all(|x| x.is_nan()));
cases::assert_invalid_step_refused(&ctx, &gpu);
gpu.close().unwrap();
}
ctx.close().unwrap();
@@ -148,73 +81,10 @@ fn closed_gpu_s_gemv_matches_the_shim_executed_golden() {
let mut worst = 0f64;
let mut launches = 0;
for case in golden["cases"].as_array().unwrap() {
let name = case["name"].as_str().unwrap();
let form = SForm {
code_bits: case["bits"].as_i64().unwrap() as i32,
code_bias: case["bias"].as_i64().unwrap() as i32,
group_elems: case["group"].as_i64().unwrap() as i32,
codebook: if case["codebook"].as_i64().unwrap() == 1 { Codebook::Iq4Nl } else { Codebook::Affine },
has_offset: case["has_offset"].as_i64().unwrap() == 1,
act_kind: 0,
};
let (n_in, n_out) = (case["n_in"].as_i64().unwrap(), case["n_out"].as_i64().unwrap());
let exact = case["exact"].as_i64().unwrap() == 1;
let codes = upload(&ctx, &json_bytes(&case["codes"]));
let scales =
upload(&ctx, &json_f32(&case["scales"]).iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>());
let offset = form.has_offset.then(|| {
upload(&ctx, &json_f32(&case["offset"]).iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>())
});
let x16: Vec<u8> =
case["x"].as_array().unwrap().iter().flat_map(|v| (v.as_u64().unwrap() as u16).to_le_bytes()).collect();
let (x16_b, q8k, q80) = (upload(&ctx, &x16), json_bytes(&case["q8k"]), json_bytes(&case["q80"]));
let mut check = |what: &str, plan: sg::Plan, x: &DeviceBuffer<'_>, want: &[f32]| {
let mut y = upload(&ctx, &vec![0xffu8; n_out as usize * 4]);
if form.code_bits == 2 && matches!(plan.kernel, Kernel::S2Gemv | Kernel::S2GemvQuads | Kernel::S2GemvQ8)
{
gpu.s2_gemv(&plan, n_in, n_out, x, &codes, &scales, &mut y).unwrap();
} else {
gpu.s_gemv(&plan, &form, n_in, n_out, x, &codes, &scales, offset.as_ref(), &mut y).unwrap();
}
let got = f32s(&download(&y, n_out as usize * 4));
let magnitude = want.iter().fold(1e-6f64, |a, w| a.max(f64::from(w.abs())));
for (o, (g, w)) in got.iter().zip(want).enumerate() {
if exact {
assert_eq!(g.to_bits(), w.to_bits(), "{name} {what} row {o}");
}
worst = worst.max(f64::from((g - w).abs()) / magnitude);
}
launches += 1;
};
let y_fp16 = json_f32(&case["y_fp16"]);
let offset_present = form.has_offset;
if exact {
check("s_gemv", sg::plan_s_gemv(n_in, n_out, &form, offset_present).unwrap().unwrap(), &x16_b, &y_fp16);
}
check(
"s_gemv_split64",
sg::plan_s_gemv_split(n_in, n_out, &form, 64, offset_present).unwrap().unwrap(),
&x16_b,
&y_fp16,
);
if form.code_bits != 2 && !q8k.is_empty() {
let b = upload(&ctx, &q8k);
check(
"q8k_split",
sg::plan_s_gemv_q8k_split(n_in, n_out, &form).unwrap().unwrap(),
&b,
&json_f32(&case["y_q8k"]),
);
}
if form.code_bits != 2 && !q80.is_empty() {
let b = upload(&ctx, &q80);
check(
"q8_0_split",
sg::plan_s_gemv_q8_0_split(n_in, n_out, &form).unwrap().unwrap(),
&b,
&json_f32(&case["y_q80"]),
);
}
let mut replay = cases::Replay::new(&ctx, &gpu, case);
replay.run(case);
worst = worst.max(replay.worst);
launches += replay.launches;
}
println!("CLOSED s_gemv_legacy launches={launches} worst relative error {worst:.3e}");
assert!(worst < 1e-4, "worst relative error {worst}");
@@ -223,6 +93,8 @@ fn closed_gpu_s_gemv_matches_the_shim_executed_golden() {
ctx.close().unwrap();
}
#[path = "closed_kernels_gpu_smoke/cases.rs"]
mod cases;
#[path = "closed_kernels_gpu_smoke/impl_rng.rs"]
mod impl_rng;
#[allow(unused_imports)]
@@ -0,0 +1,186 @@
//! The cases of the closed-program smokes: one short FlashAttention case and one replayed S-form GEMV golden case.
#[allow(unused_imports)]
use super::*;
const CAPACITY: usize = 256;
fn half_bytes(h: &[u16]) -> Vec<u8> {
h.iter().flat_map(|x| x.to_le_bytes()).collect()
}
fn f32_bytes(v: &[f32]) -> Vec<u8> {
v.iter().flat_map(|x| x.to_le_bytes()).collect()
}
fn json_f32_bytes(v: &serde_json::Value) -> Vec<u8> {
f32_bytes(&json_f32(v))
}
/// Random inputs of one short FlashAttention case of `width` cells, with or without the additive mask.
pub(super) struct FlashCase {
q: Vec<f32>,
k: Vec<u16>,
v: Vec<u16>,
mask: Vec<u16>,
width: usize,
with_mask: bool,
}
impl FlashCase {
pub(super) fn random(width: usize, with_mask: bool) -> Self {
let mut rng = Rng(0xf1a5_0000 + width as u64 * 2 + u64::from(with_mask));
let q = (0..24 * 256).map(|_| 0.8 * rng.normal()).collect();
let k = (0..CAPACITY * 512).map(|_| f16_bits(rng.normal())).collect();
let v = (0..CAPACITY * 512).map(|_| f16_bits(rng.normal())).collect();
let mask = (0..256).map(|c| f16_bits(if with_mask { ((c * 7) % 5) as f32 * -0.5 } else { 0.0 })).collect();
Self { q, k, v, mask, width, with_mask }
}
/// The device's status word and output floats for this case.
pub(super) fn run<'c>(&self, ctx: &'c Context<'c>, gpu: &ClosedKernels<'c>) -> (i32, Vec<f32>) {
let width = self.width as i32;
let step = [width - 1, width, width / 4, width];
let (q_b, k_b, v_b) =
(upload(ctx, &f32_bytes(&self.q)), upload(ctx, &half_bytes(&self.k)), upload(ctx, &half_bytes(&self.v)));
let step_b = upload(ctx, &step.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>());
let mask_b = upload(ctx, &half_bytes(&self.mask));
let mut out_b = upload(ctx, &vec![0xffu8; 24 * 256 * 4]);
let mut status_b = upload(ctx, &(-1i32).to_le_bytes());
let mask = self.with_mask.then_some(&mask_b);
gpu.native_flash_attn_short(
&q_b,
&k_b,
&v_b,
&step_b,
mask,
CAPACITY as i64,
2051,
256,
&mut out_b,
&mut status_b,
)
.unwrap();
let status = i32::from_le_bytes(download(&status_b, 4)[..4].try_into().unwrap());
(status, f32s(&download(&out_b, 24 * 256 * 4)))
}
/// The worst error of `out` relative to the largest reference magnitude of its head, over all heads.
pub(super) fn worst_error(&self, out: &[f32]) -> f64 {
(0..24).fold(0f64, |worst, head| worst.max(self.head_error(out, head)))
}
/// The worst error of one head against the fp64 reference, relative to its largest reference magnitude.
fn head_error(&self, out: &[f32], head: usize) -> f64 {
let h2f = |b: u16| sg::f16_to_f32(b);
let (width, kv) = (self.width, head / 12);
let cells = |x: &[u16]| -> Vec<Vec<f32>> {
(0..width).map(|c| (0..256).map(|d| h2f(x[(c * 2 + kv) * 256 + d])).collect()).collect()
};
let (kk, vv) = (cells(&self.k), cells(&self.v));
let m: Vec<f32> = (0..width).map(|c| h2f(self.mask[c])).collect();
let q = &self.q[head * 256..(head + 1) * 256];
let want = flash::reference_head(q, &kk, &vv, self.with_mask.then_some(&m[..]));
let magnitude = want.iter().fold(1e-6f64, |a, w| a.max(f64::from(w.abs())));
(0..256).fold(0f64, |worst, d| worst.max(f64::from((out[head * 256 + d] - want[d]).abs()) / magnitude))
}
}
/// An invalid step record is refused on the device: status 1 and a NaN output.
pub(super) fn assert_invalid_step_refused<'c>(ctx: &'c Context<'c>, gpu: &ClosedKernels<'c>) {
let zeros = vec![0u8; 24 * 256 * 4];
let (q_b, kv_b) = (upload(ctx, &zeros), upload(ctx, &vec![0u8; 256 * 1024]));
let step_b = upload(ctx, &[0u8; 16]);
let (mut out_b, mut status_b) = (upload(ctx, &zeros), upload(ctx, &0i32.to_le_bytes()));
gpu.native_flash_attn_short(&q_b, &kv_b, &zero_kv(ctx), &step_b, None, 256, 2051, 256, &mut out_b, &mut status_b)
.unwrap();
assert_eq!(i32::from_le_bytes(download(&status_b, 4)[..4].try_into().unwrap()), flash::STATUS_UNSUPPORTED_STEP);
assert!(f32s(&download(&out_b, 24 * 256 * 4)).iter().all(|x| x.is_nan()));
}
fn golden_form(case: &serde_json::Value) -> SForm {
SForm {
code_bits: case["bits"].as_i64().unwrap() as i32,
code_bias: case["bias"].as_i64().unwrap() as i32,
group_elems: case["group"].as_i64().unwrap() as i32,
codebook: if case["codebook"].as_i64().unwrap() == 1 { Codebook::Iq4Nl } else { Codebook::Affine },
has_offset: case["has_offset"].as_i64().unwrap() == 1,
act_kind: 0,
}
}
/// One golden case of the S-form GEMVs replayed on the device, with the worst relative error of its launches.
pub(super) struct Replay<'a, 'c> {
ctx: &'c Context<'c>,
gpu: &'a ClosedKernels<'c>,
name: &'a str,
form: SForm,
n_in: i64,
n_out: i64,
exact: bool,
codes: DeviceBuffer<'c>,
scales: DeviceBuffer<'c>,
offset: Option<DeviceBuffer<'c>>,
pub(super) worst: f64,
pub(super) launches: usize,
}
impl<'a, 'c> Replay<'a, 'c> {
pub(super) fn new(ctx: &'c Context<'c>, gpu: &'a ClosedKernels<'c>, case: &'a serde_json::Value) -> Self {
let name = case["name"].as_str().unwrap();
let form = golden_form(case);
let (n_in, n_out) = (case["n_in"].as_i64().unwrap(), case["n_out"].as_i64().unwrap());
let exact = case["exact"].as_i64().unwrap() == 1;
let codes = upload(ctx, &json_bytes(&case["codes"]));
let scales = upload(ctx, &json_f32_bytes(&case["scales"]));
let offset = form.has_offset.then(|| upload(ctx, &json_f32_bytes(&case["offset"])));
Self { ctx, gpu, name, form, n_in, n_out, exact, codes, scales, offset, worst: 0.0, launches: 0 }
}
/// Launches the planned kernel on activation `x` and compares with `want`: bit for bit when the case is exact.
fn check(&mut self, what: &str, plan: sg::Plan, x: &DeviceBuffer<'_>, want: &[f32]) {
let (n_in, n_out) = (self.n_in, self.n_out);
let mut y = upload(self.ctx, &vec![0xffu8; n_out as usize * 4]);
let s2 = matches!(plan.kernel, Kernel::S2Gemv | Kernel::S2GemvQuads | Kernel::S2GemvQ8);
if self.form.code_bits == 2 && s2 {
self.gpu.s2_gemv(&plan, n_in, n_out, x, &self.codes, &self.scales, &mut y).unwrap();
} else {
let offset = self.offset.as_ref();
self.gpu.s_gemv(&plan, &self.form, n_in, n_out, x, &self.codes, &self.scales, offset, &mut y).unwrap();
}
let got = f32s(&download(&y, n_out as usize * 4));
let magnitude = want.iter().fold(1e-6f64, |a, w| a.max(f64::from(w.abs())));
for (o, (g, w)) in got.iter().zip(want).enumerate() {
if self.exact {
assert_eq!(g.to_bits(), w.to_bits(), "{} {what} row {o}", self.name);
}
self.worst = self.worst.max(f64::from((g - w).abs()) / magnitude);
}
self.launches += 1;
}
/// The fp16-activation launches, then the split launches over the case's `block_q8_K` / `block_q8_0` activations.
pub(super) fn run(&mut self, case: &serde_json::Value) {
let x16: Vec<u8> =
case["x"].as_array().unwrap().iter().flat_map(|v| (v.as_u64().unwrap() as u16).to_le_bytes()).collect();
let (x16_b, q8k, q80) = (upload(self.ctx, &x16), json_bytes(&case["q8k"]), json_bytes(&case["q80"]));
let (n_in, n_out, offset_present) = (self.n_in, self.n_out, self.form.has_offset);
let y_fp16 = json_f32(&case["y_fp16"]);
if self.exact {
let plan = sg::plan_s_gemv(n_in, n_out, &self.form, offset_present).unwrap().unwrap();
self.check("s_gemv", plan, &x16_b, &y_fp16);
}
let plan = sg::plan_s_gemv_split(n_in, n_out, &self.form, 64, offset_present).unwrap().unwrap();
self.check("s_gemv_split64", plan, &x16_b, &y_fp16);
if self.form.code_bits != 2 && !q8k.is_empty() {
let b = upload(self.ctx, &q8k);
let plan = sg::plan_s_gemv_q8k_split(n_in, n_out, &self.form).unwrap().unwrap();
self.check("q8k_split", plan, &b, &json_f32(&case["y_q8k"]));
}
if self.form.code_bits != 2 && !q80.is_empty() {
let b = upload(self.ctx, &q80);
let plan = sg::plan_s_gemv_q8_0_split(n_in, n_out, &self.form).unwrap().unwrap();
self.check("q8_0_split", plan, &b, &json_f32(&case["y_q80"]));
}
}
}
+200 -113
View File
@@ -89,6 +89,67 @@ fn experimental_gpu_fwht256_matches_cpu() {
}
ctx.close().unwrap();
}
/// Appends 13 cells through `q4_append_step`; returns the device pools and the cells for the CPU model.
fn append_cells<'c>(
ctx: &'c Context<'c>,
gpu: &Experimental<'c>,
p: &Paged,
table_b: &DeviceBuffer<'_>,
) -> (DeviceBuffer<'c>, DeviceBuffer<'c>, Vec<(i32, Vec<f32>, Vec<f32>)>) {
let mut rng = Rng(0x57a7_0002);
let n = 2 * 256;
let mut cells = Vec::new();
let (mut k_b, mut v_b) = (zeroed(ctx, p.shape.q4_bytes(4) as usize), zeroed(ctx, p.shape.q4_bytes(4) as usize));
for pos in 0..13i32 {
let kc: Vec<f32> = (0..n).map(|_| rng.unit()).collect();
let vc: Vec<f32> = (0..n).map(|_| rng.unit()).collect();
let step = upload(ctx, &i32_bytes(&[pos, 0, 0, 0]));
let (kb, vb) = (upload(ctx, &f32_bytes(&kc)), upload(ctx, &f32_bytes(&vc)));
gpu.q4_append_step(p, &mut k_b, &mut v_b, table_b, &step, &kb, &vb).unwrap();
cells.push((pos, kc, vc));
}
(k_b, v_b, cells)
}
/// The CPU pools after the same cells under the first contraction model (fused, else separate) that reproduces the
/// device bytes; `"none"` with fresh pools when neither does.
fn matching_model(
p: &Paged,
q: &QsaShapes,
table: &[i32],
cells: &[(i32, Vec<f32>, Vec<f32>)],
got: (&[u8], &[u8]),
) -> (&'static str, PoolSet) {
for (name, c) in [("fused", Contraction::Fused), ("separate", Contraction::Separate)] {
let mut m = PoolSet::new(KvFormat::Q4_0, q, p.shape.rows(p.pages)).unwrap();
for (pos, kc, vc) in cells {
append_cell(KvFormat::Q4_0, &mut m, None, table, i64::from(*pos), kc, vc, q, c).unwrap();
}
if m.k_q4 == got.0 && m.v_q4 == got.1 {
return (name, m);
}
}
("none", PoolSet::new(KvFormat::Q4_0, q, p.shape.rows(p.pages)).unwrap())
}
/// Gathers cells 0, 3, 5, 7, 9, 12 on the device and compares the fp16 K bits with the CPU gather.
fn assert_q4_gather<'c>(
ctx: &'c Context<'c>,
gpu: &Experimental<'c>,
p: &Paged,
pools: [&DeviceBuffer<'_>; 4],
cpu: (&PoolSet, &[i32], &QsaShapes),
) {
let [k_b, v_b, table_b, ids_b] = pools;
let ids = [0, 3, 5, 7, 9, 12];
let step = upload(ctx, &i32_bytes(&[0, 13, 0, 6]));
let scratch = p.shape.gather_scratch_bytes(6) as usize;
let (mut ks, mut vs) = (zeroed(ctx, scratch), zeroed(ctx, scratch));
gpu.q4_gather_step(p, k_b, v_b, table_b, ids_b, &step, 6, &mut ks, &mut vs).unwrap();
let want_k = gather_q4(&cpu.0.k_q4, cpu.1, &ids, cpu.2).unwrap();
let got: Vec<u16> = download(&ks, scratch).chunks(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect();
assert_eq!(got, want_k, "gathered fp16 K bits");
}
#[test]
#[ignore = "Root schedules the first experimental GPU gate after nvcc build and pin freeze"]
@@ -100,47 +161,15 @@ fn experimental_gpu_q4_append_and_gather_match_cpu() {
let q = QsaShapes::real();
let p = Paged { shape: KvShape::real(), pages: 4, table_entries: 4 };
let table: Vec<i32> = vec![0, 1, 2, 3];
let mut rng = Rng(0x57a7_0002);
let n = 2 * 256;
let mut cpu = PoolSet::new(KvFormat::Q4_0, &q, p.shape.rows(p.pages)).unwrap();
let mut cells = Vec::new();
let (mut k_b, mut v_b) =
(zeroed(&ctx, p.shape.q4_bytes(4) as usize), zeroed(&ctx, p.shape.q4_bytes(4) as usize));
let (table_b, ids_b) = (upload(&ctx, &i32_bytes(&table)), upload(&ctx, &i32_bytes(&[0, 3, 5, 7, 9, 12])));
for pos in 0..13i32 {
let kc: Vec<f32> = (0..n).map(|_| rng.unit()).collect();
let vc: Vec<f32> = (0..n).map(|_| rng.unit()).collect();
let step = upload(&ctx, &i32_bytes(&[pos, 0, 0, 0]));
let (kb, vb) = (upload(&ctx, &f32_bytes(&kc)), upload(&ctx, &f32_bytes(&vc)));
gpu.q4_append_step(&p, &mut k_b, &mut v_b, &table_b, &step, &kb, &vb).unwrap();
cells.push((pos, kc, vc));
}
let (k_b, v_b, cells) = append_cells(&ctx, &gpu, &p, &table_b);
let got_k = download(&k_b, p.shape.q4_bytes(4) as usize);
let got_v = download(&v_b, p.shape.q4_bytes(4) as usize);
// nvcc contracts a*b+c; the Fused model is the expectation, Separate the fallback we report.
let mut which = "none";
for (name, c) in [("fused", Contraction::Fused), ("separate", Contraction::Separate)] {
let mut m = PoolSet::new(KvFormat::Q4_0, &q, p.shape.rows(p.pages)).unwrap();
for (pos, kc, vc) in &cells {
append_cell(KvFormat::Q4_0, &mut m, None, &table, i64::from(*pos), kc, vc, &q, c).unwrap();
}
if m.k_q4 == got_k && m.v_q4 == got_v {
which = name;
cpu = m;
break;
}
}
let (which, cpu) = matching_model(&p, &q, &table, &cells, (&got_k, &got_v));
assert_ne!(which, "none", "device Q4_0 pools differ from both contraction models");
println!("EXPERIMENTAL q4_append cells=13 matches={which}");
// gather
let ids = [0, 3, 5, 7, 9, 12];
let step = upload(&ctx, &i32_bytes(&[0, 13, 0, 6]));
let scratch = p.shape.gather_scratch_bytes(6) as usize;
let (mut ks, mut vs) = (zeroed(&ctx, scratch), zeroed(&ctx, scratch));
gpu.q4_gather_step(&p, &k_b, &v_b, &table_b, &ids_b, &step, 6, &mut ks, &mut vs).unwrap();
let want_k = gather_q4(&cpu.k_q4, &table, &ids, &q).unwrap();
let got: Vec<u16> = download(&ks, scratch).chunks(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect();
assert_eq!(got, want_k, "gathered fp16 K bits");
assert_q4_gather(&ctx, &gpu, &p, [&k_b, &v_b, &table_b, &ids_b], (&cpu, &table, &q));
gpu.close().unwrap();
}
ctx.close().unwrap();
@@ -170,6 +199,134 @@ fn experimental_gpu_keyless_route_matches_cpu() {
ctx.close().unwrap();
}
const STREAM_BLOCKS: u64 = 4096;
const STREAM_SLOTS: u64 = 1024;
const STREAM_QUERIES: u64 = 2;
const STREAM_CAP: u64 = 64;
/// The seven device buffers of one streamed layer's residency map.
struct MapBuffers<'c> {
page_table: DeviceBuffer<'c>,
slot_block: DeviceBuffer<'c>,
slot_stamp: DeviceBuffer<'c>,
slot_ref: DeviceBuffer<'c>,
ctl: DeviceBuffer<'c>,
miss_block: DeviceBuffer<'c>,
miss_slot: DeviceBuffer<'c>,
}
impl<'c> MapBuffers<'c> {
fn new(ctx: &'c Context<'c>) -> Self {
let slots = STREAM_SLOTS as usize;
Self {
page_table: upload(ctx, &i32_bytes(&vec![-1; STREAM_BLOCKS as usize])),
slot_block: zeroed(ctx, slots * 4),
slot_stamp: zeroed(ctx, slots * 4),
slot_ref: zeroed(ctx, slots * 4),
ctl: zeroed(ctx, CTL_INTS * 4),
miss_block: zeroed(ctx, slots * 4),
miss_slot: zeroed(ctx, slots * 4),
}
}
fn map(&mut self) -> StreamMap<'_, 'c> {
StreamMap {
page_table: &mut self.page_table,
slot_block: &mut self.slot_block,
slot_stamp: &mut self.slot_stamp,
slot_ref: &mut self.slot_ref,
ctl: &mut self.ctl,
miss_block: &mut self.miss_block,
miss_slot: &mut self.miss_slot,
}
}
}
/// Two queries, ascending cell ids; a cell is page_size = 4 per block.
fn resolve_inputs() -> (Vec<i32>, Vec<i32>) {
let width = STREAM_CAP as i32;
let mut ids = Vec::new();
let mut steps = Vec::new();
for qi in 0..STREAM_QUERIES as i32 {
ids.extend((0..STREAM_CAP as i32).map(|i| i * 4 + qi * 8));
steps.extend([STREAM_CAP as i32 * 4, 0, 0, width]);
}
(ids, steps)
}
/// Uploads the ids and step records and runs `stream_resolve` (+ copy) over the host arrays into the slot arrays.
fn resolve_on_device<'c>(
ctx: &'c Context<'c>,
gpu: &Experimental<'c>,
buffers: &mut MapBuffers<'c>,
host: &[DeviceBuffer<'c>],
slots: &mut [DeviceBuffer<'c>],
inputs: (&[i32], &[i32]),
) {
let (ids_b, steps_b) = (upload(ctx, &i32_bytes(inputs.0)), upload(ctx, &i32_bytes(inputs.1)));
let host_refs: Vec<&DeviceBuffer<'_>> = host.iter().collect();
let mut slot_refs: Vec<&mut DeviceBuffer<'_>> = slots.iter_mut().collect();
gpu.stream_resolve(
&mut buffers.map(),
StreamFormat::F16,
&KvShape::real(),
STREAM_BLOCKS,
STREAM_SLOTS,
&ids_b,
&steps_b,
STREAM_QUERIES,
STREAM_CAP,
&host_refs,
&mut slot_refs,
)
.unwrap();
}
/// Block `b` sits in slot `slot` of every array, byte for byte as in the host array.
fn assert_block_copied(
slots: &[DeviceBuffer<'_>],
host_bytes: &[Vec<u8>],
runs: &[(&'static str, u64)],
at: (usize, usize),
) {
let (b, slot) = at;
for (i, (_, len)) in runs.iter().enumerate() {
let len = *len as usize;
let got = download(&slots[i], (STREAM_SLOTS as usize) * len);
assert_eq!(&got[slot * len..(slot + 1) * len], &host_bytes[i][b * len..(b + 1) * len], "block {b} array {i}");
}
}
/// The CPU model sees the same distinct blocks (same miss count, consistent residency map) and the copies landed.
fn assert_resolved_like_cpu(
buffers: &MapBuffers<'_>,
slots: &[DeviceBuffer<'_>],
host_bytes: &[Vec<u8>],
runs: &[(&'static str, u64)],
inputs: (&[i32], &[i32]),
) {
let mut cpu = CpuMap::new(STREAM_BLOCKS as usize, STREAM_SLOTS as usize);
let report = cpu
.resolve(
inputs.0,
inputs.1,
STREAM_QUERIES as usize,
STREAM_CAP as usize,
4,
&leleka_experimental_ref::kv_stream::MissOrder::Canonical,
)
.expect("cpu resolve");
let _ = report;
let table = download(&buffers.page_table, STREAM_BLOCKS as usize * 4);
let table: Vec<i32> = table.chunks(4).map(|b| i32::from_le_bytes(b.try_into().unwrap())).collect();
let resident: Vec<usize> = (0..STREAM_BLOCKS as usize).filter(|b| table[*b] >= 0).collect();
assert_eq!(resident.len(), cpu.resident_blocks(), "same set of distinct blocks resident");
for b in resident {
assert_block_copied(slots, host_bytes, runs, (b, table[b] as usize));
}
println!("EXPERIMENTAL kv_stream resolve+copy resident={}", cpu.resident_blocks());
}
#[test]
#[ignore = "Root schedules the first experimental GPU gate after nvcc build and pin freeze"]
fn experimental_gpu_stream_resolve_copies_missed_blocks() {
@@ -177,88 +334,18 @@ fn experimental_gpu_stream_resolve_copies_missed_blocks() {
let ctx = driver.device(0).unwrap().create_context(512 << 20).unwrap();
{
let gpu = open(&ctx, Program::KvStream, Mode::KvStreamed);
let shape = KvShape::real();
let q = QsaShapes::real();
let (n_blocks, n_slots, n_q, cap) = (4096u64, 1024u64, 2u64, 64u64);
let runs = stream_runs(&q, StreamFormat::F16);
let runs = stream_runs(&QsaShapes::real(), StreamFormat::F16);
let mut rng = Rng(0x57a7_0004);
let host_bytes: Vec<Vec<u8>> =
runs.iter().map(|(_, len)| (0..n_blocks * len).map(|_| rng.next() as u8).collect()).collect();
runs.iter().map(|(_, len)| (0..STREAM_BLOCKS * len).map(|_| rng.next() as u8).collect()).collect();
let host: Vec<DeviceBuffer<'_>> = host_bytes.iter().map(|b| upload(&ctx, b)).collect();
let mut slots: Vec<DeviceBuffer<'_>> =
runs.iter().map(|(_, len)| zeroed(&ctx, (n_slots * len) as usize)).collect();
let mut page_table = upload(&ctx, &i32_bytes(&vec![-1; n_blocks as usize]));
let mut slot_block = zeroed(&ctx, n_slots as usize * 4);
let mut slot_stamp = zeroed(&ctx, n_slots as usize * 4);
let mut slot_ref = zeroed(&ctx, n_slots as usize * 4);
let mut ctl = zeroed(&ctx, CTL_INTS * 4);
let mut miss_block = zeroed(&ctx, n_slots as usize * 4);
let mut miss_slot = zeroed(&ctx, n_slots as usize * 4);
let mut map = StreamMap {
page_table: &mut page_table,
slot_block: &mut slot_block,
slot_stamp: &mut slot_stamp,
slot_ref: &mut slot_ref,
ctl: &mut ctl,
miss_block: &mut miss_block,
miss_slot: &mut miss_slot,
};
gpu.stream_reset(&mut map, n_blocks, n_slots).unwrap();
// two queries, ascending cell ids; a cell is page_size = 4 per block
let width = cap as i32;
let mut ids = Vec::new();
let mut steps = Vec::new();
for qi in 0..n_q as i32 {
ids.extend((0..cap as i32).map(|i| i * 4 + qi * 8));
steps.extend([cap as i32 * 4, 0, 0, width]);
}
let (ids_b, steps_b) = (upload(&ctx, &i32_bytes(&ids)), upload(&ctx, &i32_bytes(&steps)));
let host_refs: Vec<&DeviceBuffer<'_>> = host.iter().collect();
let mut slot_refs: Vec<&mut DeviceBuffer<'_>> = slots.iter_mut().collect();
gpu.stream_resolve(
&mut map,
StreamFormat::F16,
&shape,
n_blocks,
n_slots,
&ids_b,
&steps_b,
n_q,
cap,
&host_refs,
&mut slot_refs,
)
.unwrap();
// CPU model: same distinct blocks, so the same miss count and a consistent residency map
let mut cpu = CpuMap::new(n_blocks as usize, n_slots as usize);
let report = cpu
.resolve(
&ids,
&steps,
n_q as usize,
cap as usize,
4,
&leleka_experimental_ref::kv_stream::MissOrder::Canonical,
)
.expect("cpu resolve");
let _ = report;
let table = download(&*map.page_table, n_blocks as usize * 4);
let table: Vec<i32> = table.chunks(4).map(|b| i32::from_le_bytes(b.try_into().unwrap())).collect();
let resident: Vec<usize> = (0..n_blocks as usize).filter(|b| table[*b] >= 0).collect();
assert_eq!(resident.len(), cpu.resident_blocks(), "same set of distinct blocks resident");
for b in resident {
let slot = table[b] as usize;
for (i, (_, len)) in runs.iter().enumerate() {
let len = *len as usize;
let got = download(&slots[i], (n_slots as usize) * len);
assert_eq!(
&got[slot * len..(slot + 1) * len],
&host_bytes[i][b * len..(b + 1) * len],
"block {b} array {i}"
);
}
}
println!("EXPERIMENTAL kv_stream resolve+copy resident={}", cpu.resident_blocks());
runs.iter().map(|(_, len)| zeroed(&ctx, (STREAM_SLOTS * len) as usize)).collect();
let mut buffers = MapBuffers::new(&ctx);
gpu.stream_reset(&mut buffers.map(), STREAM_BLOCKS, STREAM_SLOTS).unwrap();
let (ids, steps) = resolve_inputs();
resolve_on_device(&ctx, &gpu, &mut buffers, &host, &mut slots, (&ids, &steps));
assert_resolved_like_cpu(&buffers, &slots, &host_bytes, &runs, (&ids, &steps));
gpu.close().unwrap();
}
ctx.close().unwrap();