mod common;
use common::{
cross_block_grid_sync_expected, cross_block_grid_sync_inputs, cross_block_grid_sync_program,
CROSS_BLOCK_GRID_SYNC_WORKGROUP,
};
use vyre_driver::launch::resolve_launch_workgroup;
use vyre_driver::validation::LaunchGeometryLimits;
use vyre_driver::DispatchConfig;
use vyre_driver_cuda::occupancy::cooperative_thread_residency_block_limit;
use vyre_driver_cuda::{cuda_factory, CudaBackend};
use vyre_foundation::ir::{BufferDecl, DataType, Expr, Node, Program};
use vyre_foundation::memory_model::MemoryOrdering;
const CHAIN_BARRIERS: u32 = 5;
const CHAIN_DELAY_PER_BLOCK: u32 = 2;
fn five_barrier_chain_program(n: u32) -> Program {
assert!(
n >= 2 * CROSS_BLOCK_GRID_SYNC_WORKGROUP && n % CROSS_BLOCK_GRID_SYNC_WORKGROUP == 0,
"Fix: the chain fixture needs a whole number of blocks and at least two; got {n} lanes."
);
let iterations = Expr::mul(
Expr::div(Expr::gid_x(), Expr::u32(CROSS_BLOCK_GRID_SYNC_WORKGROUP)),
Expr::u32(CHAIN_DELAY_PER_BLOCK),
);
let mut body: Vec<Node> = Vec::new();
for stage in 0..CHAIN_BARRIERS {
body.push(Node::loop_for(
&format!("chain_delay_{stage}"),
Expr::u32(0),
iterations.clone(),
vec![Node::store(
"ring",
Expr::gid_x(),
Expr::add(Expr::load("ring", Expr::gid_x()), Expr::u32(1)),
)],
));
body.push(Node::barrier_with_ordering(MemoryOrdering::GridSync));
body.push(Node::store(
"ring",
Expr::gid_x(),
Expr::load("ring", Expr::u32(n - 1)),
));
}
body.push(Node::store(
"out",
Expr::gid_x(),
Expr::add(
Expr::load("ring", Expr::u32(n - 1)),
Expr::load("input", Expr::gid_x()),
),
));
Program::wrapped(
vec![
BufferDecl::read("input", 0, DataType::U32).with_count(n),
BufferDecl::read_write("ring", 1, DataType::U32).with_count(n),
BufferDecl::output("out", 2, DataType::U32).with_count(n),
],
[CROSS_BLOCK_GRID_SYNC_WORKGROUP, 1, 1],
body,
)
}
fn five_barrier_chain_inputs(n: u32) -> Vec<Vec<u8>> {
let lanes: Vec<u8> = (0..n).flat_map(|lane| lane.to_le_bytes()).collect();
vec![lanes.clone(), lanes]
}
fn five_barrier_chain_expected(n: u32) -> Vec<u32> {
let blocks = n / CROSS_BLOCK_GRID_SYNC_WORKGROUP;
let shared = (n - 1) + CHAIN_BARRIERS * (blocks - 1) * CHAIN_DELAY_PER_BLOCK;
(0..n).map(|gid| shared + gid).collect()
}
fn backend() -> CudaBackend {
CudaBackend::acquire()
.expect("Fix: CUDA backend acquisition must succeed on the GPU-required test host.")
}
fn bytes_u32(bytes: &[u8]) -> Vec<u32> {
bytes
.chunks_exact(4)
.map(|chunk| u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
.collect()
}
fn launch_limits(backend: &CudaBackend) -> LaunchGeometryLimits {
LaunchGeometryLimits {
backend: "CUDA",
max_threads_per_block: backend.max_threads_per_block(),
max_block_dim: backend.max_block_dim(),
max_grid_dim: backend.max_grid_dim(),
max_threads_per_sm: backend.max_threads_per_sm(),
}
}
fn cooperative_lane_ceiling(backend: &CudaBackend, program: &Program) -> Option<u32> {
let declared_lanes = program
.buffers()
.iter()
.map(vyre_foundation::ir::BufferDecl::count)
.max()?;
let effective = resolve_launch_workgroup(
program,
&DispatchConfig::default(),
launch_limits(backend),
declared_lanes,
);
let resident_blocks = cooperative_thread_residency_block_limit(&backend.caps, effective[0]);
if resident_blocks == 0 {
return None;
}
u32::try_from(resident_blocks)
.ok()?
.checked_mul(effective[0])
}
fn over_residency_lanes_for(backend: &CudaBackend, build: impl Fn(u32) -> Program) -> Option<u32> {
let mut lanes = FITTING_LANES;
for _ in 0..8 {
let ceiling = cooperative_lane_ceiling(backend, &build(lanes))?;
let candidate = ceiling
.checked_div(CROSS_BLOCK_GRID_SYNC_WORKGROUP)?
.checked_add(4)?
.checked_mul(CROSS_BLOCK_GRID_SYNC_WORKGROUP)?;
if candidate > ceiling && cooperative_lane_ceiling(backend, &build(candidate))? < candidate
{
return Some(candidate);
}
lanes = candidate;
}
None
}
fn over_residency_lanes(backend: &CudaBackend) -> Option<u32> {
over_residency_lanes_for(backend, cross_block_grid_sync_program)
}
const FITTING_LANES: u32 = 4 * CROSS_BLOCK_GRID_SYNC_WORKGROUP;
#[test]
fn grid_sync_program_wider_than_cooperative_residency_still_dispatches_correctly() {
let backend = backend();
if !backend.hardware_supports_grid_sync() {
return;
}
let Some(lanes) = over_residency_lanes(&backend) else {
panic!(
"Fix: hardware reports grid-sync support, so the cooperative residency bound must be \
positive and an over-residency lane count must be derivable."
);
};
let ceiling = cooperative_lane_ceiling(&backend, &cross_block_grid_sync_program(lanes))
.expect("Fix: the cooperative lane ceiling must be derivable on grid-sync hardware.");
assert!(
lanes > ceiling,
"Fix: this test is only meaningful when the launch exceeds the cooperative lane ceiling; \
got {lanes} lanes against a ceiling of {ceiling}. Compare LANES, not declared-width \
blocks: the effective workgroup is what the bound is computed on."
);
let program = cross_block_grid_sync_program(lanes);
let inputs = cross_block_grid_sync_inputs(lanes);
let outputs = backend
.dispatch(&program, &inputs, &DispatchConfig::default())
.expect(
"Fix: a grid-sync program whose grid exceeds cooperative residency must route to the \
host-orchestrated split and succeed. A refusal here means the missing-native-barrier \
refusal was applied to the over-residency case too, which breaks the multi-block \
prefix scan and the C statement-structure kernel.",
);
assert_eq!(
bytes_u32(outputs.last().expect("the fixture declares an output")),
cross_block_grid_sync_expected(lanes),
"Fix: the host-split route must preserve whole-grid barrier semantics; wrong values here \
mean the split segments do not actually order the pre-barrier writes."
);
}
#[test]
fn native_and_over_residency_routes_agree_on_the_answer() {
let backend = backend();
if !backend.hardware_supports_grid_sync() {
return;
}
let fitting_program = cross_block_grid_sync_program(FITTING_LANES);
let fitting_inputs = cross_block_grid_sync_inputs(FITTING_LANES);
let native = backend
.dispatch(
&fitting_program,
&fitting_inputs,
&DispatchConfig::default(),
)
.expect("Fix: a fitting grid-sync program must dispatch natively.");
assert_eq!(
bytes_u32(native.last().expect("the fixture declares an output")),
cross_block_grid_sync_expected(FITTING_LANES),
"Fix: the native cooperative route must produce the grid-synchronized answer."
);
let Some(lanes) = over_residency_lanes(&backend) else {
panic!("Fix: cooperative residency bound must be positive on grid-sync hardware.");
};
let split_program = cross_block_grid_sync_program(lanes);
let split_inputs = cross_block_grid_sync_inputs(lanes);
let split = backend
.dispatch(&split_program, &split_inputs, &DispatchConfig::default())
.expect("Fix: an over-residency grid-sync program must dispatch via the split route.");
assert_eq!(
bytes_u32(split.last().expect("the fixture declares an output")),
cross_block_grid_sync_expected(lanes),
"Fix: the two routes must not produce different answers for the same program shape; the \
residency bound must decide only HOW the barrier is realized, never WHAT it computes."
);
}
#[test]
fn cooperative_fits_check_reports_true_for_a_fitting_grid_and_false_above_residency() {
let backend = cuda_factory()
.expect("Fix: CUDA backend acquisition must succeed on the GPU-required test host.");
let direct = CudaBackend::acquire()
.expect("Fix: CUDA backend acquisition must succeed on the GPU-required test host.");
if !direct.hardware_supports_grid_sync() {
return;
}
let fitting_program = cross_block_grid_sync_program(FITTING_LANES);
let fitting_inputs = cross_block_grid_sync_inputs(FITTING_LANES);
let fitting_borrowed: Vec<&[u8]> = fitting_inputs.iter().map(Vec::as_slice).collect();
assert!(
backend
.cooperative_grid_sync_fits(
&fitting_program,
&fitting_borrowed,
&DispatchConfig::default()
)
.expect("Fix: the fits check must compute launch geometry for a valid program."),
"Fix: a four-block grid-sync program fits cooperative residency on this device and the \
fits check must say so, or the native route is never chosen."
);
let Some(lanes) = over_residency_lanes(&direct) else {
panic!("Fix: cooperative residency bound must be positive on grid-sync hardware.");
};
let wide_program = cross_block_grid_sync_program(lanes);
let wide_inputs = cross_block_grid_sync_inputs(lanes);
let wide_borrowed: Vec<&[u8]> = wide_inputs.iter().map(Vec::as_slice).collect();
assert!(
!backend
.cooperative_grid_sync_fits(&wide_program, &wide_borrowed, &DispatchConfig::default())
.expect("Fix: the fits check must compute launch geometry for a valid program."),
"Fix: a grid above the cooperative residency bound does NOT fit and the fits check must \
report false, or an orchestrator picks the native route and fails after uploading."
);
}
#[test]
fn preflight_verdict_matches_the_route_taken_at_the_exact_residency_boundary() {
let registry = cuda_factory()
.expect("Fix: CUDA backend acquisition must succeed on the GPU-required test host.");
let backend = backend();
if !backend.hardware_supports_grid_sync() {
return;
}
let Some(ceiling_lanes) =
cooperative_lane_ceiling(&backend, &cross_block_grid_sync_program(FITTING_LANES))
else {
panic!("Fix: cooperative residency bound must be positive on grid-sync hardware.");
};
assert_eq!(
ceiling_lanes % CROSS_BLOCK_GRID_SYNC_WORKGROUP,
0,
"Fix: the cooperative lane ceiling ({ceiling_lanes}) must be a whole number of \
declared-width blocks for this fixture to straddle it exactly."
);
for (lanes, must_fit) in [
(ceiling_lanes, true),
(ceiling_lanes + CROSS_BLOCK_GRID_SYNC_WORKGROUP, false),
] {
let program = cross_block_grid_sync_program(lanes);
let inputs = cross_block_grid_sync_inputs(lanes);
let borrowed: Vec<&[u8]> = inputs.iter().map(Vec::as_slice).collect();
let fits = registry
.cooperative_grid_sync_fits(&program, &borrowed, &DispatchConfig::default())
.expect("Fix: the preflight must compute launch geometry for a valid program.");
assert_eq!(
fits, must_fit,
"Fix: at {lanes} lanes against a cooperative ceiling of {ceiling_lanes} lanes, the \
preflight must report fits={must_fit}. A boundary off by one block means the \
preflight and the route decision disagree for exactly one grid width, which is the \
hardest possible version of this bug to find."
);
let outputs = backend
.dispatch(&program, &inputs, &DispatchConfig::default())
.unwrap_or_else(|error| {
panic!(
"Fix: {lanes} lanes (preflight fits={fits}) must dispatch successfully by \
whichever route the preflight predicts: {error}"
)
});
assert_eq!(
bytes_u32(outputs.last().expect("the fixture declares an output")),
cross_block_grid_sync_expected(lanes),
"Fix: at {lanes} lanes the chosen route must still produce the grid-synchronized \
answer; a wrong value means the route the preflight predicted does not honor the \
barrier."
);
}
}
#[test]
fn cooperative_ceiling_follows_the_effective_workgroup_not_the_declared_one() {
let backend = backend();
if !backend.hardware_supports_grid_sync() {
return;
}
let program = cross_block_grid_sync_program(FITTING_LANES);
assert_eq!(
program.workgroup_size(),
[CROSS_BLOCK_GRID_SYNC_WORKGROUP, 1, 1],
"Fix: the fixture must declare a 256-wide workgroup for this comparison to mean anything."
);
let effective = resolve_launch_workgroup(
&program,
&DispatchConfig::default(),
launch_limits(&backend),
FITTING_LANES,
);
let declared_bound =
cooperative_thread_residency_block_limit(&backend.caps, CROSS_BLOCK_GRID_SYNC_WORKGROUP);
let effective_bound = cooperative_thread_residency_block_limit(&backend.caps, effective[0]);
assert_eq!(
declared_bound * u64::from(CROSS_BLOCK_GRID_SYNC_WORKGROUP),
u64::from(backend.caps.max_threads_per_sm_u32())
* u64::from(backend.caps.multi_processor_count_u32()),
"Fix: at 256 wide the workgroup divides 1536 exactly, so the block bound must account for \
every thread slot on the device."
);
assert!(
effective_bound * u64::from(effective[0])
<= declared_bound * u64::from(CROSS_BLOCK_GRID_SYNC_WORKGROUP),
"Fix: the effective workgroup can only equal or waste thread slots relative to a width \
that divides max_threads_per_sm evenly; a larger product means the bound is miscomputed."
);
let ceiling = cooperative_lane_ceiling(&backend, &program)
.expect("Fix: the cooperative lane ceiling must be derivable on grid-sync hardware.");
assert_eq!(
ceiling,
u32::try_from(effective_bound).expect("bound fits u32") * effective[0],
"Fix: the lane ceiling must be the effective block bound times the effective workgroup."
);
let device_threads = u64::from(backend.caps.max_threads_per_sm_u32())
* u64::from(backend.caps.multi_processor_count_u32());
assert_eq!(
device_threads, 261_120,
"Fix: 170 SMs at 1536 threads each is 261,120 thread slots; a different total means the \
probed device caps changed and every ceiling below moves with them."
);
if backend.caps.max_threads_per_sm_u32() % effective[0] == 0 {
assert_eq!(
u64::from(ceiling),
device_threads,
"Fix: an evenly dividing width ({}) must reach every thread slot: {device_threads} \
lanes. A lower ceiling means the block bound is miscomputed.",
effective[0]
);
} else {
let blocks_per_sm = backend.caps.max_threads_per_sm_u32() / effective[0];
assert_eq!(
u64::from(ceiling),
u64::from(blocks_per_sm)
* u64::from(effective[0])
* u64::from(backend.caps.multi_processor_count_u32()),
"Fix: with width {} the per-SM budget truncates to {blocks_per_sm} block(s), so the \
ceiling is that times the width times the SM count.",
effective[0]
);
assert!(
u64::from(ceiling) < device_threads,
"Fix: a width that does not divide the per-SM thread budget MUST leave slots idle; \
equality here means the truncation branch was entered wrongly."
);
}
}
#[test]
fn preflight_reports_false_without_erroring_for_a_program_with_no_grid_sync_barrier() {
let registry = cuda_factory()
.expect("Fix: CUDA backend acquisition must succeed on the GPU-required test host.");
let program = Program::wrapped(
vec![
BufferDecl::read("input", 0, DataType::U32).with_count(8),
BufferDecl::output("out", 1, DataType::U32).with_count(8),
],
[128, 1, 1],
vec![Node::store(
"out",
Expr::gid_x(),
Expr::add(Expr::load("input", Expr::gid_x()), Expr::u32(1)),
)],
);
let inputs: Vec<Vec<u8>> = vec![(1..=8_u32).flat_map(u32::to_le_bytes).collect()];
let borrowed: Vec<&[u8]> = inputs.iter().map(Vec::as_slice).collect();
assert!(
!registry
.cooperative_grid_sync_fits(&program, &borrowed, &DispatchConfig::default())
.expect(
"Fix: a program with no grid-sync barrier must answer the preflight with \
Ok(false), not an error."
),
"Fix: with no grid-sync barrier there is nothing to launch cooperatively, so the preflight \
reports false."
);
}
#[test]
fn registry_split_permission_stays_false_while_over_residency_splitting_works() {
let backend = cuda_factory()
.expect("Fix: CUDA backend acquisition must succeed on the GPU-required test host.");
assert!(
!backend.allows_host_grid_sync_split(),
"Fix: CUDA must not permit the registry wrapper to emulate a missing grid barrier by \
splitting; that path must be a loud refusal."
);
let direct = CudaBackend::acquire()
.expect("Fix: CUDA backend acquisition must succeed on the GPU-required test host.");
if !direct.hardware_supports_grid_sync() {
return;
}
assert!(
backend.supports_grid_sync(),
"Fix: on this device the barrier IS native, which is exactly why the registry wrapper's \
emulation permission being false costs nothing and the over-residency split is a \
different mechanism."
);
}
#[test]
fn no_dispatch_entry_point_reroutes_a_missing_native_barrier_into_a_split() {
let source = include_str!("../src/backend/host_dispatch.rs");
assert!(
source.contains("fn require_native_grid_sync_lowering"),
"Fix: the refusal helper must exist in the file that routes grid-sync dispatches."
);
assert_eq!(
source
.matches("self.require_native_grid_sync_lowering()?")
.count(),
2,
"Fix: both grid-sync entry points (dispatch_borrowed via \
grid_sync_program_needs_host_split, and dispatch_borrowed_async) must refuse a missing \
native barrier. A new entry point that skips the check reintroduces the silent split."
);
assert!(
!source.contains("if !self.supports_grid_sync() {\n return Ok(true);"),
"Fix: `!supports_grid_sync()` must no longer be a reason to host-split; it is a reason to \
refuse. Over-residency is the only split reason."
);
assert!(
!source.contains(
"contains_grid_sync(program) && !self.supports_grid_sync() {\n let outputs = self.dispatch_borrowed_with_grid_sync_split("
),
"Fix: the async entry point must not answer a missing native barrier with a silent split."
);
assert!(
source.contains("fn dispatch_borrowed_with_grid_sync_split"),
"Fix: the over-residency split route must remain; refusing it would break the multi-block \
prefix scan and the C statement-structure kernel."
);
}
#[test]
fn every_split_call_site_is_reached_through_the_residency_predicate() {
let source = include_str!("../src/backend/host_dispatch.rs");
let call_sites = source
.matches("self.dispatch_borrowed_with_grid_sync_split(")
.count();
assert_eq!(
call_sites, 2,
"Fix: exactly two internal split call sites are expected (dispatch_borrowed and the owned \
input path), both gated on grid_sync_program_needs_host_split, which refuses a missing \
native barrier before it can answer true. Found {call_sites}: a new call site must route \
through that predicate or state why it may not."
);
assert_eq!(
source
.matches("self.grid_sync_program_needs_host_split(")
.count(),
2,
"Fix: each split call site must be guarded by the residency predicate."
);
}
#[test]
fn five_barrier_program_splits_correctly_above_cooperative_residency() {
let backend = backend();
if !backend.hardware_supports_grid_sync() {
return;
}
let Some(lanes) = over_residency_lanes_for(&backend, five_barrier_chain_program) else {
panic!("Fix: cooperative residency bound must be positive on grid-sync hardware.");
};
let ceiling = cooperative_lane_ceiling(&backend, &five_barrier_chain_program(lanes))
.expect("Fix: the cooperative lane ceiling must be derivable on grid-sync hardware.");
assert!(
lanes > ceiling,
"Fix: this test is only meaningful above the cooperative lane ceiling; got {lanes} lanes \
against a ceiling of {ceiling}."
);
let program = five_barrier_chain_program(lanes);
let inputs = five_barrier_chain_inputs(lanes);
let outputs = backend
.dispatch(&program, &inputs, &DispatchConfig::default())
.expect(
"Fix: a five-barrier grid-sync program above cooperative residency must route to the \
host-orchestrated split and succeed. A failure here means multi-cut splitting is \
broken and the C statement-structure kernel has a real input ceiling after all.",
);
let actual = bytes_u32(outputs.last().expect("the fixture declares an output"));
let expected = five_barrier_chain_expected(lanes);
assert_eq!(
actual, expected,
"Fix: the split route must honor ALL FIVE barriers. Values below expectation mean a cut \
was dropped or reordered and a stage read the last lane's slot mid-accumulation."
);
}
#[test]
fn five_barrier_program_is_correct_on_the_native_cooperative_route_too() {
let backend = backend();
if !backend.hardware_supports_grid_sync() {
return;
}
let program = five_barrier_chain_program(FITTING_LANES);
let expected = five_barrier_chain_expected(FITTING_LANES);
for launch in 1..=2_u32 {
let inputs = five_barrier_chain_inputs(FITTING_LANES);
let outputs = backend
.dispatch(&program, &inputs, &DispatchConfig::default())
.unwrap_or_else(|error| {
panic!(
"Fix: native launch {launch} of the five-barrier program must succeed: {error}"
)
});
assert_eq!(
bytes_u32(outputs.last().expect("the fixture declares an output")),
expected,
"Fix: native launch {launch} must honor all five barriers; wrong values on launch 2 \
specifically mean the module-scope counter was not reset between launches."
);
}
}