From 88401e166330d214a864649253b5001fb7558af7 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 14 Oct 2026 16:56:27 +0200 Subject: [PATCH] test(kar): run the real kar_decode_levels.cu on the CPU against the kernel model nvcc and a GPU are unavailable, and the kernel's only executable evidence was a Rust transcription of it. This harness compiles the actual .cu with clang through a small shim (threads for CUDA threads, a barrier for __syncthreads, atomics for atomicOr) and replays model-generated cases: random valid windows at levels 2..5, non-finite scales/books, ~1k corrupted launch-parameter sets, multiply and SwiGLU. 17k cases (ASan build included) agree bit for bit; this does not cover nvcc codegen or device behaviour. Co-Authored-By: Claude Sonnet 5.5 --- crates/cuda-driver/emulation/main.cpp | 66 ++++++++ crates/cuda-driver/emulation/run.sh | 19 +++ crates/cuda-driver/emulation/shim/cuda_fp16.h | 5 + crates/cuda-driver/emulation/shim/cuda_shim.h | 37 +++++ crates/model-format/examples/kar_cases.rs | 157 ++++++++++++++++++ 5 files changed, 284 insertions(+) create mode 100644 crates/cuda-driver/emulation/main.cpp create mode 100755 crates/cuda-driver/emulation/run.sh create mode 100644 crates/cuda-driver/emulation/shim/cuda_fp16.h create mode 100644 crates/cuda-driver/emulation/shim/cuda_shim.h create mode 100644 crates/model-format/examples/kar_cases.rs diff --git a/crates/cuda-driver/emulation/main.cpp b/crates/cuda-driver/emulation/main.cpp new file mode 100644 index 00000000..b193cf92 --- /dev/null +++ b/crates/cuda-driver/emulation/main.cpp @@ -0,0 +1,66 @@ +#include "../src/kar_decode_levels.cu" +#include +#include +#include +#include +static std::vector W; +static size_t pos = 0; +static uint32_t rd() { if (pos >= W.size()) { fprintf(stderr, "truncated case file\n"); exit(2); } return W[pos++]; } +int main(int argc, char** argv) { + FILE* f = fopen(argv[1], "rb"); if (!f) return 2; + fseek(f, 0, SEEK_END); long n = ftell(f); fseek(f, 0, SEEK_SET); + W.resize(n / 4); if (fread(W.data(), 4, W.size(), f) != W.size()) return 2; fclose(f); + uint32_t ncases = rd(); unsigned bad = 0, skipped = 0; + for (uint32_t c = 0; c < ncases; ++c) { + uint32_t kind = rd(); + if (kind == 0) { + uint32_t s[12]; for (auto& v : s) v = rd(); + uint32_t grid = rd(), block = rd(), packet_len = rd(); + uint8_t* packet = (uint8_t*)malloc(packet_len ? packet_len : 1); + for (uint32_t i = 0; i < packet_len; ++i) packet[i] = (W[pos + i / 4] >> (8 * (i % 4))) & 255; + pos += (packet_len + 3) / 4; + uint32_t out_words = rd(), exp_status = rd(); + float* out = (float*)malloc(out_words * 4 + 4); + uint32_t* ob = (uint32_t*)out; for (uint32_t i = 0; i < out_words; ++i) ob[i] = 0xdeadbeef; + uint32_t* status = (uint32_t*)malloc(4); *status = 0; + std::vector expect(out_words); for (auto& v : expect) v = rd(); + if (grid == 0) grid = (s[2] + 255) / 256; + if (block == 0) block = 256; + launch(dim3(grid), dim3(block), [&] { leleka_kar_decode_levels_f32(packet, out, status, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11]); }); + bool ok = *status == exp_status || (exp_status == 1 && packet_len < s[11]); + if (exp_status == 1 && packet_len < s[11]) { ++skipped; free(packet); free(out); free(status); continue; } + for (uint32_t i = 0; i < out_words && ok; ++i) if (ob[i] != expect[i]) { ok = false; fprintf(stderr, "case %u decode element %u: got %08x want %08x\n", c, i, ob[i], expect[i]); } + if (!ok) { ++bad; fprintf(stderr, "case %u decode FAIL status got %u want %u params %u %u %u %u %u %u %u %u %u %u %u %u packet_len %u\n", c, *status, exp_status, s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8],s[9],s[10],s[11], packet_len); } + free(packet); free(out); free(status); + } else if (kind == 1) { + uint32_t cols = rd(), rows = rd(), tokens = rd(), gx = rd(), gy = rd(); + std::vector wts(cols * (size_t)rows), inp(cols * (size_t)tokens); + for (auto& v : wts) v = rd(); for (auto& v : inp) v = rd(); + uint32_t exp_status = rd(), out_words = rd(); + std::vector expect(out_words); for (auto& v : expect) v = rd(); + std::vector out(out_words, 0xdeadbeef); uint32_t* status = (uint32_t*)malloc(4); *status = 0; + if (gx == 0) gx = rows; if (gy == 0) gy = tokens; + launch(dim3(gx, gy), dim3(256), [&] { leleka_kar_multiply_f32((const float*)wts.data(), (const float*)inp.data(), (float*)out.data(), status, cols, rows); }); + bool ok = *status == exp_status; + for (uint32_t i = 0; i < out_words && ok; ++i) if (out[i] != expect[i]) { ok = false; fprintf(stderr, "case %u mul element %u: got %08x want %08x\n", c, i, out[i], expect[i]); } + if (!ok) { ++bad; fprintf(stderr, "case %u multiply FAIL status got %u want %u\n", c, *status, exp_status); } + free(status); + } else { + uint32_t values = rd(); + std::vector g(values), u(values), e(values); + for (auto& v : g) v = rd(); for (auto& v : u) v = rd(); + uint32_t exp_status = rd(); for (auto& v : e) v = rd(); + std::vector out(values, 0xdeadbeef); uint32_t* status = (uint32_t*)malloc(4); *status = 0; + launch(dim3((values + 255) / 256), dim3(256), [&] { leleka_kar_swiglu_f32((const float*)g.data(), (const float*)u.data(), (float*)out.data(), status, values); }); + bool ok = *status == exp_status; + for (uint32_t i = 0; i < values && ok; ++i) { + float a, b; memcpy(&a, &out[i], 4); memcpy(&b, &e[i], 4); + if (!(std::fabs(a - b) <= 2e-6f * std::fmax(1.0f, std::fabs(b)))) { ok = false; fprintf(stderr, "case %u swiglu element %u: got %g want %g\n", c, i, a, b); } + } + if (!ok) { ++bad; fprintf(stderr, "case %u swiglu FAIL status got %u want %u\n", c, *status, exp_status); } + free(status); + } + } + printf("%u cases, %u failures, %u skipped (packet shorter than claimed)\n", ncases, bad, skipped); + return bad ? 1 : 0; +} diff --git a/crates/cuda-driver/emulation/run.sh b/crates/cuda-driver/emulation/run.sh new file mode 100755 index 00000000..900abd90 --- /dev/null +++ b/crates/cuda-driver/emulation/run.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# Runs the REAL kar_decode_levels.cu (not a port of it) on the CPU: every CUDA +# thread becomes an OS thread, __syncthreads a barrier, atomicOr an atomic. The +# case file is produced by the Rust kernel model (leleka-model-format +# kar_kernel_model, itself tested against the CPU oracle), so a pass means the +# .cu source and the model agree bit for bit on valid windows, non-finite +# inputs, corrupted launch parameters (status 1, no write), multiply status/ +# reduction order and SwiGLU (tolerance 2e-6). It proves the source logic, not +# nvcc code generation or device behaviour. ASAN=1 adds AddressSanitizer +# (heap-exact buffers catch any out-of-bounds read/write; much slower). +set -eu +here=$(cd "$(dirname "$0")" && pwd) +out=${OUT:-${TMPDIR:-/tmp}/kar-emulation} +mkdir -p "$out" +cargo run --release -q -p leleka-model-format --example kar_cases -- "$out/cases.bin" +flags="-std=c++20 -O2 -ffp-contract=off -I$here/shim -include $here/shim/cuda_shim.h" +[ "${ASAN:-0}" = 1 ] && flags="$flags -g -fsanitize=address" +clang++ $flags -o "$out/harness" "$here/main.cpp" +"$out/harness" "$out/cases.bin" diff --git a/crates/cuda-driver/emulation/shim/cuda_fp16.h b/crates/cuda-driver/emulation/shim/cuda_fp16.h new file mode 100644 index 00000000..9145f6b5 --- /dev/null +++ b/crates/cuda-driver/emulation/shim/cuda_fp16.h @@ -0,0 +1,5 @@ +#pragma once +#include +struct __half { uint16_t bits; }; +inline __half __ushort_as_half(unsigned short b) { __half h; h.bits = b; return h; } +inline float __half2float(__half h) { _Float16 f; __builtin_memcpy(&f, &h.bits, 2); return (float)f; } diff --git a/crates/cuda-driver/emulation/shim/cuda_shim.h b/crates/cuda-driver/emulation/shim/cuda_shim.h new file mode 100644 index 00000000..0478c5cf --- /dev/null +++ b/crates/cuda-driver/emulation/shim/cuda_shim.h @@ -0,0 +1,37 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#define __global__ +#define __device__ +#define __shared__ static +#define __forceinline__ inline +#define __launch_bounds__(x) +#define __restrict__ __restrict +struct dim3 { unsigned x = 1, y = 1, z = 1; dim3(unsigned a=1,unsigned b=1,unsigned c=1):x(a),y(b),z(c){} }; +inline thread_local dim3 threadIdx, blockIdx; +inline dim3 blockDim, gridDim; +struct Barrier { + std::mutex m; std::condition_variable cv; unsigned n = 0, count = 0, gen = 0; + void wait() { std::unique_lock l(m); unsigned g = gen; if (++count == n) { count = 0; ++gen; cv.notify_all(); } else cv.wait(l, [&]{ return g != gen; }); } +}; +inline Barrier g_barrier; +inline void __syncthreads() { g_barrier.wait(); } +inline unsigned atomicOr(unsigned* p, unsigned v) { return __atomic_fetch_or(p, v, __ATOMIC_SEQ_CST); } +inline float __fmul_rn(float a, float b) { volatile float r = a * b; return r; } +inline float __fadd_rn(float a, float b) { volatile float r = a + b; return r; } +inline float __uint_as_float(unsigned u) { float f; __builtin_memcpy(&f, &u, 4); return f; } +template void launch(dim3 grid, dim3 block, F f) { + gridDim = grid; blockDim = block; + for (unsigned z = 0; z < grid.z; ++z) for (unsigned y = 0; y < grid.y; ++y) for (unsigned x = 0; x < grid.x; ++x) { + unsigned nt = block.x * block.y * block.z; + g_barrier.n = nt; g_barrier.count = 0; + std::vector ts; + for (unsigned t = 0; t < nt; ++t) ts.emplace_back([&, t] { threadIdx = dim3(t, 0, 0); blockIdx = dim3(x, y, z); f(); }); + for (auto& th : ts) th.join(); + } +} diff --git a/crates/model-format/examples/kar_cases.rs b/crates/model-format/examples/kar_cases.rs new file mode 100644 index 00000000..1c3752aa --- /dev/null +++ b/crates/model-format/examples/kar_cases.rs @@ -0,0 +1,157 @@ +// Dumps decode/multiply/swiglu cases for the C++ emulation harness. +use leleka_model_format::kar::KarNestedRecord; +use leleka_model_format::kar_kernel_model::*; +use std::io::Write; + +struct Rng(u64); +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + fn below(&mut self, n: u64) -> u64 { self.next() % n } + fn range(&mut self, lo: u64, hi: u64) -> u64 { lo + self.below(hi - lo + 1) } +} +fn r16(v: u64) -> u64 { v.div_ceil(16) * 16 } + +struct Out(Vec, u32); +impl Out { + fn w(&mut self, v: u32) { self.0.push(v); } + fn bytes(&mut self, b: &[u8]) { + for c in b.chunks(4) { + let mut x = [0u8; 4]; + x[..c.len()].copy_from_slice(c); + self.0.push(u32::from_le_bytes(x)); + } + } +} + +fn fixture(rng: &mut Rng, n: u64, group: u32, stored: u8) -> (Vec, KarNestedRecord) { + let n_padded = n.div_ceil(u64::from(group)) * u64::from(group); + let scales_bytes = n_padded / u64::from(group) * 2; + let books_offset = r16(256 + scales_bytes); + let books_bytes = (1u64 << (u32::from(stored) + 2)) - 4; + let planes_offset = r16(books_offset + books_bytes); + let stride = r16(n_padded / 32 * 4); + let end = planes_offset + u64::from(stored) * stride; + let mut a: Vec = (0..end).map(|_| rng.next() as u8).collect(); + let fin = |rng: &mut Rng| loop { let b = (rng.next() >> 20) as u16; if b & 0x7c00 != 0x7c00 { return b; } }; + for s in 0..(scales_bytes / 2) as usize { let at = 256 + 2 * s; a[at..at + 2].copy_from_slice(&fin(rng).to_le_bytes()); } + for e in 0..(books_bytes / 2) as usize { let at = books_offset as usize + 2 * e; a[at..at + 2].copy_from_slice(&fin(rng).to_le_bytes()); } + let rec = KarNestedRecord { + name: "t".into(), dimensions: vec![n], n_elements: n, n_padded, group, planes_stored: stored, + planes_min: 2, planes_max: stored, nesting: 0, section_offset: 256, section_bytes: end - 256, + scales_offset: 256, scales_bytes, books_offset, books_bytes, planes_offset, plane_stride_bytes: stride as u32, + }; + rec.validate().unwrap(); + (a, rec) +} + +fn scalars(p: &DecodeParams) -> [u32; 12] { + [p.level, p.staged_planes, p.count, p.head32, p.head_group, p.group, p.scales_offset, p.planes_offset, p.plane_stride_words, p.window_words, p.window_groups, p.packet_bytes] +} +fn from_scalars(s: [u32; 12]) -> DecodeParams { + DecodeParams { level: s[0], staged_planes: s[1], count: s[2], head32: s[3], head_group: s[4], group: s[5], scales_offset: s[6], planes_offset: s[7], plane_stride_words: s[8], window_words: s[9], window_groups: s[10], packet_bytes: s[11] } +} + +fn decode_case(o: &mut Out, p: &DecodeParams, packet: &[u8], grid: u32, out_words: usize) { + let mut out = vec![f32::from_bits(0xdead_beef); out_words]; + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| kernel_decode(p, packet, &mut out))); + let status = match res { + Ok(s) => s, + Err(_) => { eprintln!("MODEL PANIC for params {p:?} (model guard admits an out-of-bounds access)"); return; } + }; + o.1 += 1; + o.w(0); + for v in scalars(p) { o.w(v); } + o.w(grid); o.w(0); o.w(packet.len() as u32); + o.bytes(packet); + o.w(out.len() as u32); o.w(status); + for v in &out { o.w(v.to_bits()); } +} + +fn main() { + let mut rng = Rng(0xfeed_f00d_1234_5678); + let mut o = Out(vec![0], 0); + let groups = [32u32, 64, 96, 128, 256, 1024]; + for level in 2u8..=5 { + for round in 0..150 { + let group = groups[rng.below(6) as usize]; + let n = match round % 4 { 0 => rng.range(1, 70), 1 => rng.range(1, 3 * u64::from(group) + 5), 2 => rng.range(300, 2600), _ => rng.range(700, 12000) }; + let stored = rng.range(u64::from(level), 5) as u8; + let (arch, rec) = fixture(&mut rng, n, group, stored); + for _ in 0..4 { + let start = rng.below(n); + let count = rng.range(1, n - start); + let plan = plan_window(&rec, level, start, count).unwrap(); + let mut packet = stage_packet(&plan, &arch).unwrap(); + // Poison everything the kernel must not read (padding gaps). + let p = plan.params; + decode_case(&mut o, &p, &packet, plan.grid_blocks(), plan.count as usize); + // nonfinite injection: a scale, and a book entry. + if rng.below(3) == 0 { + let which = rng.below(2); + let mut q = packet.clone(); + if which == 0 { + let g = rng.below(u64::from(p.window_groups)) as usize; + let at = p.scales_offset as usize + 2 * g; + q[at..at + 2].copy_from_slice(&0x7c00u16.to_le_bytes()); + } else { + let e = rng.below(1 << level) as usize; + q[2 * e..2 * e + 2].copy_from_slice(&0xfe01u16.to_le_bytes()); + } + decode_case(&mut o, &p, &q, plan.grid_blocks(), plan.count as usize); + } + // corrupted params + if packet.len() < 3000 && rng.below(25) == 0 { + let base = scalars(&p); + for field in (0..12).filter(|f| *f != 2) { + for delta in [1u32, 2, 4, 32, u32::MAX, 0x8000_0000] { + let mut s = base; + s[field] = if delta % 2 == 0 && delta != 0 { s[field].wrapping_add(delta) } else { s[field].wrapping_sub(delta) }; + if delta == 0x8000_0000 { s[field] = base[field] ^ 0x8000_0000; } + let q = from_scalars(s); + decode_case(&mut o, &q, &packet, plan.grid_blocks(), plan.count as usize); + } + } + } + packet.clear(); + } + } + } + // multiply cases + for _ in 0..200 { + let cols = rng.range(1, 700) as u32; + let rows = rng.range(1, 9) as u32; + let tokens = rng.range(1, 3) as u32; + let big = rng.below(10) == 0; + let genf = |rng: &mut Rng| { let m = (rng.next() as i32 as f32) / 2147483648.0; if big { m * 3e19 } else { m * 4.0 } }; + let w: Vec = (0..cols * rows).map(|_| genf(&mut rng)).collect(); + let x: Vec = (0..cols * tokens).map(|_| genf(&mut rng)).collect(); + let mut out = vec![0f32; (rows * tokens) as usize]; + let status = kernel_multiply(&w, &x, cols, rows, tokens, &mut out); + o.1 += 1; + o.w(1); o.w(cols); o.w(rows); o.w(tokens); o.w(0); o.w(0); + for v in &w { o.w(v.to_bits()); } for v in &x { o.w(v.to_bits()); } + o.w(status); o.w(out.len() as u32); for v in &out { o.w(v.to_bits()); } + } + // swiglu + for _ in 0..30 { + let values = rng.range(1, 700) as usize; + let g: Vec = (0..values).map(|_| ((rng.next() as i32 as f32) / 2147483648.0) * if rng.below(5) == 0 { 120.0 } else { 8.0 }).collect(); + let u: Vec = (0..values).map(|_| ((rng.next() as i32 as f32) / 2147483648.0) * 3.0).collect(); + let mut act = vec![0f32; values]; + let status = kernel_swiglu(&g, &u, &mut act); + o.1 += 1; + o.w(2); o.w(values as u32); + for v in &g { o.w(v.to_bits()); } for v in &u { o.w(v.to_bits()); } + o.w(status); for v in &act { o.w(v.to_bits()); } + } + o.0[0] = o.1; + let path = std::env::args().nth(1).unwrap(); + let mut f = std::fs::File::create(path).unwrap(); + for v in &o.0 { f.write_all(&v.to_le_bytes()).unwrap(); } + eprintln!("{} cases", o.1); +}