Skip to main content

fuel_dispatch/
variant_bake.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! **Optimize-time kernel-variant baking** — the same-device arm selector.
3//!
4//! ## The gap this closes
5//!
6//! `optimize_graph` records `Op::Branch` decision points whose arms are
7//! competing routes. Two *kinds* of arm coexist under one representation:
8//!
9//! - **Placement arms** — the same op on *different* `(backend, device)`
10//!   pairs (CPU vs. CUDA). These stay live `Op::Branch` points, resolved at
11//!   dispatch by the runtime route picker on live load / VRAM
12//!   ([`crate::ranker::route_picker`], 06-runtime).
13//! - **Kernel-variant arms** — *different implementations of the same op on
14//!   the SAME device* (the decomposed attention region vs. a fused flash
15//!   kernel, both on CUDA). Per 04-optimization these are **"largely baked
16//!   at optimize time"**, NOT deferred to the runtime picker.
17//!
18//! The shipped runtime picker resolves only placement arms: it ranks arms by
19//! their `(backend, device)` keyed on arm 0's op, so two same-device arms map
20//! to the same candidate and always resolve to **arm 0** (the finding in
21//! commit `c7bfc1b5`). A same-device fused variant — e.g. the CUDA flash
22//! decode arm from [`crate::decode_flash::offer_decode_flash_arm`] — can be
23//! *offered* but never *selected*.
24//!
25//! ## What this module does (the bake)
26//!
27//! [`bake_variant_branches`] runs at optimize time (Picker 1, where costs +
28//! caps + the Judge oracle are in hand — NOT the executor). For every
29//! reachable **same-device** variant branch it:
30//!
31//! 1. costs arm 0 (the decomposed-region oracle) and each variant arm;
32//! 2. picks the **unique** variant that is **strictly cheaper** than arm 0;
33//! 3. **collapses** the branch to that winner via
34//!    [`fuel_graph::Graph::collapse_variant_branch`] (the merge is rewired to
35//!    the winner; the branch becomes an inert single arm — "the Branch
36//!    collapses" of 04-optimization).
37//!
38//! **Conservative defaults (the oracle stands):** a tie, an unknown/sentinel
39//! cost, or a variant whose kernel is not available on the placed device all
40//! resolve to **arm 0** — the decomposed correctness oracle. **Placement
41//! branches (arms on ≥2 devices) are never touched** — they are left live for
42//! the runtime picker. A graph with no same-device variant branch (every
43//! CPU/Vulkan build today, since no CUDA flash arm is offered there) is a
44//! **no-op**, so the byte-exact suites are unaffected by construction.
45//!
46//! ## Where it rides
47//!
48//! The bake mutates the graph **in place** during `optimize_graph`, so the
49//! baked choice rides [`crate::optimize::OptimizedGraph`] (which derives its
50//! dispatch order from the graph) with no extra state — plan-once persistent
51//! decode bakes once per generation and every realize lowers the collapsed
52//! graph.
53//!
54//! ## What the full version adds
55//!
56//! This is the smallest constitutional version. The full version adds:
57//! **Judge-refined variant ranking** (a Layer-2 measurement overriding the
58//! Layer-1 composed cost — plugs into the cost closure); **Pareto retention
59//! of both arms** (keep the variant as a runtime-selectable path instead of
60//! pruning it, once the picker can distinguish same-device variants); and, if
61//! it ever becomes constitutional, **runtime load-adaptive variant
62//! switching**. Today variant choice is baked and the loser is pruned.
63
64use std::collections::HashSet;
65
66use fuel_graph::registry::{FusedOpParams, FusedOps};
67use fuel_graph::{Graph, NodeId, Op, branches_in_topo_order};
68use fuel_ir::backend::{BackendCapabilities, SubstrateClass, TransferPath};
69use fuel_ir::dispatch::SizeClass;
70use fuel_ir::probe::BackendId;
71use fuel_ir::{DType, DeviceLocation, DynScalar, Shape};
72
73use crate::cost::{cost_flash_decoding_cuda, cost_matmul_cpu, default_cost_for_op_kind};
74use crate::fused::CostEstimate;
75use crate::kernel::OpParams;
76use crate::pipelined::op_to_op_kind;
77use crate::ranker::{JudgeOracle, composite_ns, default_backend_rates};
78use crate::runtime_fused_kernels::fused_kernel_available;
79
80/// The composite-nanosecond cost of a branch arm, or `None` when it is
81/// **unknown or inadmissible** — an unpriced/sentinel-cost op, or a variant
82/// whose kernel is not available on the placed device. `None` means "this arm
83/// cannot win", so the conservative arm-0 oracle stands.
84///
85/// Arguments: `(graph, branch, arm_index, arm_interior)` where `arm_interior`
86/// is the arm's interior node set (the nodes on paths `diverge → exit`, arm 0's
87/// being the decomposed region and a fused arm's being the single fused node).
88pub type ArmCostFn<'a> = dyn Fn(&Graph, NodeId, usize, &[NodeId]) -> Option<u64> + 'a;
89
90std::thread_local! {
91    /// Per-thread cumulative count of same-device variant branches baked to a
92    /// **variant** arm (arm > 0) — i.e. a fused variant (e.g. the CUDA
93    /// flash-decode arm) that won on cost and collapsed the branch. Bumped by
94    /// [`bake_variant_branches`]'s return value. Lets a downstream realize
95    /// consumer (a live bench / test) confirm the flash arm was actually
96    /// **picked**, not merely offered — the `optimize_graph` call site discards
97    /// the return value, so this is the only observation seam without widening
98    /// that signature. Mirrors `pipelined_bridge::OPTIMIZE_CALLS_TL`.
99    static VARIANT_BAKES_TL: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
100}
101
102/// The current thread's cumulative variant-bake count.
103/// Read it before and after an `optimize_graph`/realize call and diff to learn
104/// how many branches this pass collapsed to a fused variant winner — e.g. a
105/// BF16 CUDA decode step should bake one flash-decode arm per layer once the
106/// flash-arm capability seam is bridged. Thread-local so a single-threaded
107/// realize sequence isn't polluted by concurrent test threads.
108pub fn variant_bakes_thread_local() -> usize {
109    VARIANT_BAKES_TL.with(|c| c.get())
110}
111
112/// Bake same-device kernel-variant branches to their cost winner (see the
113/// module docs). Returns the number of branches collapsed **to a variant arm**
114/// (arm > 0) — a diagnostic the caller / tests assert on, also accumulated into
115/// the thread-local [`variant_bakes_thread_local`] counter. Never panics: a
116/// structural surprise from [`Graph::collapse_variant_branch`] is ignored
117/// rather than crashing (never-panic on a production path).
118pub fn bake_variant_branches(
119    graph: &mut Graph,
120    roots: &[NodeId],
121    arm_cost: &ArmCostFn<'_>,
122) -> usize {
123    // Decide first (immutable analysis over the whole set), then mutate — a
124    // collapse rewires edges, so we must not analyse against a half-mutated
125    // graph. Topo order over `reconverge_at` is the picker's order; it does
126    // not matter for independent same-device bakes but keeps parity.
127    let branches = branches_in_topo_order(graph, roots);
128    let mut decisions: Vec<(NodeId, usize)> = Vec::new();
129
130    for branch in branches {
131        let arms = graph.node(branch).inputs.clone();
132        if arms.len() < 2 {
133            continue; // already inert — no decision
134        }
135        // Same-device gate: every arm must resolve to the SAME backend. A
136        // placement branch (arms on ≥2 backends) is left LIVE for the runtime
137        // route picker; an unstamped arm (no `target_backend`) is not a
138        // determinate variant branch, so skip it conservatively.
139        let Some(backend0) = graph.target_backend(arms[0]) else {
140            continue;
141        };
142        if !arms
143            .iter()
144            .all(|&a| graph.target_backend(a) == Some(backend0))
145        {
146            continue; // placement branch → runtime picker owns it
147        }
148
149        // Cost the oracle (arm 0). An unknown oracle cost ⇒ leave arm 0.
150        let interiors = arm_interiors(graph, branch);
151        let Some(c0) = arm_cost(graph, branch, 0, &interiors[0]) else {
152            continue;
153        };
154
155        // The winner is the UNIQUE variant strictly cheaper than the oracle.
156        // A tie at the cheapest cost, or no cheaper admissible variant, ⇒
157        // arm 0 (the conservative oracle default).
158        let mut best: Option<(usize, u64)> = None;
159        let mut tie_at_best = false;
160        // Iterating `interiors` rather than `0..arms.len()` is behaviour-
161        // identical because both derive from `graph.node(branch).inputs`:
162        // `arms` clones it and `arm_interiors` maps over it, so the lengths
163        // are equal by construction. Worth stating — if they could differ,
164        // this rewrite would silently truncate where the index form panicked.
165        for (w, interior) in interiors.iter().enumerate().skip(1) {
166            let Some(cw) = arm_cost(graph, branch, w, interior) else {
167                continue; // unknown / capability-missing ⇒ cannot win
168            };
169            if cw >= c0 {
170                continue; // not strictly cheaper than the oracle
171            }
172            match best {
173                None => best = Some((w, cw)),
174                Some((_, bc)) if cw < bc => {
175                    best = Some((w, cw));
176                    tie_at_best = false;
177                }
178                Some((_, bc)) if cw == bc => tie_at_best = true,
179                _ => {}
180            }
181        }
182        let winner = if tie_at_best {
183            0
184        } else {
185            best.map(|(w, _)| w).unwrap_or(0)
186        };
187        decisions.push((branch, winner));
188    }
189
190    // Apply: collapse every same-device variant branch — to its winning
191    // variant, else to arm 0 (dropping the offered-but-unpicked variant arms).
192    // Either way no same-device variant branch survives optimize; only
193    // placement branches remain for the runtime picker.
194    let mut baked_to_variant = 0usize;
195    for (branch, winner) in decisions {
196        if winner != 0 {
197            baked_to_variant += 1;
198        }
199        let _ = graph.collapse_variant_branch(branch, winner);
200    }
201    if baked_to_variant > 0 {
202        VARIANT_BAKES_TL.with(|c| c.set(c.get() + baked_to_variant));
203    }
204    baked_to_variant
205}
206
207/// The per-arm **interior** node sets of a branch — the nodes on paths
208/// `diverge → exit`, excluding the shared diverge prefix. Mirrors
209/// `fuel_graph::run`'s cone/shared-prefix derivation (the op carries only
210/// `reconverge_at`, so the diverge is recovered as the intersection of the
211/// arm exits' backward cones). Index `i` is arm `i`'s interior; a fused arm's
212/// interior is typically the single fused node, arm 0's is the decomposed
213/// region.
214fn arm_interiors(graph: &Graph, branch: NodeId) -> Vec<Vec<NodeId>> {
215    let arm_exits = graph.node(branch).inputs.clone();
216    let cones: Vec<HashSet<NodeId>> = arm_exits.iter().map(|&e| backward_cone(graph, e)).collect();
217    if cones.is_empty() {
218        return Vec::new();
219    }
220    let mut shared: HashSet<NodeId> = cones[0].clone();
221    for c in &cones[1..] {
222        shared = shared.intersection(c).copied().collect();
223    }
224    cones
225        .iter()
226        .map(|cone| {
227            cone.iter()
228                .copied()
229                .filter(|n| !shared.contains(n))
230                .collect()
231        })
232        .collect()
233}
234
235/// Backward-reachable cone of `from` (the node and all transitive inputs).
236fn backward_cone(graph: &Graph, from: NodeId) -> HashSet<NodeId> {
237    let mut seen: HashSet<NodeId> = HashSet::new();
238    let mut stack = vec![from];
239    while let Some(n) = stack.pop() {
240        if !seen.insert(n) {
241            continue;
242        }
243        for &inp in &graph.node(n).inputs {
244            if !seen.contains(&inp) {
245                stack.push(inp);
246            }
247        }
248    }
249    seen
250}
251
252/// The **production cost provider** (04-optimization "cost-from-decompose" +
253/// the region composed-Layer-1 sum). Folds a Layer-1 [`CostEstimate`] over the
254/// arm's interior and converts it to a composite-ns figure on the placed
255/// `backend`'s throughput roofline. This is the defensible v1 the session
256/// prompt blesses: **compare the fused arm's declared cost against the region's
257/// composed Layer-1 sum over its nodes.**
258///
259/// - a `Op::Fused(FLASH_ATTN, …)` arm is priced by [`cost_flash_decoding_cuda`]
260///   (its declared decode cost — work scales with the live prefix `k_len`,
261///   not the physical capacity), gated on the CUDA flash kernel being bound
262///   (capability: absent ⇒ `None` ⇒ the oracle stands);
263/// - an `Op::MatMul` interior node (the dominant decode-region cost) is priced
264///   with its geometry derived from operand shapes;
265/// - any other op with an `op_to_op_kind` mapping is priced by its Layer-1
266///   family at `OpParams::None` (the shape-derivable floor — the same
267///   documented approximation `fused_cost` uses; a param-carrying interior op
268///   under-prices here and is refined by the Judge, biasing conservatively
269///   toward the oracle);
270/// - the region's arms are summed as **sequential** launches
271///   (`Σ composite_ns`), so the fused arm's single-launch win over an N-launch
272///   region is visible.
273///
274/// Symbolic `k_len` (persistent decode): the flash arm is priced at the KV
275/// **capacity** as the representative prefix. Both the flash cost and the
276/// decomposed region scale ~linearly in the prefix, so the winner is stable
277/// across the concrete prefix — the capacity is a sound representative extent
278/// for the plan-once bake.
279///
280/// Returns `None` (⇒ arm 0) when the arm prices to zero (nothing costable —
281/// an unknown/sentinel region) so a zero never spuriously "wins".
282pub fn decode_arm_composite_ns(
283    graph: &Graph,
284    _branch: NodeId,
285    _arm_idx: usize,
286    interior: &[NodeId],
287    backend: BackendId,
288) -> Option<u64> {
289    let (compute_rate, mem_bw) = default_backend_rates(backend);
290    let caps = neutral_caps(backend, compute_rate, mem_bw);
291    let mut total_ns: u64 = 0;
292    let mut any = false;
293    for &nid in interior {
294        let Some(cost) = node_layer1_cost(graph, nid, backend, &caps) else {
295            continue;
296        };
297        any = true;
298        total_ns = total_ns.saturating_add(composite_ns(&cost, compute_rate, mem_bw));
299    }
300    if !any || total_ns == 0 {
301        return None; // nothing costable ⇒ oracle stands (no spurious zero win)
302    }
303    Some(total_ns)
304}
305
306/// The **Layer-2-aware** cost provider — the slice-4 payoff. Consults the Judge
307/// oracle (empirical measured latency, 06-optimization Layer-2) **first** per
308/// interior node, falling back to the [`decode_arm_composite_ns`] Layer-1
309/// composite for any node the Judge hasn't measured. Summed per arm exactly as
310/// the Layer-1 provider does, so the comparison stays apples-to-apples:
311///
312/// - **arm 0** (the decomposed region) = `Σ` over its primitives of
313///   `measured(op, dtype, size_class, backend) ?? layer1(op)`;
314/// - **arm 1** (the fused flash node) = `measured(FlashAttn, …) ?? layer1(flash)`.
315///
316/// A measured latency is used **directly** (it is already a wall-clock ns, the
317/// same convention [`crate::ranker::cost::compute_static_costs`] uses when it
318/// folds the Judge cell into `kernel_overhead_ns`), so flash's real
319/// algorithm-changing win (no materialized attention matrix, one launch —
320/// smaller measured latency than the region's `N` measured launches) becomes
321/// visible where Layer-1 alone saw a FLOP-for-FLOP tie and the conservative
322/// bake kept arm 0.
323///
324/// **A Judge measurement is evidence of capability.** A cell exists only
325/// because the kernel was actually profiled (it ran), so a measured flash cell
326/// is used even when the Layer-1 capability gate ([`fused_kernel_available`])
327/// would decline it — the gate only guards the *fallback* Layer-1 path (no
328/// measurement + unbound kernel ⇒ `None` ⇒ the oracle stands, unchanged).
329///
330/// **Hybrid sum.** When some of an arm's nodes are Judge-covered and others are
331/// not, measured cells and Layer-1 estimates are summed together — directionally
332/// better than an all-Layer-1 fold, and the conservative tie-break in
333/// [`bake_variant_branches`] (strictly-cheaper-or-arm-0) still protects against
334/// a bad partial.
335///
336/// **`kernel_source`.** The bake has no per-node candidate in hand, so it
337/// queries the legacy / default (`""`) cell — where a single-impl flash/matmul
338/// kernel registers. Threading a per-arm `kernel_source` is a follow-up; `""`
339/// keeps the born-red and single-impl production apples-to-apples.
340///
341/// With `judge == None` this is **byte-identical** to [`decode_arm_composite_ns`]
342/// (it delegates), so the no-Judge production path and the persistent
343/// byte-exact suites are unaffected by construction.
344pub fn decode_arm_composite_ns_judged(
345    graph: &Graph,
346    branch: NodeId,
347    arm_idx: usize,
348    interior: &[NodeId],
349    backend: BackendId,
350    judge: Option<&dyn JudgeOracle>,
351) -> Option<u64> {
352    // No oracle ⇒ the Layer-1-only provider, byte-identical to today. The
353    // no-Judge production path + the persistent byte-exact suites are
354    // unaffected by construction.
355    let Some(judge) = judge else {
356        return decode_arm_composite_ns(graph, branch, arm_idx, interior, backend);
357    };
358
359    // Layer-2 FIRST, per interior node, with a Layer-1 fallback (the hybrid
360    // sum): a measured wall-clock latency is used directly (same convention as
361    // `compute_static_costs`'s `kernel_overhead_ns` fold); an unmeasured node
362    // falls back to its Layer-1 composite. Summed as sequential launches so the
363    // fused arm's single measured launch is compared against the region's `N`
364    // measured/Layer-1 launches apples-to-apples.
365    let (compute_rate, mem_bw) = default_backend_rates(backend);
366    let caps = neutral_caps(backend, compute_rate, mem_bw);
367    let mut total_ns: u64 = 0;
368    let mut any = false;
369    for &nid in interior {
370        // A Judge measurement is evidence of capability (a cell exists only
371        // because the kernel ran), so a measured node is admissible even if the
372        // Layer-1 capability gate would decline it. The gate guards only the
373        // fallback below.
374        let ns = match node_measured_ns(graph, nid, backend, judge) {
375            Some(measured) => Some(measured),
376            None => node_layer1_cost(graph, nid, backend, &caps)
377                .map(|cost| composite_ns(&cost, compute_rate, mem_bw)),
378        };
379        if let Some(ns) = ns {
380            any = true;
381            total_ns = total_ns.saturating_add(ns);
382        }
383    }
384    if !any || total_ns == 0 {
385        return None; // nothing costable ⇒ oracle stands (no spurious zero win)
386    }
387    Some(total_ns)
388}
389
390/// The measured (Layer-2) latency for one interior node's Judge cell, keyed the
391/// SAME way the ranker + Judge producer key it: `(op, principal_dtype,
392/// SizeClass::for_op(op, input_shapes), backend, "")`. `None` when the node has
393/// no [`op_to_op_kind`] mapping (a view/leaf) or the Judge hasn't measured that
394/// cell. The principal dtype is the first operand's dtype (the
395/// [`crate::ranker::cost::compute_static_costs`] convention), so a matmul /
396/// flash cell the Judge profiled is found by the SAME `for_op` key here.
397fn node_measured_ns(
398    graph: &Graph,
399    nid: NodeId,
400    backend: BackendId,
401    judge: &dyn JudgeOracle,
402) -> Option<u64> {
403    let node = graph.node(nid);
404    let kind = op_to_op_kind(&node.op)?;
405    let principal_dtype = match node.inputs.first() {
406        Some(&i) => graph.node(i).dtype,
407        None => node.dtype, // nullary — has no OpKind mapping anyway
408    };
409    let input_shapes: Vec<Shape> = node
410        .inputs
411        .iter()
412        .map(|&i| graph.node(i).shape.clone())
413        .collect();
414    let size_class = SizeClass::for_op(kind, &input_shapes);
415    judge.measured_latency_ns(kind, principal_dtype, size_class, backend, "", 0)
416}
417
418/// Layer-1 [`CostEstimate`] for one interior node (see [`decode_arm_composite_ns`]).
419/// `None` for a node that carries no priceable compute (a view/leaf, or a
420/// flash arm whose kernel is not bound — the capability gate).
421fn node_layer1_cost(
422    graph: &Graph,
423    nid: NodeId,
424    backend: BackendId,
425    caps: &BackendCapabilities,
426) -> Option<CostEstimate> {
427    let node = graph.node(nid);
428    match &node.op {
429        // The fused flash decode arm: priced by its declared decode cost,
430        // gated on the CUDA flash kernel being bound (capability).
431        Op::Fused(fid, params) if *fid == FusedOps::FLASH_ATTN => {
432            if !fused_kernel_available(FusedOps::FLASH_ATTN, backend) {
433                return None; // capability-missing ⇒ arm cannot win
434            }
435            let op_params = flash_op_params(graph, node, params)?;
436            let dtypes = [node.dtype, node.dtype];
437            Some(cost_flash_decoding_cuda(&[], &dtypes, &op_params, caps))
438        }
439        // MatMul — the dominant decode-region cost; geometry from shapes.
440        Op::MatMul => {
441            let op_params = matmul_op_params(graph, node)?;
442            let dtypes = [node.dtype, node.dtype, node.dtype];
443            Some(cost_matmul_cpu(&[], &dtypes, &op_params, caps))
444        }
445        // Any other primitive with an OpKind mapping: its Layer-1 family at
446        // the shape-derivable floor (OpParams::None), per the fused_cost
447        // precedent. Shapes follow `[input1, .., inputN, output]`.
448        other => {
449            let kind = op_to_op_kind(other)?;
450            let mut shapes: Vec<Shape> = node
451                .inputs
452                .iter()
453                .map(|&i| graph.node(i).shape.clone())
454                .collect();
455            shapes.push(node.shape.clone());
456            let mut dtypes: Vec<DType> = node.inputs.iter().map(|&i| graph.node(i).dtype).collect();
457            dtypes.push(node.dtype);
458            Some(default_cost_for_op_kind(kind)(
459                &shapes,
460                &dtypes,
461                &OpParams::None,
462                caps,
463            ))
464        }
465    }
466}
467
468/// Derive `OpParams::Matmul` geometry from a `MatMul` node's operand shapes:
469/// `A[.., m, k] · B[.., k, n] → [.., m, n]`. `None` if either operand is
470/// rank < 2 (nothing to cost).
471fn matmul_op_params(graph: &Graph, node: &fuel_graph::Node) -> Option<OpParams> {
472    let a = graph.node(*node.inputs.first()?).shape.clone();
473    let b = graph.node(*node.inputs.get(1)?).shape.clone();
474    let ad = a.dims();
475    let bd = b.dims();
476    if ad.len() < 2 || bd.len() < 2 {
477        return None;
478    }
479    let m = ad[ad.len() - 2];
480    let k = ad[ad.len() - 1];
481    let n = bd[bd.len() - 1];
482    let lhs_batch_dims: Vec<usize> = ad[..ad.len() - 2].to_vec();
483    let rhs_batch_dims: Vec<usize> = bd[..bd.len() - 2].to_vec();
484    // Cost/bake geometry only — the row count is the capacity `m` (a
485    // dynamic-M matmul costs at its capacity, a safe over-estimate).
486    Some(OpParams::Matmul {
487        lhs_batch_dims,
488        rhs_batch_dims,
489        m,
490        n,
491        k,
492        m_compute: crate::kernel::MatmulM::All,
493    })
494}
495
496/// Derive `OpParams::FlashAttn` for the decode cost from the flash node's
497/// `[q, k, v, ..]` inputs + its `FusedOpParams::FlashAttn`. `q = [b, hq, sq, d]`,
498/// `k = [b, hkv, sk, d]`. A symbolic `k_len` prices at the KV capacity `sk`
499/// (the representative prefix — see [`decode_arm_composite_ns`]).
500fn flash_op_params(
501    graph: &Graph,
502    node: &fuel_graph::Node,
503    params: &FusedOpParams,
504) -> Option<OpParams> {
505    let FusedOpParams::FlashAttn {
506        softmax_scale,
507        causal,
508        window_size_left,
509        window_size_right,
510        softcap,
511        k_len,
512    } = params
513    else {
514        return None;
515    };
516    let q = graph.node(*node.inputs.first()?).shape.clone();
517    let kv = graph.node(*node.inputs.get(1)?).shape.clone();
518    let qd = q.dims();
519    let kvd = kv.dims();
520    if qd.len() != 4 || kvd.len() != 4 {
521        return None;
522    }
523    let (b, hq, sq, d) = (qd[0], qd[1], qd[2], qd[3]);
524    let hkv = kvd[1];
525    let sk = kvd[2];
526    // Symbolic prefix ⇒ price at the capacity (representative extent).
527    let k_len_val = match k_len {
528        Some(DynScalar::Concrete(v)) => *v,
529        _ => sk,
530    };
531    Some(OpParams::FlashAttn {
532        b,
533        hq,
534        hkv,
535        sq,
536        sk,
537        d,
538        k_len: k_len_val,
539        softmax_scale: *softmax_scale,
540        causal: *causal,
541        window_size_left: *window_size_left,
542        window_size_right: *window_size_right,
543        softcap: *softcap,
544    })
545}
546
547/// A minimal [`BackendCapabilities`] carrying only the backend id + its
548/// throughput rates — the Layer-1 cost families ignore the rest of the struct;
549/// the roofline rates flow through [`composite_ns`] separately.
550fn neutral_caps(backend: BackendId, compute: f64, mem_bw: f64) -> BackendCapabilities {
551    BackendCapabilities {
552        backend_id: backend,
553        device_location: DeviceLocation::Cpu,
554        op_dtype_support: HashSet::new(),
555        required_alignment: 1,
556        access_granularity_bits: 8,
557        transfer_paths: vec![(DeviceLocation::Cpu, TransferPath::SameDevice)],
558        storage_substrate: SubstrateClass::HostBytes,
559        compute_throughput_flops_per_ns: compute,
560        mem_bandwidth_bytes_per_ns: mem_bw,
561    }
562}
563
564#[cfg(test)]
565mod tests {
566    use super::*;
567    use crate::ranker::judge::HashMapJudge;
568    use fuel_graph::{Node, lower_runs_arm0};
569    use fuel_ir::Shape;
570    use fuel_ir::dispatch::OpKind;
571
572    fn node(g: &mut Graph, op: Op, inputs: Vec<NodeId>, dims: &[usize], dt: DType) -> NodeId {
573        g.push(Node {
574            op,
575            inputs,
576            shape: Shape::from_dims(dims),
577            dtype: dt,
578        })
579    }
580
581    /// Build a same-device 2-arm variant branch mirroring the decode flash
582    /// shape: arm 0 is a 2-node "decomposed region" (Relu→Silu over the
583    /// diverge), arm 1 is a single "fused variant" node (Gelu). Both arms are
584    /// stamped `backend`. Returns `(graph, branch, arm0_exit, arm1, reconverge, post)`.
585    fn variant_diamond(backend: BackendId) -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId) {
586        let dt = DType::F32;
587        let mut g = Graph::new();
588        let pre = node(&mut g, Op::Const, vec![], &[4], dt);
589        let diverge = node(&mut g, Op::Relu, vec![pre], &[4], dt);
590        // arm 0 = a 2-node decomposed region.
591        let a0_mid = node(&mut g, Op::Relu, vec![diverge], &[4], dt);
592        let arm0 = node(&mut g, Op::Silu, vec![a0_mid], &[4], dt);
593        // arm 1 = a single fused-variant node.
594        let arm1 = node(&mut g, Op::GeluTanh, vec![diverge], &[4], dt);
595        g.set_target_backend(a0_mid, backend);
596        g.set_target_backend(arm0, backend);
597        g.set_target_backend(arm1, backend);
598        let reconverge = node(&mut g, Op::Relu, vec![arm0], &[4], dt);
599        let mut b = g.open_branch(diverge);
600        b.add_arm(arm0);
601        b.add_arm(arm1);
602        let branch = b
603            .finalize_branches(&mut g, reconverge)
604            .expect("well-formed 2-arm branch")
605            .expect("2 arms survive");
606        let post = node(&mut g, Op::Tanh, vec![reconverge], &[4], dt);
607        (g, branch, arm0, arm1, reconverge, post)
608    }
609
610    /// A cost closure that returns fixed per-arm costs by arm index.
611    fn fixed_costs(
612        costs: Vec<Option<u64>>,
613    ) -> impl Fn(&Graph, NodeId, usize, &[NodeId]) -> Option<u64> {
614        move |_g, _b, arm, _interior| costs.get(arm).copied().flatten()
615    }
616
617    // ===================================================================
618    // BORN-RED: a same-device variant arm is NEVER selected today (the
619    // runtime picker resolves same-device arms to arm 0). The bake makes
620    // the cheaper variant SELECTABLE by collapsing the branch to it.
621    // ===================================================================
622    #[test]
623    fn cheaper_variant_is_baked_and_becomes_the_route() {
624        let (mut g, branch, arm0, arm1, reconverge, post) = variant_diamond(BackendId::Cuda);
625
626        // (RED anchor) Before the bake, the default lowering realizes arm 0 —
627        // the same-device variant (arm 1) is offered but never selected.
628        let before = lower_runs_arm0(&g, &[post]);
629        assert!(
630            before.contains(&arm0) && !before.contains(&arm1),
631            "before the bake the same-device variant is never selected (arm 0 wins)",
632        );
633
634        // (GREEN) The variant (arm 1) is strictly cheaper ⇒ the bake collapses
635        // the branch to it.
636        let cost = fixed_costs(vec![Some(1000), Some(400)]); // arm0=1000, arm1=400
637        let baked = bake_variant_branches(&mut g, &[post], &cost);
638        assert_eq!(baked, 1, "one variant branch baked to its winner");
639
640        // The merge now reads the winner; the branch is collapsed.
641        assert!(
642            g.node(reconverge).inputs.contains(&arm1),
643            "merge rewired to the variant"
644        );
645        assert_eq!(
646            g.node(branch).inputs,
647            vec![arm1],
648            "branch collapsed to the winner"
649        );
650
651        // The default lowering now follows the baked variant (arm 1) and prunes
652        // arm 0's region — selectable with NO runtime pick.
653        let after = lower_runs_arm0(&g, &[post]);
654        assert!(
655            after.contains(&arm1),
656            "after the bake the variant is realized; order={after:?}"
657        );
658        assert!(
659            !after.contains(&arm0),
660            "arm 0's region is pruned; order={after:?}"
661        );
662    }
663
664    /// The `variant_bakes_thread_local` telemetry tracks the return value: a
665    /// winning-variant bake bumps the counter by 1, an arm-0 (oracle-wins) bake
666    /// leaves it unchanged. This is the seam a live BF16-CUDA-decode bench/test
667    /// reads to confirm the flash-decode arm was actually PICKED (baked to the
668    /// fused variant), not merely offered.
669    #[test]
670    fn variant_bakes_thread_local_tracks_the_return() {
671        // A winning variant ⇒ +1.
672        let before = variant_bakes_thread_local();
673        let (mut g1, _b1, _a0, _a1, _r1, post1) = variant_diamond(BackendId::Cuda);
674        let win = fixed_costs(vec![Some(1000), Some(400)]); // arm1 strictly cheaper
675        let baked = bake_variant_branches(&mut g1, &[post1], &win);
676        assert_eq!(baked, 1);
677        assert_eq!(
678            variant_bakes_thread_local() - before,
679            1,
680            "a winning-variant bake bumps the thread-local by its return count",
681        );
682
683        // Arm 0 wins (costlier variant) ⇒ counter unchanged.
684        let mid = variant_bakes_thread_local();
685        let (mut g2, _b2, _a0b, _a1b, _r2, post2) = variant_diamond(BackendId::Cuda);
686        let lose = fixed_costs(vec![Some(400), Some(1000)]); // arm1 costlier
687        let baked2 = bake_variant_branches(&mut g2, &[post2], &lose);
688        assert_eq!(baked2, 0);
689        assert_eq!(
690            variant_bakes_thread_local(),
691            mid,
692            "an oracle-wins bake leaves the thread-local unchanged",
693        );
694    }
695
696    /// GUARD: a costlier variant ⇒ arm 0 (the oracle). The branch collapses to
697    /// arm 0 (variant pruned), realize is byte-identical to today.
698    #[test]
699    fn costlier_variant_keeps_arm0() {
700        let (mut g, branch, arm0, arm1, _recon, post) = variant_diamond(BackendId::Cuda);
701        let cost = fixed_costs(vec![Some(400), Some(1000)]); // arm1 costlier
702        let baked = bake_variant_branches(&mut g, &[post], &cost);
703        assert_eq!(baked, 0, "no variant wins ⇒ nothing baked to a variant");
704        assert_eq!(
705            g.node(branch).inputs,
706            vec![arm0],
707            "branch collapsed to arm 0"
708        );
709        let after = lower_runs_arm0(&g, &[post]);
710        assert!(
711            after.contains(&arm0) && !after.contains(&arm1),
712            "arm 0 realized (oracle)"
713        );
714    }
715
716    /// GUARD: an unknown / sentinel variant cost ⇒ arm 0. `None` cannot win.
717    #[test]
718    fn unknown_variant_cost_keeps_arm0() {
719        let (mut g, _branch, arm0, arm1, _recon, post) = variant_diamond(BackendId::Cuda);
720        let cost = fixed_costs(vec![Some(1000), None]); // arm1 unknown
721        let baked = bake_variant_branches(&mut g, &[post], &cost);
722        assert_eq!(baked, 0, "unknown variant cost ⇒ arm 0 (conservative)");
723        let after = lower_runs_arm0(&g, &[post]);
724        assert!(
725            after.contains(&arm0) && !after.contains(&arm1),
726            "arm 0 realized"
727        );
728    }
729
730    /// GUARD: a tie between the oracle and the variant ⇒ arm 0.
731    #[test]
732    fn tie_keeps_arm0() {
733        let (mut g, _branch, arm0, arm1, _recon, post) = variant_diamond(BackendId::Cuda);
734        let cost = fixed_costs(vec![Some(500), Some(500)]); // equal ⇒ not strictly cheaper
735        let baked = bake_variant_branches(&mut g, &[post], &cost);
736        assert_eq!(baked, 0, "tie ⇒ arm 0 (variant not strictly cheaper)");
737        let after = lower_runs_arm0(&g, &[post]);
738        assert!(
739            after.contains(&arm0) && !after.contains(&arm1),
740            "arm 0 realized"
741        );
742    }
743
744    /// GUARD: capability-missing (modelled as a `None` variant cost, the way
745    /// [`decode_arm_composite_ns`] surfaces an unbound flash kernel) ⇒ arm 0.
746    #[test]
747    fn capability_missing_keeps_arm0() {
748        let (mut g, _branch, arm0, arm1, _recon, post) = variant_diamond(BackendId::Cuda);
749        // A provider that declines the variant arm (capability gate) but prices
750        // the oracle — exactly the None the flash capability gate returns.
751        let cost = |_g: &Graph, _b: NodeId, arm: usize, _i: &[NodeId]| -> Option<u64> {
752            if arm == 0 { Some(1000) } else { None }
753        };
754        let baked = bake_variant_branches(&mut g, &[post], &cost);
755        assert_eq!(baked, 0, "capability-missing variant ⇒ arm 0");
756        let after = lower_runs_arm0(&g, &[post]);
757        assert!(
758            after.contains(&arm0) && !after.contains(&arm1),
759            "arm 0 realized"
760        );
761    }
762
763    /// GUARD: a **placement** branch (arms on DIFFERENT backends) is UNTOUCHED
764    /// — it stays a live 2-arm decision point for the runtime picker, even
765    /// when the variant-shaped cost would prefer arm 1. The bake only ever
766    /// collapses same-device branches.
767    #[test]
768    fn placement_branch_is_untouched() {
769        let (mut g, branch, arm0, arm1, _recon, post) = variant_diamond(BackendId::Cuda);
770        // Re-stamp arm 1 onto a DIFFERENT backend ⇒ placement branch.
771        g.set_target_backend(arm1, BackendId::Cpu);
772        let cost = fixed_costs(vec![Some(1000), Some(1)]); // arm1 "cheaper", but placement
773        let baked = bake_variant_branches(&mut g, &[post], &cost);
774        assert_eq!(baked, 0, "a placement branch is never baked");
775        assert_eq!(
776            g.node(branch).inputs,
777            vec![arm0, arm1],
778            "placement branch stays a live 2-arm decision point (runtime picker owns it)",
779        );
780    }
781
782    /// GUARD: an unstamped branch (arms with no `target_backend`) is skipped —
783    /// not a determinate same-device variant branch.
784    #[test]
785    fn unstamped_branch_is_skipped() {
786        let dt = DType::F32;
787        let mut g = Graph::new();
788        let pre = node(&mut g, Op::Const, vec![], &[4], dt);
789        let diverge = node(&mut g, Op::Relu, vec![pre], &[4], dt);
790        let a0_mid = node(&mut g, Op::Relu, vec![diverge], &[4], dt);
791        let arm0 = node(&mut g, Op::Silu, vec![a0_mid], &[4], dt);
792        let arm1 = node(&mut g, Op::GeluTanh, vec![diverge], &[4], dt);
793        // NO target_backend stamps on the arms.
794        let reconverge = node(&mut g, Op::Relu, vec![arm0], &[4], dt);
795        let mut b = g.open_branch(diverge);
796        b.add_arm(arm0);
797        b.add_arm(arm1);
798        let branch = b.finalize_branches(&mut g, reconverge).unwrap().unwrap();
799        let post = node(&mut g, Op::Tanh, vec![reconverge], &[4], dt);
800        let cost = fixed_costs(vec![Some(1000), Some(1)]);
801        let baked = bake_variant_branches(&mut g, &[post], &cost);
802        assert_eq!(baked, 0, "unstamped branch is skipped");
803        assert_eq!(g.node(branch).inputs, vec![arm0, arm1], "branch untouched");
804    }
805
806    // ===================================================================
807    // The PRODUCTION cost provider: a decomposed attention region vs. the
808    // fused flash arm — flash WINS on the region-vs-fused Layer-1 fold.
809    // ===================================================================
810
811    /// The **region-vs-fused costing approach**, priced honestly. The
812    /// production provider folds a real Layer-1 cost over BOTH arm kinds — the
813    /// decomposed region (matmul-dominated fold) and the fused flash arm
814    /// (declared decode cost from derived `OpParams`). This proves the costing
815    /// path end-to-end; it deliberately does NOT force flash to "win" on
816    /// Layer-1: `cost_flash_decoding_cuda` gives flash the SAME FLOPs as the
817    /// region's two matmuls (they compute the same attention), so on the
818    /// coarse Layer-1 model the two are ~cost-equal and the conservative bake
819    /// keeps the oracle (arm 0). Flash's real win is an *algorithm-changing*
820    /// fusion (no materialized attention matrix, one launch) that the Judge's
821    /// Layer-2 measurement corrects downward — "a missed win until measured,
822    /// not an optimistic irreversible commit" (04-optimization).
823    #[test]
824    fn region_and_flash_arms_are_both_priced_by_the_provider() {
825        let (b, hq, d, sk) = (1usize, 8, 128, 512);
826        let dt = DType::F16;
827        let mut g = Graph::new();
828        let q = node(&mut g, Op::Const, vec![], &[b, hq, 1, d], dt);
829        let k = node(&mut g, Op::Const, vec![], &[b, hq, sk, d], dt);
830        let v = node(&mut g, Op::Const, vec![], &[b, hq, sk, d], dt);
831
832        // Decomposed region interior (two matmuls dominate).
833        let kt = node(
834            &mut g,
835            Op::Permute(vec![0, 1, 3, 2]),
836            vec![k],
837            &[b, hq, d, sk],
838            dt,
839        );
840        let scores = node(&mut g, Op::MatMul, vec![q, kt], &[b, hq, 1, sk], dt);
841        let attn = node(&mut g, Op::MatMul, vec![scores, v], &[b, hq, 1, d], dt);
842        let region: Vec<NodeId> = vec![kt, scores, attn];
843
844        // (1) The region folds to a real, nonzero composite cost — no binding
845        // needed (pure shape/FLOP fold).
846        let region_ns = decode_arm_composite_ns(&g, NodeId(0), 0, &region, BackendId::Cuda)
847            .expect("the decomposed region has costable compute (its two matmuls)");
848        assert!(region_ns > 0, "region prices to a real nonzero cost");
849
850        // (2) The fused flash arm's DECLARED decode cost, priced directly from
851        // derived OpParams (the provider's capability gate is bypassed here so
852        // the costing path is exercised on any build, incl. no-CUDA).
853        let flash_node = Node {
854            op: Op::Fused(
855                FusedOps::FLASH_ATTN,
856                FusedOpParams::FlashAttn {
857                    softmax_scale: 0.1,
858                    causal: true,
859                    window_size_left: None,
860                    window_size_right: None,
861                    softcap: None,
862                    k_len: Some(DynScalar::Concrete(sk)),
863                },
864            ),
865            inputs: vec![q, k, v],
866            shape: Shape::from_dims(&[b, hq, 1, d]),
867            dtype: dt,
868        };
869        let (cr, bw) = default_backend_rates(BackendId::Cuda);
870        let caps = neutral_caps(BackendId::Cuda, cr, bw);
871        let fp_full = decode_flash_cost_at(&g, &flash_node, sk, &caps, cr, bw);
872        let fp_small = decode_flash_cost_at(&g, &flash_node, 32, &caps, cr, bw);
873        assert!(
874            fp_full > 0 && fp_small > 0,
875            "flash decode cost is real + nonzero"
876        );
877        assert!(
878            fp_full > fp_small,
879            "the flash decode cost scales with the live prefix k_len \
880             ({fp_full} @512 > {fp_small} @32) — decode work is O(prefix)",
881        );
882
883        // (3) The provider's capability gate: without a bound CUDA flash kernel
884        // the flash ARM is inadmissible (None) ⇒ the oracle stands. (In a live
885        // CUDA build the kernel is bound and the arm prices instead.)
886        let flash = node(
887            &mut g,
888            Op::Fused(
889                FusedOps::FLASH_ATTN,
890                FusedOpParams::FlashAttn {
891                    softmax_scale: 0.1,
892                    causal: true,
893                    window_size_left: None,
894                    window_size_right: None,
895                    softcap: None,
896                    k_len: Some(DynScalar::Concrete(sk)),
897                },
898            ),
899            vec![q, k, v],
900            &[b, hq, 1, d],
901            dt,
902        );
903        let gated = decode_arm_composite_ns(&g, NodeId(0), 1, &[flash], BackendId::Cuda);
904        if fused_kernel_available(FusedOps::FLASH_ATTN, BackendId::Cuda) {
905            assert!(gated.is_some(), "bound flash kernel ⇒ arm priced");
906        } else {
907            assert!(
908                gated.is_none(),
909                "unbound flash kernel ⇒ arm inadmissible (oracle stands)"
910            );
911        }
912    }
913
914    /// Helper: the flash decode composite-ns at a given prefix (bypasses the
915    /// capability gate to exercise the declared-cost path on any build).
916    fn decode_flash_cost_at(
917        g: &Graph,
918        flash_node: &Node,
919        k_len: usize,
920        caps: &BackendCapabilities,
921        cr: f64,
922        bw: f64,
923    ) -> u64 {
924        let params = FusedOpParams::FlashAttn {
925            softmax_scale: 0.1,
926            causal: true,
927            window_size_left: None,
928            window_size_right: None,
929            softcap: None,
930            k_len: Some(DynScalar::Concrete(k_len)),
931        };
932        let op_params = flash_op_params(g, flash_node, &params).expect("derivable");
933        let dtypes = [flash_node.dtype, flash_node.dtype];
934        let cost = cost_flash_decoding_cuda(&[], &dtypes, &op_params, caps);
935        composite_ns(&cost, cr, bw)
936    }
937
938    /// The flash `OpParams` derivation prices a symbolic `k_len` at the KV
939    /// capacity (the representative prefix), so a plan-once persistent-decode
940    /// bake still produces a concrete, stable cost.
941    #[test]
942    fn symbolic_k_len_prices_at_capacity() {
943        let (b, hq, d, sk) = (1usize, 4, 64, 256);
944        let dt = DType::F16;
945        let mut g = Graph::new();
946        let q = node(&mut g, Op::Const, vec![], &[b, hq, 1, d], dt);
947        let k = node(&mut g, Op::Const, vec![], &[b, hq, sk, d], dt);
948        let v = node(&mut g, Op::Const, vec![], &[b, hq, sk, d], dt);
949        let flash = node(
950            &mut g,
951            Op::Fused(
952                FusedOps::FLASH_ATTN,
953                FusedOpParams::FlashAttn {
954                    softmax_scale: 0.1,
955                    causal: true,
956                    window_size_left: None,
957                    window_size_right: None,
958                    softcap: None,
959                    // Symbolic prefix (persistent decode).
960                    k_len: Some(DynScalar::Sym(fuel_ir::symbol::SymId(0))),
961                },
962            ),
963            vec![q, k, v],
964            &[b, hq, 1, d],
965            dt,
966        );
967        let flash_node = g.node(flash).clone();
968        let params_in = match &flash_node.op {
969            Op::Fused(_, p) => p.clone(),
970            _ => unreachable!(),
971        };
972        let params = flash_op_params(&g, &flash_node, &params_in).expect("derivable");
973        match params {
974            OpParams::FlashAttn {
975                k_len,
976                sk: sk_out,
977                sq,
978                ..
979            } => {
980                assert_eq!(k_len, sk, "symbolic k_len prices at the capacity");
981                assert_eq!(sk_out, sk);
982                assert_eq!(sq, 1, "decode sq == 1");
983            }
984            _ => panic!("expected FlashAttn params"),
985        }
986    }
987
988    // ===================================================================
989    // SLICE 4 (THE PAYOFF): the variant bake consults the Judge's MEASURED
990    // latency (Layer-2) per arm, so the CUDA flash arm WINS the
991    // decode-flash-vs-decomposed bake where it merely TIES on Layer-1. With
992    // an injected oracle this proves the SELECTION logic on a CPU build (no
993    // live GPU): the born-red flips arm 0 → arm 1 the moment the provider
994    // reads the Judge.
995    // ===================================================================
996
997    /// A same-device (CUDA) 2-arm DECODE variant branch mirroring the real
998    /// decode-flash bake: arm 0 is the decomposed attention region
999    /// (`Permute` → `MatMul` QKᵀ → `MatMul` PV), arm 1 is the fused
1000    /// `FlashAttn` node. `q` is a `Relu` over a const so a single Op::Branch
1001    /// diverge point dominates both arm exits; both arm exits are stamped
1002    /// CUDA (same-device). Returns
1003    /// `(graph, branch, region_exit, flash_exit, reconverge, post)`.
1004    fn flash_variant_diamond() -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId) {
1005        let (b, hq, d, sk) = (1usize, 8, 128, 512);
1006        let dt = DType::F16;
1007        let mut g = Graph::new();
1008        let qc = node(&mut g, Op::Const, vec![], &[b, hq, 1, d], dt);
1009        let k = node(&mut g, Op::Const, vec![], &[b, hq, sk, d], dt);
1010        let v = node(&mut g, Op::Const, vec![], &[b, hq, sk, d], dt);
1011        // The single DIVERGE point both arms read as their `q` operand.
1012        let q = node(&mut g, Op::Relu, vec![qc], &[b, hq, 1, d], dt);
1013        // arm 0 — the decomposed attention region (two matmuls dominate).
1014        let kt = node(
1015            &mut g,
1016            Op::Permute(vec![0, 1, 3, 2]),
1017            vec![k],
1018            &[b, hq, d, sk],
1019            dt,
1020        );
1021        let scores = node(&mut g, Op::MatMul, vec![q, kt], &[b, hq, 1, sk], dt);
1022        let attn = node(&mut g, Op::MatMul, vec![scores, v], &[b, hq, 1, d], dt);
1023        // arm 1 — the fused flash node (same exit shape & dtype as the region).
1024        let flash = node(
1025            &mut g,
1026            Op::Fused(
1027                FusedOps::FLASH_ATTN,
1028                FusedOpParams::FlashAttn {
1029                    softmax_scale: 0.1,
1030                    causal: true,
1031                    window_size_left: None,
1032                    window_size_right: None,
1033                    softcap: None,
1034                    k_len: Some(DynScalar::Concrete(sk)),
1035                },
1036            ),
1037            vec![q, k, v],
1038            &[b, hq, 1, d],
1039            dt,
1040        );
1041        // Same-device stamps — the bake's same-device gate reads the arm exits.
1042        g.set_target_backend(kt, BackendId::Cuda);
1043        g.set_target_backend(scores, BackendId::Cuda);
1044        g.set_target_backend(attn, BackendId::Cuda);
1045        g.set_target_backend(flash, BackendId::Cuda);
1046        let reconverge = node(&mut g, Op::Relu, vec![attn], &[b, hq, 1, d], dt);
1047        let mut br = g.open_branch(q);
1048        br.add_arm(attn);
1049        br.add_arm(flash);
1050        let branch = br
1051            .finalize_branches(&mut g, reconverge)
1052            .expect("well-formed 2-arm decode branch")
1053            .expect("2 arms survive");
1054        let post = node(&mut g, Op::Tanh, vec![reconverge], &[b, hq, 1, d], dt);
1055        (g, branch, attn, flash, reconverge, post)
1056    }
1057
1058    /// The decode-shape Judge keys, single-sourced through the SAME helpers
1059    /// the bake's `for_op` derivation and the fuel-core Judge producer use:
1060    /// scores QKᵀ = `matmul(m=1, n=sk, k=d)`, attn PV = `matmul(m=1, n=d,
1061    /// k=sk)`, flash = `attention(hq, k_len=sk, d)`.
1062    fn decode_keys() -> (SizeClass, SizeClass, SizeClass) {
1063        let (hq, d, sk) = (8usize, 128, 512);
1064        (
1065            SizeClass::matmul(1, sk, d), // scores
1066            SizeClass::matmul(1, d, sk), // attn
1067            SizeClass::attention(hq, sk, d),
1068        )
1069    }
1070
1071    /// **BORN-RED (the arc headline).** A measured flash cell that is strictly
1072    /// cheaper than the region's summed measured primitives flips the bake from
1073    /// arm 0 to arm 1. RED before the Layer-2 wiring (the flash arm ties / is
1074    /// gated on Layer-1 ⇒ arm 0 kept); GREEN after (measured flash wins).
1075    #[test]
1076    fn judge_measured_flash_wins_the_decode_bake() {
1077        let (mut g, branch, attn, flash, reconverge, post) = flash_variant_diamond();
1078        let dt = DType::F16;
1079        let (k_scores, k_attn, k_flash) = decode_keys();
1080
1081        // (RED anchor) the default lowering realizes the decomposed region.
1082        let before = lower_runs_arm0(&g, &[post]);
1083        assert!(
1084            before.contains(&attn) && !before.contains(&flash),
1085            "before the bake the decomposed region wins (arm 0); order={before:?}",
1086        );
1087
1088        // Injected Judge: flash measures CHEAPER (400 ns) than the region's two
1089        // measured matmuls (500 + 500 = 1000 ns) — flash's algorithm-changing
1090        // win Layer-1 can't see (FLOP tie / CPU-build capability gate).
1091        let mut judge = HashMapJudge::new();
1092        judge.insert(OpKind::MatMul, dt, k_scores, BackendId::Cuda, "", 500, 0);
1093        judge.insert(OpKind::MatMul, dt, k_attn, BackendId::Cuda, "", 500, 0);
1094        judge.insert(OpKind::FlashAttn, dt, k_flash, BackendId::Cuda, "", 400, 0);
1095
1096        let cost = |g: &Graph, b: NodeId, arm: usize, i: &[NodeId]| -> Option<u64> {
1097            decode_arm_composite_ns_judged(g, b, arm, i, BackendId::Cuda, Some(&judge))
1098        };
1099        let baked = bake_variant_branches(&mut g, &[post], &cost);
1100
1101        assert_eq!(
1102            baked, 1,
1103            "measured flash is strictly cheaper ⇒ the branch bakes to it"
1104        );
1105        assert_eq!(
1106            g.node(branch).inputs,
1107            vec![flash],
1108            "branch collapsed to the flash arm"
1109        );
1110        assert!(
1111            g.node(reconverge).inputs.contains(&flash),
1112            "merge rewired to flash"
1113        );
1114
1115        let after = lower_runs_arm0(&g, &[post]);
1116        assert!(
1117            after.contains(&flash),
1118            "flash realized after the bake; order={after:?}"
1119        );
1120        assert!(
1121            !after.contains(&attn),
1122            "the decomposed region is pruned; order={after:?}"
1123        );
1124    }
1125
1126    /// GUARD: the Judge says flash is SLOWER than the region ⇒ arm 0 (the
1127    /// conservative oracle default holds — a measurement never optimistically
1128    /// commits a losing variant).
1129    #[test]
1130    fn judge_measured_flash_slower_keeps_the_region() {
1131        let (mut g, branch, attn, flash, _recon, post) = flash_variant_diamond();
1132        let dt = DType::F16;
1133        let (k_scores, k_attn, k_flash) = decode_keys();
1134        let mut judge = HashMapJudge::new();
1135        judge.insert(OpKind::MatMul, dt, k_scores, BackendId::Cuda, "", 500, 0);
1136        judge.insert(OpKind::MatMul, dt, k_attn, BackendId::Cuda, "", 500, 0);
1137        judge.insert(OpKind::FlashAttn, dt, k_flash, BackendId::Cuda, "", 2000, 0);
1138        let cost = |g: &Graph, b: NodeId, arm: usize, i: &[NodeId]| -> Option<u64> {
1139            decode_arm_composite_ns_judged(g, b, arm, i, BackendId::Cuda, Some(&judge))
1140        };
1141        let baked = bake_variant_branches(&mut g, &[post], &cost);
1142        assert_eq!(
1143            baked, 0,
1144            "measured flash is slower ⇒ arm 0 (the region) stands"
1145        );
1146        assert_eq!(
1147            g.node(branch).inputs,
1148            vec![attn],
1149            "branch collapsed to arm 0"
1150        );
1151        let after = lower_runs_arm0(&g, &[post]);
1152        assert!(
1153            after.contains(&attn) && !after.contains(&flash),
1154            "region realized (oracle)"
1155        );
1156    }
1157
1158    /// GUARD: with `judge == None` the judged provider is **byte-identical** to
1159    /// the Layer-1-only provider per arm (the no-Judge production path + the
1160    /// persistent byte-exact suites stay untouched by construction), and the
1161    /// bake keeps arm 0.
1162    #[test]
1163    fn no_oracle_is_byte_identical_to_layer1() {
1164        let (mut g, branch, attn, flash, _recon, post) = flash_variant_diamond();
1165        let interiors = arm_interiors(&g, branch);
1166        for (arm, interior) in interiors.iter().enumerate() {
1167            assert_eq!(
1168                decode_arm_composite_ns_judged(&g, branch, arm, interior, BackendId::Cuda, None),
1169                decode_arm_composite_ns(&g, branch, arm, interior, BackendId::Cuda),
1170                "judged(None) must equal the Layer-1 provider for arm {arm}",
1171            );
1172        }
1173        let cost = |g: &Graph, b: NodeId, arm: usize, i: &[NodeId]| -> Option<u64> {
1174            decode_arm_composite_ns_judged(g, b, arm, i, BackendId::Cuda, None)
1175        };
1176        let baked = bake_variant_branches(&mut g, &[post], &cost);
1177        assert_eq!(
1178            baked, 0,
1179            "no oracle ⇒ Layer-1 path ⇒ arm 0 (flash unbound on a CPU build)"
1180        );
1181        assert_eq!(g.node(branch).inputs, vec![attn]);
1182        let _ = flash;
1183    }
1184
1185    /// GUARD (capability-missing, via the hybrid fallback): the Judge measured
1186    /// the region's matmuls but NOT the flash cell, so the flash arm falls back
1187    /// to Layer-1 where the capability gate (no bound CUDA flash kernel on a CPU
1188    /// build) makes it inadmissible ⇒ arm 0. A measurement is required to make
1189    /// an unbound-on-this-build variant admissible.
1190    #[test]
1191    fn judge_without_flash_cell_falls_to_capability_gate() {
1192        let (mut g, branch, attn, flash, _recon, post) = flash_variant_diamond();
1193        let dt = DType::F16;
1194        let (k_scores, k_attn, _k_flash) = decode_keys();
1195        let mut judge = HashMapJudge::new();
1196        judge.insert(OpKind::MatMul, dt, k_scores, BackendId::Cuda, "", 1, 0);
1197        judge.insert(OpKind::MatMul, dt, k_attn, BackendId::Cuda, "", 1, 0);
1198        let cost = |g: &Graph, b: NodeId, arm: usize, i: &[NodeId]| -> Option<u64> {
1199            decode_arm_composite_ns_judged(g, b, arm, i, BackendId::Cuda, Some(&judge))
1200        };
1201        let baked = bake_variant_branches(&mut g, &[post], &cost);
1202        if !fused_kernel_available(FusedOps::FLASH_ATTN, BackendId::Cuda) {
1203            assert_eq!(baked, 0, "no flash measurement + unbound kernel ⇒ arm 0");
1204            assert_eq!(g.node(branch).inputs, vec![attn]);
1205        }
1206        let _ = flash;
1207    }
1208
1209    /// GUARD (the hybrid sum): when only SOME of an arm's nodes are
1210    /// Judge-covered, measured cells and Layer-1 estimates are summed together.
1211    /// Here only the `scores` matmul is measured (500 ns); `attn` falls back to
1212    /// Layer-1. The region cost is exactly `500 + Layer-1(attn)`, and a cheaper
1213    /// measured flash still wins.
1214    #[test]
1215    fn hybrid_sum_mixes_measured_and_layer1_for_the_region() {
1216        let (mut g, branch, attn, flash, _recon, post) = flash_variant_diamond();
1217        let dt = DType::F16;
1218        let (k_scores, _k_attn, k_flash) = decode_keys();
1219        let mut judge = HashMapJudge::new();
1220        judge.insert(OpKind::MatMul, dt, k_scores, BackendId::Cuda, "", 500, 0); // scores only
1221        judge.insert(OpKind::FlashAttn, dt, k_flash, BackendId::Cuda, "", 400, 0);
1222
1223        // The region arm's hybrid cost == measured scores (500) + Layer-1 attn.
1224        let region = arm_interiors(&g, branch)[0].clone();
1225        let hybrid =
1226            decode_arm_composite_ns_judged(&g, branch, 0, &region, BackendId::Cuda, Some(&judge))
1227                .expect("region prices");
1228        let layer1_attn = decode_arm_composite_ns(&g, branch, 0, &[attn], BackendId::Cuda)
1229            .expect("attn prices on Layer-1");
1230        assert_eq!(
1231            hybrid,
1232            500 + layer1_attn,
1233            "hybrid region = measured scores (500) + Layer-1 attn ({layer1_attn})",
1234        );
1235
1236        // Flash (measured 400) is cheaper than the hybrid region ⇒ it wins.
1237        let cost = |g: &Graph, b: NodeId, arm: usize, i: &[NodeId]| -> Option<u64> {
1238            decode_arm_composite_ns_judged(g, b, arm, i, BackendId::Cuda, Some(&judge))
1239        };
1240        let baked = bake_variant_branches(&mut g, &[post], &cost);
1241        assert_eq!(
1242            baked, 1,
1243            "measured flash beats the hybrid region ⇒ bakes to flash"
1244        );
1245        assert_eq!(g.node(branch).inputs, vec![flash]);
1246    }
1247
1248    /// GUARD: a **placement** branch (arm exits on DIFFERENT backends) is never
1249    /// touched by the bake — even with a flash-loving Judge — because the
1250    /// same-device gate in `bake_variant_branches` skips it BEFORE the cost
1251    /// provider (and thus the Judge) is ever consulted. It stays a live 2-arm
1252    /// decision point for the runtime route picker.
1253    #[test]
1254    fn judge_does_not_touch_a_placement_branch() {
1255        let (mut g, branch, attn, flash, _recon, post) = flash_variant_diamond();
1256        // Re-stamp the flash arm onto a DIFFERENT backend ⇒ placement branch.
1257        g.set_target_backend(flash, BackendId::Cpu);
1258        let dt = DType::F16;
1259        let (_ks, _ka, k_flash) = decode_keys();
1260        let mut judge = HashMapJudge::new();
1261        judge.insert(OpKind::FlashAttn, dt, k_flash, BackendId::Cpu, "", 1, 0);
1262        let cost = |g: &Graph, b: NodeId, arm: usize, i: &[NodeId]| -> Option<u64> {
1263            let backend = g.target_backend(g.node(b).inputs.first().copied()?)?;
1264            decode_arm_composite_ns_judged(g, b, arm, i, backend, Some(&judge))
1265        };
1266        let baked = bake_variant_branches(&mut g, &[post], &cost);
1267        assert_eq!(
1268            baked, 0,
1269            "a placement branch is never baked, even with a flash-loving judge"
1270        );
1271        assert_eq!(
1272            g.node(branch).inputs,
1273            vec![attn, flash],
1274            "placement branch stays a live 2-arm decision point (runtime picker owns it)",
1275        );
1276    }
1277}