use std::collections::HashSet;
use fuel_graph::registry::{FusedOpParams, FusedOps};
use fuel_graph::{Graph, NodeId, Op, branches_in_topo_order};
use fuel_ir::backend::{BackendCapabilities, SubstrateClass, TransferPath};
use fuel_ir::dispatch::SizeClass;
use fuel_ir::probe::BackendId;
use fuel_ir::{DType, DeviceLocation, DynScalar, Shape};
use crate::cost::{cost_flash_decoding_cuda, cost_matmul_cpu, default_cost_for_op_kind};
use crate::fused::CostEstimate;
use crate::kernel::OpParams;
use crate::pipelined::op_to_op_kind;
use crate::ranker::cost::{composite_ns, default_backend_rates};
use crate::ranker::judge::JudgeOracle;
use crate::runtime_fused_kernels::fused_kernel_available;
pub type ArmCostFn<'a> = dyn Fn(&Graph, NodeId, usize, &[NodeId]) -> Option<u64> + 'a;
std::thread_local! {
static VARIANT_BAKES_TL: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
pub fn variant_bakes_thread_local() -> usize {
VARIANT_BAKES_TL.with(|c| c.get())
}
pub fn bake_variant_branches(
graph: &mut Graph,
roots: &[NodeId],
arm_cost: &ArmCostFn<'_>,
) -> usize {
let branches = branches_in_topo_order(graph, roots);
let mut decisions: Vec<(NodeId, usize)> = Vec::new();
for branch in branches {
let arms = graph.node(branch).inputs.clone();
if arms.len() < 2 {
continue; }
let Some(backend0) = graph.target_backend(arms[0]) else {
continue;
};
if !arms
.iter()
.all(|&a| graph.target_backend(a) == Some(backend0))
{
continue; }
let interiors = arm_interiors(graph, branch);
let Some(c0) = arm_cost(graph, branch, 0, &interiors[0]) else {
continue;
};
let mut best: Option<(usize, u64)> = None;
let mut tie_at_best = false;
for (w, interior) in interiors.iter().enumerate().skip(1) {
let Some(cw) = arm_cost(graph, branch, w, interior) else {
continue; };
if cw >= c0 {
continue; }
match best {
None => best = Some((w, cw)),
Some((_, bc)) if cw < bc => {
best = Some((w, cw));
tie_at_best = false;
}
Some((_, bc)) if cw == bc => tie_at_best = true,
_ => {}
}
}
let winner = if tie_at_best {
0
} else {
best.map(|(w, _)| w).unwrap_or(0)
};
decisions.push((branch, winner));
}
let mut baked_to_variant = 0usize;
for (branch, winner) in decisions {
if winner != 0 {
baked_to_variant += 1;
}
let _ = graph.collapse_variant_branch(branch, winner);
}
if baked_to_variant > 0 {
VARIANT_BAKES_TL.with(|c| c.set(c.get() + baked_to_variant));
}
baked_to_variant
}
fn arm_interiors(graph: &Graph, branch: NodeId) -> Vec<Vec<NodeId>> {
let arm_exits = graph.node(branch).inputs.clone();
let cones: Vec<HashSet<NodeId>> = arm_exits.iter().map(|&e| backward_cone(graph, e)).collect();
if cones.is_empty() {
return Vec::new();
}
let mut shared: HashSet<NodeId> = cones[0].clone();
for c in &cones[1..] {
shared = shared.intersection(c).copied().collect();
}
cones
.iter()
.map(|cone| {
cone.iter()
.copied()
.filter(|n| !shared.contains(n))
.collect()
})
.collect()
}
fn backward_cone(graph: &Graph, from: NodeId) -> HashSet<NodeId> {
let mut seen: HashSet<NodeId> = HashSet::new();
let mut stack = vec![from];
while let Some(n) = stack.pop() {
if !seen.insert(n) {
continue;
}
for &inp in &graph.node(n).inputs {
if !seen.contains(&inp) {
stack.push(inp);
}
}
}
seen
}
pub fn decode_arm_composite_ns(
graph: &Graph,
_branch: NodeId,
_arm_idx: usize,
interior: &[NodeId],
backend: BackendId,
) -> Option<u64> {
let (compute_rate, mem_bw) = default_backend_rates(backend);
let caps = neutral_caps(backend, compute_rate, mem_bw);
let mut total_ns: u64 = 0;
let mut any = false;
for &nid in interior {
let Some(cost) = node_layer1_cost(graph, nid, backend, &caps) else {
continue;
};
any = true;
total_ns = total_ns.saturating_add(composite_ns(&cost, compute_rate, mem_bw));
}
if !any || total_ns == 0 {
return None; }
Some(total_ns)
}
pub fn decode_arm_composite_ns_judged(
graph: &Graph,
branch: NodeId,
arm_idx: usize,
interior: &[NodeId],
backend: BackendId,
judge: Option<&dyn JudgeOracle>,
) -> Option<u64> {
let Some(judge) = judge else {
return decode_arm_composite_ns(graph, branch, arm_idx, interior, backend);
};
let (compute_rate, mem_bw) = default_backend_rates(backend);
let caps = neutral_caps(backend, compute_rate, mem_bw);
let mut total_ns: u64 = 0;
let mut any = false;
for &nid in interior {
let ns = match node_measured_ns(graph, nid, backend, judge) {
Some(measured) => Some(measured),
None => node_layer1_cost(graph, nid, backend, &caps)
.map(|cost| composite_ns(&cost, compute_rate, mem_bw)),
};
if let Some(ns) = ns {
any = true;
total_ns = total_ns.saturating_add(ns);
}
}
if !any || total_ns == 0 {
return None; }
Some(total_ns)
}
fn node_measured_ns(
graph: &Graph,
nid: NodeId,
backend: BackendId,
judge: &dyn JudgeOracle,
) -> Option<u64> {
let node = graph.node(nid);
let kind = op_to_op_kind(&node.op)?;
let principal_dtype = match node.inputs.first() {
Some(&i) => graph.node(i).dtype,
None => node.dtype, };
let input_shapes: Vec<Shape> = node
.inputs
.iter()
.map(|&i| graph.node(i).shape.clone())
.collect();
let size_class = SizeClass::for_op(kind, &input_shapes);
judge.measured_latency_ns(kind, principal_dtype, size_class, backend, "", 0)
}
fn node_layer1_cost(
graph: &Graph,
nid: NodeId,
backend: BackendId,
caps: &BackendCapabilities,
) -> Option<CostEstimate> {
let node = graph.node(nid);
match &node.op {
Op::Fused(fid, params) if *fid == FusedOps::FLASH_ATTN => {
if !fused_kernel_available(FusedOps::FLASH_ATTN, backend) {
return None; }
let op_params = flash_op_params(graph, node, params)?;
let dtypes = [node.dtype, node.dtype];
Some(cost_flash_decoding_cuda(&[], &dtypes, &op_params, caps))
}
Op::MatMul => {
let op_params = matmul_op_params(graph, node)?;
let dtypes = [node.dtype, node.dtype, node.dtype];
Some(cost_matmul_cpu(&[], &dtypes, &op_params, caps))
}
other => {
let kind = op_to_op_kind(other)?;
let mut shapes: Vec<Shape> = node
.inputs
.iter()
.map(|&i| graph.node(i).shape.clone())
.collect();
shapes.push(node.shape.clone());
let mut dtypes: Vec<DType> = node.inputs.iter().map(|&i| graph.node(i).dtype).collect();
dtypes.push(node.dtype);
Some(default_cost_for_op_kind(kind)(
&shapes,
&dtypes,
&OpParams::None,
caps,
))
}
}
}
fn matmul_op_params(graph: &Graph, node: &fuel_graph::Node) -> Option<OpParams> {
let a = graph.node(*node.inputs.first()?).shape.clone();
let b = graph.node(*node.inputs.get(1)?).shape.clone();
let ad = a.dims();
let bd = b.dims();
if ad.len() < 2 || bd.len() < 2 {
return None;
}
let m = ad[ad.len() - 2];
let k = ad[ad.len() - 1];
let n = bd[bd.len() - 1];
let lhs_batch_dims: Vec<usize> = ad[..ad.len() - 2].to_vec();
let rhs_batch_dims: Vec<usize> = bd[..bd.len() - 2].to_vec();
Some(OpParams::Matmul {
lhs_batch_dims,
rhs_batch_dims,
m,
n,
k,
m_compute: crate::kernel::MatmulM::All,
})
}
fn flash_op_params(
graph: &Graph,
node: &fuel_graph::Node,
params: &FusedOpParams,
) -> Option<OpParams> {
let FusedOpParams::FlashAttn {
softmax_scale,
causal,
window_size_left,
window_size_right,
softcap,
k_len,
} = params
else {
return None;
};
let q = graph.node(*node.inputs.first()?).shape.clone();
let kv = graph.node(*node.inputs.get(1)?).shape.clone();
let qd = q.dims();
let kvd = kv.dims();
if qd.len() != 4 || kvd.len() != 4 {
return None;
}
let (b, hq, sq, d) = (qd[0], qd[1], qd[2], qd[3]);
let hkv = kvd[1];
let sk = kvd[2];
let k_len_val = match k_len {
Some(DynScalar::Concrete(v)) => *v,
_ => sk,
};
Some(OpParams::FlashAttn {
b,
hq,
hkv,
sq,
sk,
d,
k_len: k_len_val,
softmax_scale: *softmax_scale,
causal: *causal,
window_size_left: *window_size_left,
window_size_right: *window_size_right,
softcap: *softcap,
})
}
fn neutral_caps(backend: BackendId, compute: f64, mem_bw: f64) -> BackendCapabilities {
BackendCapabilities {
backend_id: backend,
device_location: DeviceLocation::Cpu,
op_dtype_support: HashSet::new(),
required_alignment: 1,
access_granularity_bits: 8,
transfer_paths: vec![(DeviceLocation::Cpu, TransferPath::SameDevice)],
storage_substrate: SubstrateClass::HostBytes,
compute_throughput_flops_per_ns: compute,
mem_bandwidth_bytes_per_ns: mem_bw,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ranker::judge::HashMapJudge;
use fuel_graph::{Node, lower_runs_arm0};
use fuel_ir::Shape;
use fuel_ir::dispatch::OpKind;
fn node(g: &mut Graph, op: Op, inputs: Vec<NodeId>, dims: &[usize], dt: DType) -> NodeId {
g.push(Node {
op,
inputs,
shape: Shape::from_dims(dims),
dtype: dt,
})
}
fn variant_diamond(backend: BackendId) -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId) {
let dt = DType::F32;
let mut g = Graph::new();
let pre = node(&mut g, Op::Const, vec![], &[4], dt);
let diverge = node(&mut g, Op::Relu, vec![pre], &[4], dt);
let a0_mid = node(&mut g, Op::Relu, vec![diverge], &[4], dt);
let arm0 = node(&mut g, Op::Silu, vec![a0_mid], &[4], dt);
let arm1 = node(&mut g, Op::GeluTanh, vec![diverge], &[4], dt);
g.set_target_backend(a0_mid, backend);
g.set_target_backend(arm0, backend);
g.set_target_backend(arm1, backend);
let reconverge = node(&mut g, Op::Relu, vec![arm0], &[4], dt);
let mut b = g.open_branch(diverge);
b.add_arm(arm0);
b.add_arm(arm1);
let branch = b
.finalize_branches(&mut g, reconverge)
.expect("well-formed 2-arm branch")
.expect("2 arms survive");
let post = node(&mut g, Op::Tanh, vec![reconverge], &[4], dt);
(g, branch, arm0, arm1, reconverge, post)
}
fn fixed_costs(
costs: Vec<Option<u64>>,
) -> impl Fn(&Graph, NodeId, usize, &[NodeId]) -> Option<u64> {
move |_g, _b, arm, _interior| costs.get(arm).copied().flatten()
}
#[test]
fn cheaper_variant_is_baked_and_becomes_the_route() {
let (mut g, branch, arm0, arm1, reconverge, post) = variant_diamond(BackendId::Cuda);
let before = lower_runs_arm0(&g, &[post]);
assert!(
before.contains(&arm0) && !before.contains(&arm1),
"before the bake the same-device variant is never selected (arm 0 wins)",
);
let cost = fixed_costs(vec![Some(1000), Some(400)]); let baked = bake_variant_branches(&mut g, &[post], &cost);
assert_eq!(baked, 1, "one variant branch baked to its winner");
assert!(
g.node(reconverge).inputs.contains(&arm1),
"merge rewired to the variant"
);
assert_eq!(
g.node(branch).inputs,
vec![arm1],
"branch collapsed to the winner"
);
let after = lower_runs_arm0(&g, &[post]);
assert!(
after.contains(&arm1),
"after the bake the variant is realized; order={after:?}"
);
assert!(
!after.contains(&arm0),
"arm 0's region is pruned; order={after:?}"
);
}
#[test]
fn variant_bakes_thread_local_tracks_the_return() {
let before = variant_bakes_thread_local();
let (mut g1, _b1, _a0, _a1, _r1, post1) = variant_diamond(BackendId::Cuda);
let win = fixed_costs(vec![Some(1000), Some(400)]); let baked = bake_variant_branches(&mut g1, &[post1], &win);
assert_eq!(baked, 1);
assert_eq!(
variant_bakes_thread_local() - before,
1,
"a winning-variant bake bumps the thread-local by its return count",
);
let mid = variant_bakes_thread_local();
let (mut g2, _b2, _a0b, _a1b, _r2, post2) = variant_diamond(BackendId::Cuda);
let lose = fixed_costs(vec![Some(400), Some(1000)]); let baked2 = bake_variant_branches(&mut g2, &[post2], &lose);
assert_eq!(baked2, 0);
assert_eq!(
variant_bakes_thread_local(),
mid,
"an oracle-wins bake leaves the thread-local unchanged",
);
}
#[test]
fn costlier_variant_keeps_arm0() {
let (mut g, branch, arm0, arm1, _recon, post) = variant_diamond(BackendId::Cuda);
let cost = fixed_costs(vec![Some(400), Some(1000)]); let baked = bake_variant_branches(&mut g, &[post], &cost);
assert_eq!(baked, 0, "no variant wins ⇒ nothing baked to a variant");
assert_eq!(
g.node(branch).inputs,
vec![arm0],
"branch collapsed to arm 0"
);
let after = lower_runs_arm0(&g, &[post]);
assert!(
after.contains(&arm0) && !after.contains(&arm1),
"arm 0 realized (oracle)"
);
}
#[test]
fn unknown_variant_cost_keeps_arm0() {
let (mut g, _branch, arm0, arm1, _recon, post) = variant_diamond(BackendId::Cuda);
let cost = fixed_costs(vec![Some(1000), None]); let baked = bake_variant_branches(&mut g, &[post], &cost);
assert_eq!(baked, 0, "unknown variant cost ⇒ arm 0 (conservative)");
let after = lower_runs_arm0(&g, &[post]);
assert!(
after.contains(&arm0) && !after.contains(&arm1),
"arm 0 realized"
);
}
#[test]
fn tie_keeps_arm0() {
let (mut g, _branch, arm0, arm1, _recon, post) = variant_diamond(BackendId::Cuda);
let cost = fixed_costs(vec![Some(500), Some(500)]); let baked = bake_variant_branches(&mut g, &[post], &cost);
assert_eq!(baked, 0, "tie ⇒ arm 0 (variant not strictly cheaper)");
let after = lower_runs_arm0(&g, &[post]);
assert!(
after.contains(&arm0) && !after.contains(&arm1),
"arm 0 realized"
);
}
#[test]
fn capability_missing_keeps_arm0() {
let (mut g, _branch, arm0, arm1, _recon, post) = variant_diamond(BackendId::Cuda);
let cost = |_g: &Graph, _b: NodeId, arm: usize, _i: &[NodeId]| -> Option<u64> {
if arm == 0 { Some(1000) } else { None }
};
let baked = bake_variant_branches(&mut g, &[post], &cost);
assert_eq!(baked, 0, "capability-missing variant ⇒ arm 0");
let after = lower_runs_arm0(&g, &[post]);
assert!(
after.contains(&arm0) && !after.contains(&arm1),
"arm 0 realized"
);
}
#[test]
fn placement_branch_is_untouched() {
let (mut g, branch, arm0, arm1, _recon, post) = variant_diamond(BackendId::Cuda);
g.set_target_backend(arm1, BackendId::Cpu);
let cost = fixed_costs(vec![Some(1000), Some(1)]); let baked = bake_variant_branches(&mut g, &[post], &cost);
assert_eq!(baked, 0, "a placement branch is never baked");
assert_eq!(
g.node(branch).inputs,
vec![arm0, arm1],
"placement branch stays a live 2-arm decision point (runtime picker owns it)",
);
}
#[test]
fn unstamped_branch_is_skipped() {
let dt = DType::F32;
let mut g = Graph::new();
let pre = node(&mut g, Op::Const, vec![], &[4], dt);
let diverge = node(&mut g, Op::Relu, vec![pre], &[4], dt);
let a0_mid = node(&mut g, Op::Relu, vec![diverge], &[4], dt);
let arm0 = node(&mut g, Op::Silu, vec![a0_mid], &[4], dt);
let arm1 = node(&mut g, Op::GeluTanh, vec![diverge], &[4], dt);
let reconverge = node(&mut g, Op::Relu, vec![arm0], &[4], dt);
let mut b = g.open_branch(diverge);
b.add_arm(arm0);
b.add_arm(arm1);
let branch = b.finalize_branches(&mut g, reconverge).unwrap().unwrap();
let post = node(&mut g, Op::Tanh, vec![reconverge], &[4], dt);
let cost = fixed_costs(vec![Some(1000), Some(1)]);
let baked = bake_variant_branches(&mut g, &[post], &cost);
assert_eq!(baked, 0, "unstamped branch is skipped");
assert_eq!(g.node(branch).inputs, vec![arm0, arm1], "branch untouched");
}
#[test]
fn region_and_flash_arms_are_both_priced_by_the_provider() {
let (b, hq, d, sk) = (1usize, 8, 128, 512);
let dt = DType::F16;
let mut g = Graph::new();
let q = node(&mut g, Op::Const, vec![], &[b, hq, 1, d], dt);
let k = node(&mut g, Op::Const, vec![], &[b, hq, sk, d], dt);
let v = node(&mut g, Op::Const, vec![], &[b, hq, sk, d], dt);
let kt = node(
&mut g,
Op::Permute(vec![0, 1, 3, 2]),
vec![k],
&[b, hq, d, sk],
dt,
);
let scores = node(&mut g, Op::MatMul, vec![q, kt], &[b, hq, 1, sk], dt);
let attn = node(&mut g, Op::MatMul, vec![scores, v], &[b, hq, 1, d], dt);
let region: Vec<NodeId> = vec![kt, scores, attn];
let region_ns = decode_arm_composite_ns(&g, NodeId(0), 0, ®ion, BackendId::Cuda)
.expect("the decomposed region has costable compute (its two matmuls)");
assert!(region_ns > 0, "region prices to a real nonzero cost");
let flash_node = Node {
op: Op::Fused(
FusedOps::FLASH_ATTN,
FusedOpParams::FlashAttn {
softmax_scale: 0.1,
causal: true,
window_size_left: None,
window_size_right: None,
softcap: None,
k_len: Some(DynScalar::Concrete(sk)),
},
),
inputs: vec![q, k, v],
shape: Shape::from_dims(&[b, hq, 1, d]),
dtype: dt,
};
let (cr, bw) = default_backend_rates(BackendId::Cuda);
let caps = neutral_caps(BackendId::Cuda, cr, bw);
let fp_full = decode_flash_cost_at(&g, &flash_node, sk, &caps, cr, bw);
let fp_small = decode_flash_cost_at(&g, &flash_node, 32, &caps, cr, bw);
assert!(
fp_full > 0 && fp_small > 0,
"flash decode cost is real + nonzero"
);
assert!(
fp_full > fp_small,
"the flash decode cost scales with the live prefix k_len \
({fp_full} @512 > {fp_small} @32) — decode work is O(prefix)",
);
let flash = node(
&mut g,
Op::Fused(
FusedOps::FLASH_ATTN,
FusedOpParams::FlashAttn {
softmax_scale: 0.1,
causal: true,
window_size_left: None,
window_size_right: None,
softcap: None,
k_len: Some(DynScalar::Concrete(sk)),
},
),
vec![q, k, v],
&[b, hq, 1, d],
dt,
);
let gated = decode_arm_composite_ns(&g, NodeId(0), 1, &[flash], BackendId::Cuda);
if fused_kernel_available(FusedOps::FLASH_ATTN, BackendId::Cuda) {
assert!(gated.is_some(), "bound flash kernel ⇒ arm priced");
} else {
assert!(
gated.is_none(),
"unbound flash kernel ⇒ arm inadmissible (oracle stands)"
);
}
}
fn decode_flash_cost_at(
g: &Graph,
flash_node: &Node,
k_len: usize,
caps: &BackendCapabilities,
cr: f64,
bw: f64,
) -> u64 {
let params = FusedOpParams::FlashAttn {
softmax_scale: 0.1,
causal: true,
window_size_left: None,
window_size_right: None,
softcap: None,
k_len: Some(DynScalar::Concrete(k_len)),
};
let op_params = flash_op_params(g, flash_node, ¶ms).expect("derivable");
let dtypes = [flash_node.dtype, flash_node.dtype];
let cost = cost_flash_decoding_cuda(&[], &dtypes, &op_params, caps);
composite_ns(&cost, cr, bw)
}
#[test]
fn symbolic_k_len_prices_at_capacity() {
let (b, hq, d, sk) = (1usize, 4, 64, 256);
let dt = DType::F16;
let mut g = Graph::new();
let q = node(&mut g, Op::Const, vec![], &[b, hq, 1, d], dt);
let k = node(&mut g, Op::Const, vec![], &[b, hq, sk, d], dt);
let v = node(&mut g, Op::Const, vec![], &[b, hq, sk, d], dt);
let flash = node(
&mut g,
Op::Fused(
FusedOps::FLASH_ATTN,
FusedOpParams::FlashAttn {
softmax_scale: 0.1,
causal: true,
window_size_left: None,
window_size_right: None,
softcap: None,
k_len: Some(DynScalar::Sym(fuel_ir::symbol::SymId(0))),
},
),
vec![q, k, v],
&[b, hq, 1, d],
dt,
);
let flash_node = g.node(flash).clone();
let params_in = match &flash_node.op {
Op::Fused(_, p) => p.clone(),
_ => unreachable!(),
};
let params = flash_op_params(&g, &flash_node, ¶ms_in).expect("derivable");
match params {
OpParams::FlashAttn {
k_len,
sk: sk_out,
sq,
..
} => {
assert_eq!(k_len, sk, "symbolic k_len prices at the capacity");
assert_eq!(sk_out, sk);
assert_eq!(sq, 1, "decode sq == 1");
}
_ => panic!("expected FlashAttn params"),
}
}
fn flash_variant_diamond() -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId) {
let (b, hq, d, sk) = (1usize, 8, 128, 512);
let dt = DType::F16;
let mut g = Graph::new();
let qc = node(&mut g, Op::Const, vec![], &[b, hq, 1, d], dt);
let k = node(&mut g, Op::Const, vec![], &[b, hq, sk, d], dt);
let v = node(&mut g, Op::Const, vec![], &[b, hq, sk, d], dt);
let q = node(&mut g, Op::Relu, vec![qc], &[b, hq, 1, d], dt);
let kt = node(
&mut g,
Op::Permute(vec![0, 1, 3, 2]),
vec![k],
&[b, hq, d, sk],
dt,
);
let scores = node(&mut g, Op::MatMul, vec![q, kt], &[b, hq, 1, sk], dt);
let attn = node(&mut g, Op::MatMul, vec![scores, v], &[b, hq, 1, d], dt);
let flash = node(
&mut g,
Op::Fused(
FusedOps::FLASH_ATTN,
FusedOpParams::FlashAttn {
softmax_scale: 0.1,
causal: true,
window_size_left: None,
window_size_right: None,
softcap: None,
k_len: Some(DynScalar::Concrete(sk)),
},
),
vec![q, k, v],
&[b, hq, 1, d],
dt,
);
g.set_target_backend(kt, BackendId::Cuda);
g.set_target_backend(scores, BackendId::Cuda);
g.set_target_backend(attn, BackendId::Cuda);
g.set_target_backend(flash, BackendId::Cuda);
let reconverge = node(&mut g, Op::Relu, vec![attn], &[b, hq, 1, d], dt);
let mut br = g.open_branch(q);
br.add_arm(attn);
br.add_arm(flash);
let branch = br
.finalize_branches(&mut g, reconverge)
.expect("well-formed 2-arm decode branch")
.expect("2 arms survive");
let post = node(&mut g, Op::Tanh, vec![reconverge], &[b, hq, 1, d], dt);
(g, branch, attn, flash, reconverge, post)
}
fn decode_keys() -> (SizeClass, SizeClass, SizeClass) {
let (hq, d, sk) = (8usize, 128, 512);
(
SizeClass::matmul(1, sk, d), SizeClass::matmul(1, d, sk), SizeClass::attention(hq, sk, d),
)
}
#[test]
fn judge_measured_flash_wins_the_decode_bake() {
let (mut g, branch, attn, flash, reconverge, post) = flash_variant_diamond();
let dt = DType::F16;
let (k_scores, k_attn, k_flash) = decode_keys();
let before = lower_runs_arm0(&g, &[post]);
assert!(
before.contains(&attn) && !before.contains(&flash),
"before the bake the decomposed region wins (arm 0); order={before:?}",
);
let mut judge = HashMapJudge::new();
judge.insert(OpKind::MatMul, dt, k_scores, BackendId::Cuda, "", 500, 0);
judge.insert(OpKind::MatMul, dt, k_attn, BackendId::Cuda, "", 500, 0);
judge.insert(OpKind::FlashAttn, dt, k_flash, BackendId::Cuda, "", 400, 0);
let cost = |g: &Graph, b: NodeId, arm: usize, i: &[NodeId]| -> Option<u64> {
decode_arm_composite_ns_judged(g, b, arm, i, BackendId::Cuda, Some(&judge))
};
let baked = bake_variant_branches(&mut g, &[post], &cost);
assert_eq!(
baked, 1,
"measured flash is strictly cheaper ⇒ the branch bakes to it"
);
assert_eq!(
g.node(branch).inputs,
vec![flash],
"branch collapsed to the flash arm"
);
assert!(
g.node(reconverge).inputs.contains(&flash),
"merge rewired to flash"
);
let after = lower_runs_arm0(&g, &[post]);
assert!(
after.contains(&flash),
"flash realized after the bake; order={after:?}"
);
assert!(
!after.contains(&attn),
"the decomposed region is pruned; order={after:?}"
);
}
#[test]
fn judge_measured_flash_slower_keeps_the_region() {
let (mut g, branch, attn, flash, _recon, post) = flash_variant_diamond();
let dt = DType::F16;
let (k_scores, k_attn, k_flash) = decode_keys();
let mut judge = HashMapJudge::new();
judge.insert(OpKind::MatMul, dt, k_scores, BackendId::Cuda, "", 500, 0);
judge.insert(OpKind::MatMul, dt, k_attn, BackendId::Cuda, "", 500, 0);
judge.insert(OpKind::FlashAttn, dt, k_flash, BackendId::Cuda, "", 2000, 0);
let cost = |g: &Graph, b: NodeId, arm: usize, i: &[NodeId]| -> Option<u64> {
decode_arm_composite_ns_judged(g, b, arm, i, BackendId::Cuda, Some(&judge))
};
let baked = bake_variant_branches(&mut g, &[post], &cost);
assert_eq!(
baked, 0,
"measured flash is slower ⇒ arm 0 (the region) stands"
);
assert_eq!(
g.node(branch).inputs,
vec![attn],
"branch collapsed to arm 0"
);
let after = lower_runs_arm0(&g, &[post]);
assert!(
after.contains(&attn) && !after.contains(&flash),
"region realized (oracle)"
);
}
#[test]
fn no_oracle_is_byte_identical_to_layer1() {
let (mut g, branch, attn, flash, _recon, post) = flash_variant_diamond();
let interiors = arm_interiors(&g, branch);
for (arm, interior) in interiors.iter().enumerate() {
assert_eq!(
decode_arm_composite_ns_judged(&g, branch, arm, interior, BackendId::Cuda, None),
decode_arm_composite_ns(&g, branch, arm, interior, BackendId::Cuda),
"judged(None) must equal the Layer-1 provider for arm {arm}",
);
}
let cost = |g: &Graph, b: NodeId, arm: usize, i: &[NodeId]| -> Option<u64> {
decode_arm_composite_ns_judged(g, b, arm, i, BackendId::Cuda, None)
};
let baked = bake_variant_branches(&mut g, &[post], &cost);
assert_eq!(
baked, 0,
"no oracle ⇒ Layer-1 path ⇒ arm 0 (flash unbound on a CPU build)"
);
assert_eq!(g.node(branch).inputs, vec![attn]);
let _ = flash;
}
#[test]
fn judge_without_flash_cell_falls_to_capability_gate() {
let (mut g, branch, attn, flash, _recon, post) = flash_variant_diamond();
let dt = DType::F16;
let (k_scores, k_attn, _k_flash) = decode_keys();
let mut judge = HashMapJudge::new();
judge.insert(OpKind::MatMul, dt, k_scores, BackendId::Cuda, "", 1, 0);
judge.insert(OpKind::MatMul, dt, k_attn, BackendId::Cuda, "", 1, 0);
let cost = |g: &Graph, b: NodeId, arm: usize, i: &[NodeId]| -> Option<u64> {
decode_arm_composite_ns_judged(g, b, arm, i, BackendId::Cuda, Some(&judge))
};
let baked = bake_variant_branches(&mut g, &[post], &cost);
if !fused_kernel_available(FusedOps::FLASH_ATTN, BackendId::Cuda) {
assert_eq!(baked, 0, "no flash measurement + unbound kernel ⇒ arm 0");
assert_eq!(g.node(branch).inputs, vec![attn]);
}
let _ = flash;
}
#[test]
fn hybrid_sum_mixes_measured_and_layer1_for_the_region() {
let (mut g, branch, attn, flash, _recon, post) = flash_variant_diamond();
let dt = DType::F16;
let (k_scores, _k_attn, k_flash) = decode_keys();
let mut judge = HashMapJudge::new();
judge.insert(OpKind::MatMul, dt, k_scores, BackendId::Cuda, "", 500, 0); judge.insert(OpKind::FlashAttn, dt, k_flash, BackendId::Cuda, "", 400, 0);
let region = arm_interiors(&g, branch)[0].clone();
let hybrid =
decode_arm_composite_ns_judged(&g, branch, 0, ®ion, BackendId::Cuda, Some(&judge))
.expect("region prices");
let layer1_attn = decode_arm_composite_ns(&g, branch, 0, &[attn], BackendId::Cuda)
.expect("attn prices on Layer-1");
assert_eq!(
hybrid,
500 + layer1_attn,
"hybrid region = measured scores (500) + Layer-1 attn ({layer1_attn})",
);
let cost = |g: &Graph, b: NodeId, arm: usize, i: &[NodeId]| -> Option<u64> {
decode_arm_composite_ns_judged(g, b, arm, i, BackendId::Cuda, Some(&judge))
};
let baked = bake_variant_branches(&mut g, &[post], &cost);
assert_eq!(
baked, 1,
"measured flash beats the hybrid region ⇒ bakes to flash"
);
assert_eq!(g.node(branch).inputs, vec![flash]);
}
#[test]
fn judge_does_not_touch_a_placement_branch() {
let (mut g, branch, attn, flash, _recon, post) = flash_variant_diamond();
g.set_target_backend(flash, BackendId::Cpu);
let dt = DType::F16;
let (_ks, _ka, k_flash) = decode_keys();
let mut judge = HashMapJudge::new();
judge.insert(OpKind::FlashAttn, dt, k_flash, BackendId::Cpu, "", 1, 0);
let cost = |g: &Graph, b: NodeId, arm: usize, i: &[NodeId]| -> Option<u64> {
let backend = g.target_backend(g.node(b).inputs.first().copied()?)?;
decode_arm_composite_ns_judged(g, b, arm, i, backend, Some(&judge))
};
let baked = bake_variant_branches(&mut g, &[post], &cost);
assert_eq!(
baked, 0,
"a placement branch is never baked, even with a flash-loving judge"
);
assert_eq!(
g.node(branch).inputs,
vec![attn, flash],
"placement branch stays a live 2-arm decision point (runtime picker owns it)",
);
}
}