Files
leleka/crates/cuda-driver/tests/q5_gpu.rs
T

314 lines
11 KiB
Rust

#![cfg(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))]
#[path = "q5_oracle.rs"]
mod oracle;
use leleka_cuda_driver::{Context, DeviceBuffer, Driver, Error, Q5KProjectionShape};
use std::{
fs,
path::{Path, PathBuf},
process::Command,
};
fn upload<'a>(ctx: &'a Context<'_>, data: &[u8]) -> DeviceBuffer<'a> {
let mut b = ctx.allocate(data.len()).unwrap();
b.copy_from(data).unwrap();
b
}
fn read(b: &DeviceBuffer<'_>) -> Vec<u8> {
let mut x = vec![0; b.len()];
b.copy_to(&mut x).unwrap();
x
}
fn compare_output(actual: &[u8], expected: &[u8]) {
assert_eq!(actual.len(), expected.len());
for (i, (a, b)) in actual
.as_chunks::<4>()
.0
.iter()
.zip(expected.as_chunks::<4>().0.iter())
.enumerate()
{
let a = u32::from_le_bytes(*a);
let b = u32::from_le_bytes(*b);
if f32::from_bits(b).is_nan() {
assert!(f32::from_bits(a).is_nan(), "row {i} NaN classification");
} else {
assert_eq!(a, b, "row {i} native exactbits");
}
}
}
fn run_case(
ctx: &Context<'_>,
root: &Path,
native: &Path,
ptx: &Path,
rows: usize,
columns: usize,
pattern: usize,
) {
let w = oracle::weights(rows, columns, pattern);
let x = oracle::activation(columns, pattern);
let xb = oracle::f32bytes(&x);
let stem = format!("m{rows}-n{columns}-p{pattern}");
let input = root.join(format!("{stem}.input"));
let result = root.join(format!("{stem}.native"));
let mut data = Vec::new();
for h in [0x35314b51, rows as u32, columns as u32] {
data.extend_from_slice(&h.to_le_bytes());
}
data.extend_from_slice(&w);
data.extend_from_slice(&xb);
fs::write(&input, &data).unwrap();
let output = Command::new("timeout")
.args(["--signal=TERM", "--kill-after=5", "30"])
.arg(native)
.arg(&input)
.arg(&result)
.arg(ptx)
.output()
.unwrap();
fs::write(root.join(format!("{stem}.stdout")), &output.stdout).unwrap();
fs::write(root.join(format!("{stem}.stderr")), &output.stderr).unwrap();
assert!(
output.status.success(),
"native {stem}: {}",
String::from_utf8_lossy(&output.stderr)
);
let expected = fs::read(&result).unwrap();
let qb = columns / 32 * 36;
assert_eq!(expected.len(), 16 + 2 * qb + rows * 4);
assert_eq!(
u32::from_le_bytes(expected[0..4].try_into().unwrap()),
0x35314f51
);
assert_eq!(&expected[4..8], &(rows as u32).to_le_bytes());
assert_eq!(&expected[8..12], &(columns as u32).to_le_bytes());
assert_eq!(
&expected[12..16],
&0u32.to_le_bytes(),
"native-math activation admission"
);
let nativeq = &expected[16..16 + qb];
let candidateq = &expected[16 + qb..16 + 2 * qb];
assert_eq!(
candidateq, nativeq,
"all independently quantized Q8 bytes {stem}"
);
if pattern == 1 {
for block in nativeq.as_chunks::<36>().0.iter() {
assert_eq!(&block[..4], &[0, 0x3c, 0, 0]);
assert_eq!(&block[4..8], &[127, 129, 1, 255]);
assert!(block[8..].iter().all(|&v| v == 0));
}
}
if pattern == 2 || pattern == 3 {
for block in nativeq.as_chunks::<36>().0.iter() {
assert_eq!(&block[..2], &[0, 0]);
assert_eq!(&block[2..4], if pattern == 3 { &[0, 128] } else { &[0, 0] });
assert!(block[4..].iter().all(|&v| v == 0));
}
}
if pattern == 7 {
for word in expected[16 + 2 * qb..].as_chunks::<4>().0.iter() {
assert_eq!(
f32::from_le_bytes(*word),
959104.0 * (columns / 256) as f32,
"independent hand projection"
);
}
}
let dw = upload(ctx, &w);
let dx = upload(ctx, &xb);
let sentinel = vec![0xa5; rows * 4];
let mut dy = upload(ctx, &sentinel);
let charged = ctx.allocated_bytes();
ctx.q5_k_q8_1(&dw, &dx, &mut dy, Q5KProjectionShape { rows, columns })
.expect("safe resident public projection");
let actual = read(&dy);
compare_output(&actual, &expected[16 + 2 * qb..]);
assert_eq!(read(&dw), w, "compressed weights immutable");
assert_eq!(read(&dx), xb, "resident activation immutable");
assert_eq!(ctx.allocated_bytes(), charged, "healthy temporary cleanup");
// Repeat proves the public cache path and stable ownership, against the SAME
// frozen native result, not a first candidate run used as a baseline.
ctx.q5_k_q8_1(&dw, &dx, &mut dy, Q5KProjectionShape { rows, columns })
.unwrap();
compare_output(&read(&dy), &expected[16 + 2 * qb..]);
fs::write(root.join(format!("{stem}.actual")), &actual).unwrap();
dw.release().unwrap();
dx.release().unwrap();
dy.release().unwrap();
assert_eq!(ctx.allocated_bytes(), 0);
println!(
"Q5_NATIVE PASS {stem} q8_bytes={qb} outputs={rows} exactbits=true repeat=true cleanup=0"
);
}
#[test]
#[ignore = "requires installed NVIDIA GPU, pinned independent native fixture and explicit private evidence root"]
fn installed_driver_q5_native_parity() {
assert_eq!(std::env::var("LELEKA_CUDA_REAL_GPU").as_deref(), Ok("1"));
let root = PathBuf::from(std::env::var("LELEKA_Q5_EVIDENCE").unwrap());
let native = PathBuf::from(std::env::var("LELEKA_Q5_NATIVE_ORACLE").unwrap());
let ptx = PathBuf::from(std::env::var("LELEKA_Q5_TRUSTED_PTX").unwrap());
assert!(root.is_absolute() && native.is_absolute() && ptx.is_absolute());
fs::create_dir_all(&root).unwrap();
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let ctx = device.create_context(1 << 20).unwrap();
for rows in [1, 3, 4, 5] {
for columns in [256, 512, 2048, 2560, 6144] {
run_case(&ctx, &root, &native, &ptx, rows, columns, 0);
}
}
for pattern in 1..=6 {
run_case(&ctx, &root, &native, &ptx, 5, 6144, pattern);
}
for pattern in 7..=9 {
run_case(&ctx, &root, &native, &ptx, 3, 256, pattern);
}
ctx.close().unwrap();
println!(
"Q5_PARITY_SUMMARY cases=29 public_launches=58 q8_exact=true outputs_exact=true context_close=ok"
);
}
#[test]
#[ignore = "requires installed NVIDIA driver, explicit opt-in"]
fn installed_driver_q5_numeric_refusals() {
assert_eq!(std::env::var("LELEKA_CUDA_REAL_GPU").as_deref(), Ok("1"));
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let ctx = device.create_context(1 << 20).unwrap();
let w = oracle::weights(1, 256, 0);
let dw = upload(&ctx, &w);
let sentinel = vec![0xa5; 4];
let mut dy = upload(&ctx, &sentinel);
let cases = [
("nan", f32::NAN),
("positive_inf", f32::INFINITY),
("negative_inf", f32::NEG_INFINITY),
("half_sum_overflow", 4096.0),
("scale_overflow", f32::MAX),
("flushed_nonzero_divisor", f32::MIN_POSITIVE),
];
for (name, value) in cases {
let mut x = vec![0.0; 256];
if name == "half_sum_overflow" {
x[..32].fill(value);
} else {
x[0] = value;
}
let xb = oracle::f32bytes(&x);
let dx = upload(&ctx, &xb);
let charged = ctx.allocated_bytes();
assert_eq!(
ctx.q5_k_q8_1(
&dw,
&dx,
&mut dy,
Q5KProjectionShape {
rows: 1,
columns: 256
}
),
Err(Error::InvalidQ8Activation),
"{name}"
);
assert_eq!(read(&dy), sentinel, "{name} output untouched");
assert_eq!(read(&dx), xb);
assert_eq!(ctx.allocated_bytes(), charged);
ctx.synchronize().unwrap();
dx.release().unwrap();
println!("Q5_REFUSAL PASS {name} output_unchanged=true healthy=true");
}
dw.release().unwrap();
dy.release().unwrap();
assert_eq!(ctx.allocated_bytes(), 0);
ctx.close().unwrap();
}
#[test]
#[ignore = "one explicitly selected private Qwen Q5_K tensor; synthetic activation; no model-forward claim"]
fn installed_driver_q5_real_tensor_component() {
assert_eq!(std::env::var("LELEKA_CUDA_REAL_GPU").as_deref(), Ok("1"));
let root = PathBuf::from(std::env::var("LELEKA_Q5_EVIDENCE").unwrap());
let input = PathBuf::from(std::env::var("LELEKA_Q5_REAL_INPUT").unwrap());
let native = PathBuf::from(std::env::var("LELEKA_Q5_NATIVE_ORACLE").unwrap());
let ptx = PathBuf::from(std::env::var("LELEKA_Q5_TRUSTED_PTX").unwrap());
assert!(root.is_absolute() && input.is_absolute() && native.is_absolute() && ptx.is_absolute());
fs::create_dir_all(&root).unwrap();
let data = fs::read(&input).unwrap();
let (m, n) = (640usize, 2560usize);
let wb = m * (n / 256) * 176;
let xb = n * 4;
let qb = n / 32 * 36;
assert_eq!(data.len(), 12 + wb + xb);
assert_eq!(&data[..4], &0x35314b51u32.to_le_bytes());
assert_eq!(&data[4..8], &(m as u32).to_le_bytes());
assert_eq!(&data[8..12], &(n as u32).to_le_bytes());
// Synthetic activation must equal our independent deterministic input,
// rather than a captured request or an arbitrary external fixture.
assert_eq!(
&data[12 + wb..],
oracle::f32bytes(&oracle::activation(n, 0))
);
let result = root.join("real-qwen-q5.native");
let out = Command::new("timeout")
.args(["--signal=TERM", "--kill-after=5", "30"])
.arg(native)
.arg(&input)
.arg(&result)
.arg(ptx)
.output()
.unwrap();
fs::write(root.join("real-qwen-q5.stdout"), &out.stdout).unwrap();
fs::write(root.join("real-qwen-q5.stderr"), &out.stderr).unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let expected = fs::read(result).unwrap();
assert_eq!(expected.len(), 16 + 2 * qb + m * 4);
assert_eq!(&expected[..4], &0x35314f51u32.to_le_bytes());
assert_eq!(&expected[12..16], &0u32.to_le_bytes());
assert_eq!(
&expected[16..16 + qb],
&expected[16 + qb..16 + 2 * qb],
"separate fresh Q8 bytes"
);
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let ctx = device.create_context(8 << 20).unwrap();
let w = upload(&ctx, &data[12..12 + wb]);
let x = upload(&ctx, &data[12 + wb..]);
let mut y = upload(&ctx, &vec![0xa5; m * 4]);
let resident = ctx.allocated_bytes();
for _ in 0..2 {
ctx.q5_k_q8_1(
&w,
&x,
&mut y,
Q5KProjectionShape {
rows: m,
columns: n,
},
)
.unwrap();
compare_output(&read(&y), &expected[16 + 2 * qb..]);
assert_eq!(ctx.allocated_bytes(), resident);
}
assert_eq!(read(&w), data[12..12 + wb]);
assert_eq!(read(&x), data[12 + wb..]);
fs::write(root.join("real-qwen-q5.actual"), read(&y)).unwrap();
w.release().unwrap();
x.release().unwrap();
y.release().unwrap();
assert_eq!(ctx.allocated_bytes(), 0);
ctx.close().unwrap();
println!(
"Q5_REAL_COMPONENT PASS tensor=blk.4.ffn_up_shexp.weight rows=640 columns=2560 packed_bytes=1126400 q8_bytes=2880 outputs=640 exactbits=true repeat=true synthetic_activation=true cleanup=0 scope=single_projection"
);
}