347 lines
12 KiB
Rust
347 lines
12 KiB
Rust
//! Drift guard for the six CUDA ports: every line of every `__device__` / `__global__` function body of the
|
|
//! Original (`engine/strata/src/kernels/cuda/*.cu`) must still appear, whitespace-normalised, in the checked-in
|
|
//! port (`crates/cuda-driver/src/experimental_*.cu`). Signatures, host wrappers and error handling are the
|
|
//! documented deviations; kernel bodies are not allowed to differ.
|
|
//!
|
|
//! A device function of the Original that the port deliberately does not carry is named in that pair's
|
|
//! `EXCLUDED` list with its reason. The list is the only way past the guard, it is checked both ways (a name that
|
|
//! no longer exists in the Original fails, so the list cannot rot), and a NEW device function of the Original
|
|
//! that is neither in the port nor in the list fails the test: the upstream sync has to be looked at.
|
|
//!
|
|
//! History: the 2026-10-25 sync of `engine/strata` to upstream `41cf05a0` moved the Original kernels and the
|
|
//! ports were re-synced on 2026-11-03.
|
|
|
|
use std::collections::HashSet;
|
|
|
|
fn norm(line: &str) -> String {
|
|
line.split_whitespace().collect::<Vec<_>>().join(" ")
|
|
}
|
|
|
|
/// One `__global__` / `__device__` function of a source: its name and the normalised lines of its body.
|
|
#[derive(Debug)]
|
|
struct Body {
|
|
name: String,
|
|
lines: Vec<String>,
|
|
}
|
|
|
|
/// The function name of a signature (text between the `__global__` / `__device__` marker and the opening brace):
|
|
/// the identifier right before the first `(` once `__launch_bounds__(..)` is removed.
|
|
fn signature_name(signature: &str) -> String {
|
|
let mut text = signature.to_string();
|
|
while let Some(i) = text.find("__launch_bounds__") {
|
|
let open = text[i..].find('(').map(|k| i + k);
|
|
let close = open.and_then(|o| text[o..].find(')').map(|k| o + k));
|
|
match close {
|
|
Some(c) => text.replace_range(i..=c, " "),
|
|
None => break,
|
|
}
|
|
}
|
|
let head = match text.find('(') {
|
|
Some(i) => &text[..i],
|
|
None => &text[..],
|
|
};
|
|
head.trim_end()
|
|
.rsplit(|c: char| !(c.is_alphanumeric() || c == '_'))
|
|
.next()
|
|
.unwrap_or("")
|
|
.to_string()
|
|
}
|
|
|
|
/// Offset (from `after`) of the `}` that closes the `{` at `open`.
|
|
fn matching_brace(after: &str, open: usize) -> usize {
|
|
let mut depth = 0i32;
|
|
for (k, ch) in after[open..].char_indices() {
|
|
match ch {
|
|
'{' => depth += 1,
|
|
'}' => {
|
|
depth -= 1;
|
|
if depth == 0 {
|
|
return open + k;
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
panic!("unbalanced braces")
|
|
}
|
|
|
|
/// The normalised, non-trivial lines of a function body.
|
|
fn body_lines(body: &str) -> Vec<String> {
|
|
let mut lines = Vec::new();
|
|
for line in body.lines() {
|
|
let l = norm(line);
|
|
if l.len() >= 6 && !l.starts_with("//") {
|
|
lines.push(l);
|
|
}
|
|
}
|
|
lines
|
|
}
|
|
|
|
/// The first `__global__` / `__device__` marker of `rest`: its offset and length.
|
|
fn next_marker(rest: &str) -> Option<(usize, usize)> {
|
|
["__global__", "__device__"]
|
|
.iter()
|
|
.filter_map(|m| rest.find(m).map(|i| (i, m.len())))
|
|
.min()
|
|
}
|
|
|
|
/// Bodies of all device functions (text between the first `{` after the `__global__` / `__device__` marker and its
|
|
/// matching `}`), signatures excluded.
|
|
fn device_bodies(source: &str) -> Vec<Body> {
|
|
let mut out = Vec::new();
|
|
let text = source;
|
|
let mut search = 0;
|
|
while search < text.len() {
|
|
let Some((i, len)) = next_marker(&text[search..]) else { break };
|
|
let from = search + i + len;
|
|
// a declaration like `__device__ int x;` has `;` before any `{`
|
|
let after = &text[from..];
|
|
let (brace, semi) = (after.find('{'), after.find(';'));
|
|
match (brace, semi) {
|
|
(Some(b), Some(s)) if s < b => {
|
|
search = from + s;
|
|
continue;
|
|
}
|
|
(Some(b), _) => {
|
|
let end = matching_brace(after, b);
|
|
out.push(Body {
|
|
name: signature_name(&after[..b]),
|
|
lines: body_lines(&after[b + 1..end]),
|
|
});
|
|
search = from + end;
|
|
}
|
|
_ => break,
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// A device function of the Original that the port does not carry, and why.
|
|
type Excluded = (&'static str, &'static str);
|
|
|
|
/// Every exclusion names a device function of the Original and carries a reason.
|
|
fn assert_exclusions_are_live(name: &str, names: &HashSet<&str>, excluded: &[Excluded]) {
|
|
for (function, reason) in excluded {
|
|
assert!(
|
|
names.contains(function),
|
|
"{name}: EXCLUDED names `{function}` ({reason}) but the Original has no such device \
|
|
function; remove or rename the entry"
|
|
);
|
|
assert!(
|
|
!reason.is_empty(),
|
|
"{name}: `{function}` is excluded without a reason"
|
|
);
|
|
}
|
|
}
|
|
|
|
/// The body lines that appear neither as a line of the port nor in its whitespace-flattened text.
|
|
fn missing_lines<'a>(lines: &[&'a String], have: &HashSet<String>, flat: &str) -> Vec<&'a String> {
|
|
lines
|
|
.iter()
|
|
.copied()
|
|
.filter(|l| !have.contains(*l) && !flat.contains(l.as_str()))
|
|
.collect()
|
|
}
|
|
|
|
fn check(name: &str, original: &str, port: &str, excluded: &[Excluded]) {
|
|
let have: HashSet<String> = port.lines().map(norm).collect();
|
|
let flat = norm(port);
|
|
let bodies = device_bodies(original);
|
|
let names: HashSet<&str> = bodies.iter().map(|b| b.name.as_str()).collect();
|
|
assert_exclusions_are_live(name, &names, excluded);
|
|
let skip: HashSet<&str> = excluded.iter().map(|(f, _)| *f).collect();
|
|
let kept: Vec<&Body> = bodies.iter().filter(|b| !skip.contains(b.name.as_str())).collect();
|
|
let lines: Vec<&String> = kept.iter().flat_map(|b| b.lines.iter()).collect();
|
|
assert!(lines.len() > 5, "{name}: found no device bodies");
|
|
let missing = missing_lines(&lines, &have, &flat);
|
|
assert!(
|
|
missing.is_empty(),
|
|
"{name}: {} original kernel-body lines are not in the port:\n{}",
|
|
missing.len(),
|
|
missing
|
|
.iter()
|
|
.map(|l| l.as_str())
|
|
.collect::<Vec<_>>()
|
|
.join("\n")
|
|
);
|
|
println!(
|
|
"{name}: {} kernel-body lines of {} device functions all present; {} functions excluded \
|
|
with a reason",
|
|
lines.len(),
|
|
kept.len(),
|
|
excluded.len()
|
|
);
|
|
}
|
|
|
|
macro_rules! pair {
|
|
($test:ident, $name:literal, $orig:literal, $port:literal, $excluded:expr) => {
|
|
#[test]
|
|
fn $test() {
|
|
check(
|
|
$name,
|
|
include_str!(concat!("../../../engine/strata/src/kernels/cuda/", $orig)),
|
|
include_str!(concat!("../../cuda-driver/src/", $port)),
|
|
$excluded,
|
|
);
|
|
}
|
|
};
|
|
}
|
|
|
|
// kv_q8.cu: the 8-wide gather exists only in the experimental SM60 build of the Original (`#if
|
|
// defined(STRATA_EXPERIMENTAL_SM60)`, Pascal / Volta). The ready-made engine, and this port (sm_120, sm_86), run the
|
|
// 4-wide `kv_gather_q8_kernel`, which is ported. The Original states the wide kernel is bitwise the same.
|
|
const KV_Q8_EXCLUDED: &[Excluded] = &[
|
|
(
|
|
"q8_pair_to_f16x2",
|
|
"STRATA_EXPERIMENTAL_SM60 build only (sm_60/sm_70); compiled out of the ready-made engine",
|
|
),
|
|
(
|
|
"kv_gather_q8_wide_kernel",
|
|
"STRATA_EXPERIMENTAL_SM60 build only (sm_60/sm_70); bitwise the 4-wide gather, which is ported",
|
|
),
|
|
];
|
|
|
|
// qsa_decode_attn.cu: the port carries the reference schedule of KV modes 2, 3 and 4 and the merge. The Original
|
|
// grew alternate schedules and batch variants of the same arithmetic, picked by architecture or environment, none
|
|
// of which the six closed programs expose as an entry. The Original proves the alternates bitwise equal to the
|
|
// reference schedule (its `qsa_merge_daily_parity` and `kv_hybrid_parity` harnesses, header comment of
|
|
// `qsa_decode_attn_chunks_only`); here the emulated reference schedule is compared with the Rust CPU reference
|
|
// (tests/emulated_kernels.rs).
|
|
const QSA_ATTN_EXCLUDED: &[Excluded] = &[
|
|
(
|
|
"attn_chunk_kernel",
|
|
"thin __global__ wrapper over attn_chunk_body; the extern \"C\" entries of the port are the equivalent \
|
|
wrappers",
|
|
),
|
|
(
|
|
"attn_chunk_slots_kernel",
|
|
"same body over a per-query pool set (QsaAttnSlotPools kernel argument): engine batch slots, not an \
|
|
experimental entry",
|
|
),
|
|
(
|
|
"attn_chunk_rows_kernel",
|
|
"same body over per-query pool rows (QsaAttnPoolsRows kernel argument): engine batch windows, not an \
|
|
experimental entry",
|
|
),
|
|
(
|
|
"attn_chunk_q8_v3_kernel",
|
|
"INT8 (KV_MODE 1) Turing schedule; the port instantiates modes 2, 3 and 4 only",
|
|
),
|
|
(
|
|
"attn_chunk_kernel_pre75",
|
|
"alternate schedule of attn_chunk_body (NC cells per step, reduce12); bitwise the reference schedule per the \
|
|
Original's parity harness; the Original selects it for pre-sm_75 cards and, by default, compute capability \
|
|
12.0 (STRATA_ATTN_DAILY)",
|
|
),
|
|
("shfl_x", "helper of attn_chunk_kernel_pre75 only"),
|
|
("warp_sum_x", "helper of attn_chunk_kernel_pre75 only"),
|
|
("warp_max_x", "helper of attn_chunk_kernel_pre75 only"),
|
|
(
|
|
"reduce12",
|
|
"helper of attn_chunk_kernel_pre75 only (reduce12_gfx906 is the ported twin used by attn_chunk_body)",
|
|
),
|
|
(
|
|
"head_of_lane",
|
|
"helper of attn_chunk_kernel_pre75 only (reduce12_head_of_lane is the ported twin)",
|
|
),
|
|
("load_v1", "helper of attn_chunk_kernel_pre75 only"),
|
|
("merge_max_block", "helper of attn_merge_v2_kernel only"),
|
|
("merge_sum_block", "helper of attn_merge_v2_kernel only"),
|
|
(
|
|
"attn_merge_v2_kernel",
|
|
"alternate merge (width-bounded, batched loads); bitwise attn_merge_kernel per the Original's parity harness; \
|
|
follows STRATA_ATTN_DAILY",
|
|
),
|
|
];
|
|
|
|
pair!(
|
|
kv_q4_bodies_are_literal,
|
|
"kv_q4",
|
|
"kv_q4.cu",
|
|
"experimental_kv_q4.cu",
|
|
&[]
|
|
);
|
|
pair!(
|
|
kv_q8_bodies_are_literal,
|
|
"kv_q8",
|
|
"kv_q8.cu",
|
|
"experimental_kv_q8.cu",
|
|
KV_Q8_EXCLUDED
|
|
);
|
|
pair!(
|
|
kv_stream_bodies_are_literal,
|
|
"kv_stream",
|
|
"kv_stream.cu",
|
|
"experimental_kv_stream.cu",
|
|
&[]
|
|
);
|
|
pair!(
|
|
keyless_bodies_are_literal,
|
|
"keyless",
|
|
"keyless.cu",
|
|
"experimental_keyless.cu",
|
|
&[]
|
|
);
|
|
pair!(
|
|
qsa_attn_bodies_are_literal,
|
|
"qsa_attn",
|
|
"qsa_decode_attn.cu",
|
|
"experimental_qsa_attn.cu",
|
|
QSA_ATTN_EXCLUDED
|
|
);
|
|
pair!(
|
|
cvec_bodies_are_literal,
|
|
"cvec",
|
|
"cvec.cu",
|
|
"experimental_cvec.cu",
|
|
&[]
|
|
);
|
|
|
|
/// A synthetic Original: one kernel and one helper device function.
|
|
fn synthetic_original() -> &'static str {
|
|
concat!(
|
|
"__global__ void k(int a) {\n int x = a + 1;\n int y = x * 2;\n int u = y + x;\n",
|
|
" int v = u + y;\n int z = y - 3;\n int w = z;\n return;\n}\n",
|
|
"__device__ __forceinline__ float helper(float v) {\n",
|
|
" float s = v * 3.0f + 1.0f;\n return s * s;\n}\n"
|
|
)
|
|
}
|
|
|
|
fn check_panics(original: &str, port: &str, excluded: &[Excluded]) -> bool {
|
|
std::panic::catch_unwind(|| check("synthetic", original, port, excluded)).is_err()
|
|
}
|
|
|
|
#[test]
|
|
fn the_guard_notices_a_changed_or_unlisted_device_function() {
|
|
let original = synthetic_original();
|
|
let port_same = original.replace("__global__ void k(int a)", "__device__ void k_body(int a)");
|
|
check("synthetic", original, &port_same, &[]);
|
|
let changed = port_same.replace("int y = x * 2;", "int y = x * 3;");
|
|
assert!(check_panics(original, &changed, &[]));
|
|
let without_helper = port_same.replace("float s = v * 3.0f + 1.0f;", "float s = v;");
|
|
assert!(check_panics(original, &without_helper, &[]));
|
|
// an exclusion lets the function go, a stale one is refused
|
|
check("synthetic", original, &without_helper, &[("helper", "test")]);
|
|
assert!(check_panics(original, &port_same, &[("gone", "test")]));
|
|
}
|
|
|
|
#[test]
|
|
fn signature_names_survive_launch_bounds_and_templates() {
|
|
assert_eq!(
|
|
signature_name(
|
|
" void __launch_bounds__(THREADS) attn_chunk_kernel_pre75(const float* q, int n)"
|
|
),
|
|
"attn_chunk_kernel_pre75"
|
|
);
|
|
assert_eq!(
|
|
signature_name(" __forceinline__ float warp_sum(float v)"),
|
|
"warp_sum"
|
|
);
|
|
assert_eq!(
|
|
signature_name(
|
|
"\n__device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, QsaAttnPools p,"
|
|
),
|
|
"attn_chunk_body"
|
|
);
|
|
}
|