fuel_dispatch/optimize.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! `optimize_graph` — the new "plan IS the graph" entry point.
3//!
4//! Phase A PR-A3a/A4 of the "plan IS the graph" rebuild
5//! ([`../../docs/session-prompts/plan-is-graph-rebuild.md`](
6//! ../../docs/session-prompts/plan-is-graph-rebuild.md), the PR-A3/A4
7//! lines + the "Representation — DECIDED 2026-06-15" blockquote, incl.
8//! the architect-approved arm-0 temporary lowering).
9//!
10//! ## What this is
11//!
12//! [`optimize_graph`] is the **new optimization entry point**: it
13//! transforms a [`Graph`] *in place* into the bounded multi-path form
14//! and returns a transient [`OptimizedGraph`] *view* whose dispatch
15//! order is the **arm-0 single-route lowering** of `fuel-graph`'s
16//! `extract_runs` (PR-A2/A4). The optimized form lives **in the
17//! graph** — a graph with zero [`Op::Branch`] nodes is exactly today's
18//! single-route graph.
19//!
20//! ## PR-A4 — the first pathfinder (deliberate-fork seed)
21//!
22//! [`PlacementForkPathfinder`](crate::driver::PlacementForkPathfinder) is the first real pathfinder: where
23//! the placement DP admitted a kernel-bearing node with **≥2 distinct
24//! `(backend, device)` placements** that has a producer (the diverge)
25//! and exactly one consumer (the reconverge), it records ONE
26//! `Op::Branch` — arm-0 = the DP winner (the route realize uses today),
27//! arm-1 = the runner-up clone (orphaned, read only by the Branch). It
28//! emits a branch only at a genuine placement choice, never at ordinary
29//! DAG fan-out, so the fewness gate holds. A CPU-only build (one
30//! placement per node) emits zero branches ⇒ today's single-route graph.
31//!
32//! [`OptimizedGraph::dispatch_order`] is the architect-approved
33//! **arm-0 single-route lowering**: it follows arm 0 through every
34//! branch and skips the other arms' runs, so a branched graph realizes
35//! to the same result as before (arm-0 = the winner). The Phase-C
36//! runtime picker is what later selects non-arm-0 arms.
37//!
38//! ## A3a origin scope (ADDITIVE — proved equivalence, deleted nothing)
39//!
40//! This entry point landed in the **split** A3a: introduced *alongside*
41//! the old path and proved equivalent before anything old was removed.
42//! PR-A3b-1 then made it the default realize path, and PR-A3b-2 deleted
43//! `PlanStore` and the legacy `compile_plan` route-picking dispatch
44//! entirely (`optimize_graph` is now the only path). As originally
45//! introduced in A3a:
46//!
47//! - There were **no pathfinders yet** — the first
48//! ([`PlacementForkPathfinder`](crate::driver::PlacementForkPathfinder)) landed in PR-A4. A graph with no
49//! competing routes is already its own single-route plan, so
50//! [`optimize_graph`] introduces **zero [`Op::Branch`] nodes** for it.
51//! - It **reuses** the existing placement / cost / `target_backend`
52//! annotation machinery wholesale by driving
53//! [`crate::plan::compile_plan`] over the same `execution_plan`
54//! order the bridge uses — the placement DP, cost composer, filter
55//! chain, and fail-fast missing-binding diagnostics are *not*
56//! reinvented. The point of A3a is to establish the new entry point
57//! + in-place form, not new optimization.
58//! - [`crate::plan::compile_plan`] + [`crate::plan::ExecutionPlan`]
59//! are reused (the latter as a transient by-product). PR-A3b-1 wired
60//! `optimize_graph` in as the default realize path; PR-A3b-2 made it
61//! the ONLY path — the legacy `compile_plan`/`PlanStore` route-picking
62//! dispatch and the identity-keyed plan store are deleted, and
63//! `optimize_graph` now surfaces its internal `ExecutionPlan` so the
64//! bridge's stamp/residency/layout passes reuse it (one `compile_plan`
65//! per realize).
66//!
67//! ## The equivalence gate
68//!
69//! For a graph with no competing routes, [`optimize_graph`] leaves
70//! zero `Op::Branch` nodes and the `extract_runs` / `lower_run`
71//! dispatch order equals today's
72//! [`crate::plan::compile_plan`]`(...).order` — the exact sequence the
73//! production executor walks. The order today is simply the
74//! `execution_plan` topo order `compile_plan` is handed (it copies it
75//! into `ExecutionPlan::order` verbatim); for a branchless,
76//! single-residency graph the run extractor produces exactly one run
77//! whose members are that same topo order. The gate asserts that
78//! equality exactly (same `NodeId`s, same order) — see
79//! `tests::equivalence_gate_branchless_order_matches_compile_plan`.
80
81use std::collections::{HashMap, HashSet};
82
83use fuel_graph::opt::insert_cross_device_copies;
84use fuel_graph::{Graph, NodeId, Op, extract_runs_multi, topo_order_multi};
85use fuel_ir::{DType, DeviceLocation, Result};
86
87use crate::driver::{OptimizationContext, PassRegistry};
88use crate::kernel::KernelBindingTable;
89use crate::plan::{ExecutionPlan, PlanOptions, compile_plan};
90use crate::topology::SystemTopology;
91
92/// Round cap for the residency-eviction pass `optimize_graph` runs under a device byte budget
93/// (the legacy rule's default; the pass stops earlier once the budget is met).
94const RESIDENCY_EVICTION_MAX_ROUNDS: usize = 16;
95
96/// The transient *view* [`optimize_graph`] returns — the realize-roots
97/// it optimized for plus the topology generation it ran under. It is
98/// **not** stored on the graph; the optimized form is the graph itself
99/// (with its `Op::Branch` decision points, of which A3a emits none).
100///
101/// The dispatch order is derived on demand from `fuel-graph`'s run
102/// extraction so the run view is always recomputed from the current
103/// arena — never a stale snapshot. This is the shape PR-A3b swaps the
104/// bridge onto in place of `ExecutionPlan::order`.
105#[derive(Debug, Clone)]
106pub struct OptimizedGraph {
107 /// The realize roots this optimization targeted (the same
108 /// `targets` the bridge passes today).
109 pub roots: Vec<NodeId>,
110 /// `SystemTopology` generation snapshotted at optimize time —
111 /// mirrors [`crate::plan::ExecutionPlan::generation`] so a later
112 /// chunk-boundary check can detect a topology shift exactly as
113 /// the executor does today.
114 pub generation: u64,
115 /// Final effective placement per node, as the optimizer resolved it.
116 /// Read via [`OptimizedGraph::placement_of`].
117 ///
118 /// `None` when the residency pass did not run — it is gated on
119 /// `PlanOptions::pinned_device`, which the production realize path always
120 /// sets and bare-graph test callers often do not. `None` therefore means
121 /// **"not computed"**, never "placed nowhere".
122 pub(crate) placements: Option<HashMap<NodeId, DeviceLocation>>,
123 /// What the budgeted eviction pass did (ROADMAP row 67 I1): `Some` only when
124 /// `PlanOptions::device_budget_bytes` was set and a device was pinned. Read
125 /// [`crate::residency::EvictionOutcome::fits`] before trusting that the budget was met: today a same-device
126 /// budget cannot be met (the reload is not delayed), and this says so.
127 pub eviction: Option<crate::residency::EvictionOutcome>,
128}
129
130impl OptimizedGraph {
131 /// Extract the runs of the optimized graph, in topological order
132 /// of their entries (delegates to [`extract_runs_multi`]). A
133 /// branchless, single-residency graph yields exactly one run.
134 pub fn runs(&self, graph: &Graph) -> Vec<fuel_graph::Run> {
135 extract_runs_multi(graph, &self.roots)
136 }
137
138 /// **The device the optimizer decided this node runs on** — the observable
139 /// form of the placement decision, for callers that need to check *where*
140 /// work landed rather than infer it from timing.
141 ///
142 /// This is the resolved *effective* placement, not a hint. It is the same
143 /// map the residency pass uses to decide where to stitch cross-device
144 /// copies, resolved by the priority in `effective_placements`:
145 /// residency-declaring ops → explicit `Graph::placement` → input residency
146 /// → **plan winner** → backend stamp → view pass-through.
147 ///
148 /// **Do not substitute [`fuel_graph::Graph::placement`] for this.** That is
149 /// only *level 2* of the six — a hint set by inserted copies and caller
150 /// overrides. The planner's actual choice for a compute node arrives at
151 /// level 4 ("plan winner"), so `Graph::placement` returns `None` for
152 /// precisely the nodes whose placement is interesting, and reading that
153 /// `None` as "unplaced" is a wrong answer that looks like a null one.
154 ///
155 /// Returns `None` if the node is unknown to this optimization **or** if the
156 /// residency pass did not run (no `pinned_device`; see the field docs) —
157 /// the two are deliberately not distinguished here because neither means
158 /// "placed nowhere". Use [`OptimizedGraph::has_placements`] to tell them
159 /// apart before drawing a conclusion from a `None`.
160 pub fn placement_of(&self, node: NodeId) -> Option<DeviceLocation> {
161 self.placements.as_ref()?.get(&node).copied()
162 }
163
164 /// Whether placement was computed at all. Distinguishes "this node has no
165 /// placement" from "no node does, because the pass was skipped" — the
166 /// difference between a real observation and an absent instrument.
167 pub fn has_placements(&self) -> bool {
168 self.placements.is_some()
169 }
170
171 /// Every resolved `(node, device)` pair, for dumping a whole graph's
172 /// placement. Empty iterator when placement was not computed — check
173 /// [`OptimizedGraph::has_placements`] first if that distinction matters.
174 pub fn placements(&self) -> impl Iterator<Item = (NodeId, DeviceLocation)> + '_ {
175 self.placements
176 .iter()
177 .flat_map(|m| m.iter().map(|(&id, &loc)| (id, loc)))
178 }
179
180 /// The flat executable dispatch order — the **arm-0 single-route
181 /// lowering** (PR-A4). It follows arm 0 through every `Op::Branch`
182 /// (pre-run, arm-0's run, post-run) and **skips every non-arm-0
183 /// arm's run**, via [`fuel_graph::lower_runs_arm0`].
184 ///
185 /// For a graph with **zero `Op::Branch` nodes** this is the exact
186 /// `NodeId` sequence today's executor walks via
187 /// [`crate::plan::compile_plan`]`(...).order` — the equivalence gate
188 /// proves it (no arm to skip ⇒ identical to concatenating
189 /// [`fuel_graph::run::lower_run`] over the runs). For a branched graph it is the
190 /// single-route lowering on **arm 0 = the DP winner** (the route
191 /// realize used before the branch was recorded), so a branched graph
192 /// realizes to the same result. The Phase-C runtime picker is what
193 /// will later select non-arm-0 arms at the decision points.
194 pub fn dispatch_order(&self, graph: &Graph) -> Vec<NodeId> {
195 fuel_graph::lower_runs_arm0(graph, &self.roots)
196 }
197
198 /// The number of `Op::Branch` decision points in the arena. Counting
199 /// over the whole arena (not just the roots' reachable set) is the
200 /// stronger claim. Zero for a single-route graph (CPU-only build, or
201 /// any graph with no genuine ≥2-placement fork); PR-A4's
202 /// deliberate-fork pathfinder emits one per genuine placement fork.
203 pub fn branch_count(&self, graph: &Graph) -> usize {
204 (0..graph.len())
205 .map(NodeId)
206 .filter(|&id| matches!(graph.node(id).op, Op::Branch { .. }))
207 .count()
208 }
209}
210
211/// Optimize `graph` **in place** into the "plan IS the graph" form and
212/// return the transient [`OptimizedGraph`] lowering view.
213///
214/// `roots` are the realize targets (the bridge's `targets`);
215/// `bindings_table` is the kernel registry the placement/cost
216/// machinery queries (production passes [`crate::dispatch::global_bindings`];
217/// tests pass a local table); `opts` is the same [`PlanOptions`] the
218/// bridge builds for `compile_plan`.
219///
220/// ## Behavior
221///
222/// `optimize_graph`:
223///
224/// 1. Derives the dispatch order via `fuel_graph::opt::execution_plan`
225/// — exactly the order the bridge feeds `compile_plan` today
226/// (data-flow topo refined by destructive-op ordering edges).
227/// 2. Drives [`compile_plan`] over that order to **reuse** the
228/// existing placement DP / cost composer / filter chain and to
229/// fail-fast at build time on a missing binding or absent device
230/// context (validate-at-graph-build-time per the working
231/// agreement). Its [`crate::plan::ExecutionPlan`] is a transient
232/// by-product here — the source of truth is the graph.
233/// 3. Runs the PR-A4 deliberate-fork pathfinder
234/// ([`PlacementForkPathfinder`](crate::driver::PlacementForkPathfinder)): records ONE `Op::Branch` per
235/// genuine ≥2-placement fork (arm-0 = winner, arm-1 = runner-up). A
236/// graph with no competing routes gets **zero** branches — it is
237/// already its own single-route plan.
238///
239/// The returned view's [`OptimizedGraph::dispatch_order`] is the arm-0
240/// single-route lowering; for any branchless graph it reproduces
241/// `compile_plan(...).order` exactly — the equivalence gate.
242///
243/// ## The internal `ExecutionPlan` (Step D — no longer returned)
244///
245/// `optimize_graph` drives [`compile_plan`] internally for
246/// placement/cost/validation; the resulting `ExecutionPlan` is a
247/// **transient, optimizer-internal** accumulator the stamp / residency /
248/// layout-fixup passes + the lock-step rankers read below. It is NOT
249/// returned or threaded anywhere — the durable output is the graph's
250/// `target_backend` stamps + `Op::Branch` arms. The executor reads the
251/// graph + re-derives any per-arm candidate from the binding registry at
252/// realize time, so the plan never becomes a dispatch-time authority.
253pub fn optimize_graph(
254 graph: &mut Graph,
255 roots: &[NodeId],
256 bindings_table: &KernelBindingTable,
257 opts: &PlanOptions<'_>,
258) -> Result<OptimizedGraph> {
259 optimize_graph_with_passes(
260 graph,
261 roots,
262 bindings_table,
263 opts,
264 PassRegistry::default_passes(),
265 )
266}
267
268/// [`optimize_graph`] with the runtime-fusion pathfinder registered
269/// ([`PassRegistry::default_passes_with_runtime_fusion`]): adopted (Tier-2 /
270/// JIT-synthesized) fused ops get their gated `Op::Branch` arms emitted before
271/// placement runs. This is the **production realize path's** entry once a
272/// process can adopt runtime kernels; `optimize_graph` stays runtime-op-free so
273/// bare-graph callers and tests never scan the process-global sidecar.
274pub fn optimize_graph_with_runtime_fusion(
275 graph: &mut Graph,
276 roots: &[NodeId],
277 bindings_table: &KernelBindingTable,
278 opts: &PlanOptions<'_>,
279) -> Result<OptimizedGraph> {
280 optimize_graph_with_passes(
281 graph,
282 roots,
283 bindings_table,
284 opts,
285 PassRegistry::default_passes_with_runtime_fusion(),
286 )
287}
288
289fn optimize_graph_with_passes(
290 graph: &mut Graph,
291 roots: &[NodeId],
292 bindings_table: &KernelBindingTable,
293 opts: &PlanOptions<'_>,
294 passes: PassRegistry,
295) -> Result<OptimizedGraph> {
296 // (1) The dispatch order today: data-flow topo refined by ordering
297 // edges. `compile_plan` copies this verbatim into
298 // `ExecutionPlan::order`, so it IS the executor's walk order.
299 let order = fuel_graph::opt::execution_plan(graph, roots);
300
301 // (2) Reuse the placement/cost/validation machinery. The plan is a
302 // transient, optimizer-INTERNAL by-product — we drive `compile_plan`
303 // so the same fail-fast diagnostics (missing binding, no device
304 // context) fire at optimize time, and so the placement DP / cost
305 // composer run unchanged. The plan is the working accumulator the
306 // stamp / residency / layout-fixup passes + the lock-step rankers
307 // read below; it is NOT returned or threaded (Step D — the graph
308 // stamps + arms are the only durable output).
309 // (2a) Dtype-reconciliation fixup — insert promoting `Op::Cast`s so a node
310 // whose per-operand key no compiled-in backend serves natively (e.g. a
311 // mixed-precision `[F32, BF16, F32]` matmul) becomes servable, instead of
312 // dead-ending in `compile_plan` below. Runs BEFORE the plan because it
313 // changes what's enumerable; if it rewrites, re-derive the execution
314 // order over the mutated graph. The layout/residency fixups are its
315 // post-plan siblings.
316 let order = if insert_dtype_fixups(graph, roots, bindings_table, opts) {
317 fuel_graph::opt::execution_plan(graph, roots)
318 } else {
319 order
320 };
321
322 let plan = compile_plan(graph, &order, bindings_table, opts)?;
323 let generation = plan.generation;
324
325 // (3) PR-B3: the lock-step pass driver. The pre-B3 hardcoded
326 // `seed_placement_fork_branches(...)` call is replaced by a
327 // registry of pathfinders + optimizers run lock-step
328 // (prune-as-you-go): for each registered pathfinder, ADD its
329 // candidate paths, then immediately run every registered
330 // optimizer to MERGE/DISCARD over the region just touched. The
331 // shipped configuration ([`PassRegistry::default_passes`]) is the
332 // PR-A4 `PlacementForkPathfinder` (the deliberate-fork seed) +
333 // the `FrontierConvergenceOptimizer` (duplicate-path convergence
334 // + the never-strand / no-active-cycle invariant guards) — which
335 // is exactly the pre-B3 sequence, re-expressed. A CPU-only build
336 // has one placement per node ⇒ the pathfinder proposes zero
337 // branches ⇒ today's single-route graph (unchanged).
338 //
339 // The *ranker* + the PR-B2 per-device Pareto frontier are applied
340 // per kernel-bearing node *inside* `compile_plan` (the MEASURE +
341 // per-node PRUNE), and the ranked, frontier-pruned result is the
342 // `plan` the driver reads via `OptimizationContext::plan`. Batch
343 // optimize has no executing region, so the cycle guard is empty.
344 let cycle_guard: HashSet<NodeId> = HashSet::new();
345 let ctx = OptimizationContext {
346 order: &order,
347 plan: &plan,
348 cycle_guard: &cycle_guard,
349 bindings: bindings_table,
350 };
351 passes.run_lockstep(graph, &ctx)?;
352
353 // "Plan IS the graph": commit the placement decision INTO the graph's
354 // `target_backend` side-table here, so a fully-optimized graph carries
355 // its own backend stamps and downstream consumers read the graph, not a
356 // threaded plan. Guarded on a pinned device — the production realize
357 // path always sets one (`PlanOptions::with_pinned_device`); bare-graph
358 // test callers that don't are unaffected. (Cleanup Step A: this is
359 // idempotent with the bridge's transitional `stamp_plan_backends`, which
360 // re-stamps the identical result; Step A2 removes the bridge copy.)
361 // Stays `None` when the residency pass below is skipped (no pinned device),
362 // so a caller can tell "not computed" from "no placement" — see
363 // `OptimizedGraph::has_placements`.
364 let mut resolved_placements: Option<HashMap<NodeId, DeviceLocation>> = None;
365 let mut eviction: Option<crate::residency::EvictionOutcome> = None;
366 if let Some(pinned) = opts.pinned_device {
367 stamp_plan_backends(graph, roots, &plan, pinned);
368 // Optimize-time kernel-variant bake: resolve **same-device**
369 // kernel-variant branches (a decomposed region vs. a fused kernel on
370 // the SAME device — e.g. the CUDA flash decode arm) to their cost
371 // winner and COLLAPSE them, so the winning variant is selectable
372 // without a runtime pick (04-optimization: kernel-variant choice is
373 // "largely baked at optimize time"). Runs AFTER `stamp_plan_backends`
374 // (the arms now carry `target_backend`, which the same-device gate
375 // reads) and BEFORE `insert_residency_copies` (so the residency pass
376 // stitches inbound copies only for the surviving winner arm, not a
377 // pruned one). A **placement** branch (arms on ≥2 devices) is left
378 // LIVE for the runtime route picker; a graph with no same-device
379 // variant branch — every CPU/Vulkan build today, since no CUDA flash
380 // arm is offered there — is a strict no-op. Ties / unknown costs /
381 // capability-missing default to arm 0 (the decomposed oracle).
382 // The cost provider consults the Judge's MEASURED latency (Layer-2)
383 // FIRST per arm node, falling back to the Layer-1 composite where the
384 // Judge has no cell (the hybrid sum). With `opts.judge == None` this is
385 // byte-identical to the Layer-1-only provider, so the no-Judge path is
386 // unchanged. The same oracle `cost.rs`/`plan.rs` read is threaded here.
387 let judge = opts.judge;
388 crate::variant_bake::bake_variant_branches(graph, roots, &|g, branch, arm, interior| {
389 let backend = g.target_backend(g.node(branch).inputs.first().copied()?)?;
390 crate::variant_bake::decode_arm_composite_ns_judged(
391 g, branch, arm, interior, backend, judge,
392 )
393 });
394 // Cleanup Step B (residency): the optimizer-side cross-device copy pass
395 // (was the bridge's `insert_resident_input_copies`). Runs AFTER stamping
396 // (it reads `target_backend`) and BEFORE layout-fixup, preserving the
397 // prior residency→layout order. Cache residency (where persistent /
398 // const inputs already live) arrives via the `opts.input_residency`
399 // provider the realize path already threads in — the optimizer reads
400 // that fact, it does not touch realize-time storage.
401 // Capture the resolved placement map on the way past — it is the pass's
402 // own input, and surfacing it is what makes `OptimizedGraph::placement_of`
403 // an observation rather than an inference.
404 let placements = insert_residency_copies(graph, roots, &plan, pinned, opts.input_residency);
405 // ROADMAP row 67 (I1): with a device byte budget, evict + reload around the
406 // best candidates while the analysed peak exceeds it. Runs after the copy pass
407 // (it reads the resolved placements) and before layout fixups. No budget = no-op.
408 if let Some(budget) = opts.device_budget_bytes {
409 let mut outcome = crate::residency::insert_residency_evictions_in(
410 graph,
411 roots,
412 pinned,
413 budget,
414 RESIDENCY_EVICTION_MAX_ROUNDS,
415 |id| placements.get(&id).copied(),
416 )?;
417 outcome.budget_source = opts.device_budget_source;
418 eviction = Some(outcome);
419 }
420 resolved_placements = Some(placements);
421 // Cleanup Step B (layout): insert `Op::Contiguize` before any kernel
422 // whose chosen winner rejects strided inputs and whose input layout is
423 // non-contiguous — the optimizer writing the layout-fixup decision INTO
424 // the graph (was the bridge's `apply_layout_fixups`, now retired). No
425 // runtime deps: reads only the in-scope `plan` winner caps + graph
426 // layout. CSE-deduped + idempotent. Gated on `pinned_device` so it runs
427 // on the realize path (which always sets one), matching the prior
428 // bridge behavior; bare-graph test callers without a pin are unaffected.
429 fuel_graph::opt::insert_layout_fixups(graph, roots, |id| {
430 plan.alternatives(id)
431 .and_then(|set| set.winner())
432 .map(|cand| cand.caps.strided_input)
433 .unwrap_or(true)
434 });
435 }
436
437 Ok(OptimizedGraph {
438 roots: roots.to_vec(),
439 generation,
440 placements: resolved_placements,
441 eviction,
442 })
443}
444
445/// Dtype-reconciliation fixup (runs BEFORE `compile_plan`): for any kernel-
446/// bearing node whose per-operand `(op, dtypes)` key is not servable by any
447/// compiled-in backend, insert `Op::Cast`(s) promoting the mismatched input(s)
448/// to the node's OUTPUT dtype — IF that lossless upcast yields a key some backend
449/// DOES support. This is "backends advertise; the optimizer adapts"
450/// ([04-optimization], [05-backend-contract]) applied to dtype, and the sibling
451/// of `insert_layout_fixups` (`Op::Contiguize`) and `insert_residency_copies`
452/// (`Op::Copy`).
453///
454/// It is the non-native-kernel fallback the mixed-precision matmul path already
455/// ASSUMED exists — `vulkan_dispatch`'s matmul route picker documents "otherwise
456/// falls back to f32 matmul (after a Cast)" — but which was never built as a
457/// pass, so a graph builder emitting a mixed `[F32, BF16] → F32` matmul
458/// dead-ended at `NoBackendForOp` on every backend without the native mixed key
459/// (all but Vulkan; and CPU-only default builds have none).
460///
461/// SAFE + CONSERVATIVE: promotes ONLY by a value-LOSSLESS upcast to the output
462/// dtype ([`lossless_upcast`]), so it never changes op semantics (a comparison's
463/// `U8` output is not a lossless upcast target, so comparisons are left alone) and
464/// never corrupts a value.
465///
466/// **NUMERIC CAVEAT:** the upcast is value-lossless but the promoted op is NOT
467/// numerically identical to a native mixed-precision kernel — it accumulates in
468/// the higher precision, so the *same graph* can differ by which arm ran (a CPU
469/// upcast vs a native `[F32,BF16,F32]` kernel; and it already differs
470/// CPU-vs-CUDA). The pass REPORTS every promotion via `tracing` (visibility, per
471/// C-6's "never silently deoptimize"). Making a promoting cast **forbiddable
472/// under a C-5 determinism/tolerance constraint** (so a byte-exact-oracle or
473/// CPU-vs-CUDA-parity consumer gets the native path or a hard fail, not a silent
474/// upcast) and **accounting its extra resident bytes under C-4** (BF16→F32
475/// doubles a weight) are tracked ROADMAP follow-ups.
476///
477/// When no lossless promotion yields a supported key, the node is left unchanged
478/// and fails cleanly at `compile_plan` with the truthful coverage diagnostic — a
479/// genuine gap, surfaced honestly. Returns whether it changed the graph (so the
480/// caller re-derives the execution order).
481///
482/// The broader fix — expanding per-op dtype coverage across kernels (starting
483/// CPU) so fewer combos need reconciling — is a tracked ROADMAP item; this pass
484/// makes the graph builder's mixed-precision promise executable everywhere today.
485fn insert_dtype_fixups(
486 graph: &mut Graph,
487 roots: &[NodeId],
488 bindings: &KernelBindingTable,
489 options: &PlanOptions<'_>,
490) -> bool {
491 let order = topo_order_multi(graph, roots);
492 // Decision only (immutable graph reads): the `(consumer, input, target)` edges
493 // to promote. The mechanical Cast-insert + rewire is
494 // `fuel_graph::opt::insert_cast_fixups` (the dtype-changing sibling of the
495 // layout fixup). Built in topo order ⇒ deterministic cast-node assignment.
496 let mut casts: Vec<(NodeId, NodeId, DType)> = Vec::new();
497
498 for &id in &order {
499 let (op, inputs, out_dtype) = {
500 let node = graph.node(id);
501 (node.op.clone(), node.inputs.clone(), node.dtype)
502 };
503 let op_kind = match crate::pipelined::op_to_op_kind(&op) {
504 Some(k) => k,
505 None => continue, // view / Const / not-dispatched → no binding key
506 };
507 // The exact per-operand key the dispatcher will look up.
508 let native_key = crate::pipelined::build_lookup_dtypes(graph, graph.node(id));
509 // Only reconcile the generic `[in0, in1, …, out]` key shape. Ops whose
510 // key is canonicalized (Concat, WriteSlice*) share a uniform input dtype
511 // by construction, so they never present a mixed-input miss here.
512 if native_key.len() != inputs.len() + 1 {
513 continue;
514 }
515 // The backends THIS node may actually be placed on. Asked via the
516 // planner's own resolver so the two cannot drift: a weaker predicate
517 // here (e.g. "does any registered backend serve it?") lets a backend
518 // the node can never run on suppress the reconciliation the node needs,
519 // and `compile_plan` below then dead-ends at `NoBackendForOp`.
520 let candidates = crate::plan::candidate_backends_for(graph, options, id, graph.node(id));
521 let servable = |key: &[DType]| {
522 candidates
523 .iter()
524 .any(|&backend| bindings.backend_supports(op_kind, key, backend))
525 };
526
527 if servable(&native_key) {
528 continue; // a backend this node can run on serves it natively
529 }
530 // Promotion target = the output dtype ("compute dtype"), taken ONLY when
531 // every input can losslessly upcast to it — else decline.
532 let target = out_dtype;
533 if !inputs
534 .iter()
535 .all(|&i| lossless_upcast(graph.node(i).dtype, target))
536 {
537 continue;
538 }
539 // Uniform promoted key `[target, …, target, out]` (target == out).
540 let promoted_key: Vec<DType> = inputs
541 .iter()
542 .map(|_| target)
543 .chain(std::iter::once(out_dtype))
544 .collect();
545 if promoted_key == native_key {
546 continue; // inputs already == target; nothing to promote
547 }
548 if !servable(&promoted_key) {
549 continue; // the lossless promotion still isn't servable — genuine gap
550 }
551 for &input_id in &inputs {
552 if graph.node(input_id).dtype != target {
553 casts.push((id, input_id, target));
554 }
555 }
556 }
557
558 if casts.is_empty() {
559 return false;
560 }
561 // Visibility (C-6 "fuel never silently deoptimizes without saying so", applied
562 // to precision rather than fusion): a promoting cast is NOT numerically
563 // identical to a native mixed-precision kernel — it accumulates the upcast in
564 // higher precision, so the same graph can diverge by which arm ran (CPU upcast
565 // vs CUDA native mixed) — and it increases the promoted operand's resident
566 // bytes (e.g. BF16→F32 doubles a weight). A byte-exact-oracle or determinism
567 // consumer must be able to SEE it. Reported via `tracing`; forbidding it under
568 // a C-5 constraint + full C-4 cost accounting are tracked ROADMAP follow-ups.
569 tracing::warn!(
570 promoting_casts = casts.len(),
571 "dtype-reconciliation inserted {} promoting Cast(s): a node's per-operand \
572 dtype key had no native kernel on any backend, so input(s) were upcast to \
573 the output dtype. This CHANGES numerics vs a native mixed-precision kernel \
574 and increases resident bytes for the promoted operand(s).",
575 casts.len(),
576 );
577 fuel_graph::opt::insert_cast_fixups(graph, &casts);
578 true
579}
580
581/// Lossless dtype upcast predicate for [`insert_dtype_fixups`] — `true` ONLY for
582/// conversions that preserve every value exactly (identity + float widenings
583/// where the target's exponent AND mantissa cover the source's). Deliberately
584/// conservative: an unlisted pair returns `false`, so the pass declines rather
585/// than risk a lossy or semantics-changing promotion.
586fn lossless_upcast(from: DType, to: DType) -> bool {
587 use DType::*;
588 if from == to {
589 return true;
590 }
591 matches!(
592 (from, to),
593 (BF16, F32) | (BF16, F64) | (F16, F32) | (F16, F64) | (F32, F64)
594 )
595}
596
597/// Commit the plan's per-node winner backend to the graph's
598/// `target_backend` side-table — the optimizer writing its placement
599/// decision into the graph.
600///
601/// Per kernel-bearing node: stamp `winner.backend` if the plan has an
602/// `AlternativeSet` for it, else the pinned device's backend (structural
603/// ops the planner skips — `Op::Copy`/`Op::Move`/`Op::Alloc`/`Op::ZeroFill`
604/// — plus any op without an `OpKind` mapping). `Op::Const`/`Op::Release`/
605/// `Op::Contiguize`/view ops/`Op::Reshape` inherit or don't need a stamp
606/// and are skipped. Always overwrites, so re-optimizing after a
607/// `TopologyChanged` retry re-stamps consistently from the fresh plan.
608fn stamp_plan_backends(
609 graph: &mut Graph,
610 roots: &[NodeId],
611 plan: &ExecutionPlan,
612 pinned_loc: DeviceLocation,
613) {
614 let pinned_backend = pinned_loc.backend();
615 let order = topo_order_multi(graph, roots);
616 for &id in &order {
617 let node = graph.node(id);
618 if matches!(node.op, Op::Const | Op::Release | Op::Contiguize)
619 || node.op.is_view_op()
620 || matches!(node.op, Op::Reshape(_))
621 {
622 continue;
623 }
624 let stamp = plan
625 .alternatives(id)
626 .and_then(|set| set.winner())
627 .map(|c| c.backend)
628 .unwrap_or(pinned_backend);
629 graph.set_target_backend(id, stamp);
630 }
631}
632
633/// Cleanup Step B (residency): the optimizer-side cross-device copy pass —
634/// insert `Op::Copy { target }` on every edge whose producer's resident
635/// location doesn't share a storage substrate with the consumer's placement,
636/// then stamp each inserted copy's `target_backend` with the SOURCE backend
637/// (the pipelined executor's `Op::Copy` convention: the transfer kernel runs
638/// on the backend the bytes come FROM). Was the bridge's
639/// `insert_resident_input_copies`; moved here so the optimizer — not the
640/// realize-time bridge — owns the residency decision and writes it into the
641/// graph.
642///
643/// Placements come from graph-knowable facts only (no realize-time storage):
644/// residency-declaring ops, explicit `Graph::placement` (the bridge converts
645/// cache residency into placement stamps before optimize — cleanup Step B),
646/// the plan winner's device, the `target_backend` stamp (→ pinned), and view
647/// pass-through. Substrate sharing is queried via the process-global
648/// `SystemTopology` (available pre-realize once backends are registered).
649///
650/// Runs after `stamp_plan_backends` (it reads `target_backend`); the re-stamp
651/// sweep below restores the source-backend stamp on copies/moves that the
652/// stamping pass overwrote with the pinned backend.
653/// Returns the effective-placement map it resolved, so the optimizer can hand
654/// it out via [`OptimizedGraph::placement_of`]. The map is the pass's own input
655/// — surfacing it costs nothing and makes the placement decision observable
656/// instead of inferable.
657///
658/// Note the snapshot is taken BEFORE copy insertion (see the `placements`
659/// comment below), which is the right vantage for "where did this node land":
660/// it reports the placement of the original nodes, with the inserted copies
661/// being the consequence rather than part of the answer.
662fn insert_residency_copies(
663 graph: &mut Graph,
664 roots: &[NodeId],
665 plan: &ExecutionPlan,
666 pinned_loc: DeviceLocation,
667 input_residency: Option<&dyn Fn(NodeId) -> Option<DeviceLocation>>,
668) -> HashMap<NodeId, DeviceLocation> {
669 // Step E Phase C, PR C-0: walk the ARM-INCLUSIVE reachable set, not bare
670 // `roots`. A finalized `Op::Branch` is orphaned (its `reconverge_at` reads
671 // arm-0 directly, per the PR-A1 runnability invariant), so a plain
672 // `topo_order_multi(roots)` never reaches it — and therefore never reaches
673 // its non-arm-0 arms. The residency pass MUST stitch inbound cross-device
674 // copies for EVERY surviving arm so the executor can legally re-pick
675 // arm-1+ at runtime by live load (C2): whichever arm it picks, that arm's
676 // device-inputs are already resident. `effective_roots` (the same seeding
677 // the run extractor + route picker use) pulls every Branch's arms into the
678 // walk. On a branchless graph it returns exactly `roots` ⇒ byte-identical.
679 let eff_roots = fuel_graph::effective_roots(graph, roots);
680 let placements = effective_placements(graph, &eff_roots, plan, pinned_loc, input_residency);
681 let topology = SystemTopology::current();
682 // Identical locations short-circuit to `true` BEFORE the topology lookup
683 // (a location trivially shares bytes with itself; `shares_storage` returns
684 // `false` for unknown backends, so without this an unprobed topology would
685 // wrap every same-device edge in a copy).
686 let shares = |a: DeviceLocation, b: DeviceLocation| -> bool {
687 if a == b {
688 return true;
689 }
690 topology.shares_storage((a.backend(), a), (b.backend(), b))
691 };
692 // Hop-count oracle: an edge whose transfer path is `HostStaging` can't
693 // be done as a single `Op::Copy` (no direct device-to-device copy
694 // kernel between distinct GPU substrates — the cross-VENDOR CUDA↔Vulkan
695 // case), so the residency pass routes it through a CPU intermediate as
696 // TWO hops. `SystemTopology::transfer_path` already returns `HostStaging`
697 // for such pairs and `SameDevice` for `a == b`; CPU↔CUDA / CPU↔Vulkan
698 // resolve to a direct path (or the universal host-staging fallback only
699 // when CPU is NOT one of the endpoints), so any CPU-touching edge stays
700 // single-hop. We additionally guard on neither endpoint being CPU: a CPU
701 // intermediate for a CPU-touching edge would be nonsensical (and the
702 // single-hop CPU↔GPU Copy kernels exist and are byte-identical to
703 // today). Same-vendor GPU pairs that don't share storage (e.g. CUDA gpu0
704 // ↔ gpu1) fall back to `HostStaging` too — correctly two-hop, since
705 // there's no direct cross-gpu_id copy kernel today either.
706 let needs_host_staging = |a: DeviceLocation, b: DeviceLocation| -> bool {
707 if a == DeviceLocation::Cpu || b == DeviceLocation::Cpu {
708 return false;
709 }
710 matches!(
711 topology.transfer_path(a, b),
712 fuel_ir::backend::TransferPath::HostStaging
713 )
714 };
715 let inserted = insert_cross_device_copies(
716 graph,
717 &eff_roots,
718 |id| placements.get(&id).copied(),
719 shares,
720 needs_host_staging,
721 );
722 // Source-location resolver for stamping inserted copies. The
723 // `placements` snapshot was computed BEFORE insertion, so it does NOT
724 // contain the freshly-inserted CPU intermediate of a two-hop edge. That
725 // intermediate's placement was written into the graph by the pass
726 // (`set_placement(cpu_id, Cpu)`), so fall back to `graph.placement(src)`
727 // when the snapshot lacks the node — this is what stamps a two-hop's
728 // consumer-side hop with `Cpu` (its bytes come FROM the CPU intermediate,
729 // so its Copy kernel is the CPU `copy_from_cpu_wrapper`).
730 let src_location = |graph: &Graph, src: NodeId| -> Option<DeviceLocation> {
731 placements
732 .get(&src)
733 .copied()
734 .or_else(|| graph.placement(src))
735 };
736 // Stamp the new copies: target_backend = SOURCE backend. The pass only
737 // inserts a copy when the producer's placement resolved to Some.
738 for ©_id in &inserted {
739 if let Some(&src) = graph.node(copy_id).inputs.first()
740 && let Some(src_loc) = src_location(graph, src)
741 {
742 graph.set_target_backend(copy_id, src_loc.backend());
743 }
744 }
745 // Re-stamp ALL copies/moves with their SOURCE backend — graph rewrites are
746 // sticky and `stamp_plan_backends` just overwrote pre-existing ones (e.g.
747 // realize-root splices) with the pinned backend; the transfer kernel runs
748 // where the bytes come from. The freshly-inserted copies are visited too,
749 // but their input's placement resolves to the same source location, so the
750 // sweep re-applies the identical stamp (idempotent). Copies whose source
751 // placement is absent keep whatever stamp they already have. The two-hop
752 // CPU intermediate's source is the original GPU producer (stamped to that
753 // GPU); the consumer-side hop's source is the CPU intermediate (stamped
754 // Cpu via the `graph.placement` fallback in `src_location`).
755 // Arm-inclusive (C-0): re-walk from the arm-seeded roots so copies just
756 // inserted inside non-arm-0 arms are re-stamped too. The `eff_roots` seed
757 // set (Branch nodes are unchanged by insertion) reaches the fresh arm
758 // copies via the now-rewired arm-input edges.
759 let order = topo_order_multi(graph, &eff_roots);
760 for &id in &order {
761 if !matches!(graph.node(id).op, Op::Copy { .. } | Op::Move { .. }) {
762 continue;
763 }
764 let Some(&src) = graph.node(id).inputs.first() else {
765 continue;
766 };
767 let Some(src_loc) = src_location(graph, src) else {
768 continue;
769 };
770 graph.set_target_backend(id, src_loc.backend());
771 }
772
773 placements
774}
775
776/// Compute every reachable node's *effective placement* for the residency
777/// pass, mirroring the bridge's old `effective_placements`. Priority per node:
778///
779/// 1. **Residency-declaring ops** — `Op::Copy`/`Op::Move`/`Op::Alloc` carry
780/// their output location in the variant (definitional).
781/// 2. **Explicit `Graph::placement`** — set by inserted copies (and any
782/// caller-provided placement hints).
783/// 3. **Input residency** — where a persistent / const input already lives,
784/// supplied by the realize path via `PlanOptions::input_residency`. This is
785/// the only runtime fact, read through the provider closure — the optimizer
786/// never touches the storage itself.
787/// 4. **Plan winner** — a planned node runs on its winner's device.
788/// 5. **Backend stamp** — a node with `target_backend` but no plan entry
789/// (structural ops) follows the pinned device.
790/// 6. **View pass-throughs** — view ops / `Reshape` / `Contiguize` follow
791/// their data input (already resolved; `order` is topological).
792fn effective_placements(
793 g: &Graph,
794 roots: &[NodeId],
795 plan: &ExecutionPlan,
796 pinned_loc: DeviceLocation,
797 input_residency: Option<&dyn Fn(NodeId) -> Option<DeviceLocation>>,
798) -> HashMap<NodeId, DeviceLocation> {
799 let order = topo_order_multi(g, roots);
800 let mut map: HashMap<NodeId, DeviceLocation> = HashMap::with_capacity(order.len());
801 for &id in &order {
802 let node = g.node(id);
803 match node.op {
804 Op::Copy { target } | Op::Move { target } | Op::Alloc { target } => {
805 map.insert(id, target);
806 continue;
807 }
808 _ => {}
809 }
810 if let Some(loc) = g.placement(id) {
811 map.insert(id, loc);
812 continue;
813 }
814 if let Some(loc) = input_residency.and_then(|f| f(id)) {
815 map.insert(id, loc);
816 continue;
817 }
818 if let Some(winner) = plan.alternatives(id).and_then(|set| set.winner()) {
819 map.insert(id, winner.device);
820 continue;
821 }
822 if g.target_backend(id).is_some() {
823 map.insert(id, pinned_loc);
824 continue;
825 }
826 if (node.op.is_view_op() || matches!(node.op, Op::Reshape(_) | Op::Contiguize))
827 && let Some(&loc) = node.inputs.first().and_then(|i| map.get(i))
828 {
829 map.insert(id, loc);
830 }
831 }
832 map
833}
834
835/// The PR-A4 deliberate-fork pathfinder + the PR-B2 frontier
836/// convergence optimizer now live in [`crate::driver`] as registered
837/// [`crate::driver::Pathfinder`] / [`crate::driver::Optimizer`] impls
838/// ([`crate::driver::PlacementForkPathfinder`] /
839/// [`crate::driver::FrontierConvergenceOptimizer`]). PR-B3 replaced the
840/// hardcoded `seed_placement_fork_branches(...)` call in
841/// [`optimize_graph`] with a lock-step
842/// [`crate::driver::PassRegistry::run_lockstep`] drive over those
843/// registered passes (see the module docs). The pathfinder body is
844/// unchanged — it moved verbatim behind the trait.
845#[cfg(test)]
846mod tests {
847 use super::*;
848 use crate::fused::PrecisionGuarantee;
849 use crate::kernel::{KernelCaps, OpParams, unknown_cost};
850 use fuel_graph::opt::execution_plan;
851 use fuel_graph::{Node, Op};
852 use fuel_ir::dispatch::OpKind;
853 use fuel_ir::probe::BackendId;
854 use fuel_ir::{DType, DeviceLocation, Layout, Result as FuelResult, Shape};
855 use fuel_memory::Storage;
856 use std::sync::{Arc, RwLock};
857
858 fn noop_kernel(
859 _i: &[Arc<RwLock<Storage>>],
860 _o: &mut [Arc<RwLock<Storage>>],
861 _l: &[Layout],
862 _p: &OpParams,
863 ) -> FuelResult<()> {
864 Ok(())
865 }
866
867 fn register_elementwise(table: &mut KernelBindingTable, op: OpKind, n_in: usize) {
868 let mut dtypes = vec![DType::F32; n_in];
869 dtypes.push(DType::F32); // output dtype
870 table.register_full(
871 op,
872 &dtypes,
873 BackendId::Cpu,
874 noop_kernel,
875 KernelCaps::empty(),
876 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
877 unknown_cost,
878 );
879 }
880
881 fn f32_node(g: &mut Graph, op: Op, inputs: Vec<NodeId>) -> NodeId {
882 // No pre-stamp: post-Step-A `optimize_graph` writes `target_backend`
883 // itself, so pre-stamping here is redundant for the tests that run the
884 // optimizer — and it would falsify the `*_stamps_backends_*` tests'
885 // "unstamped before optimize" / "Const leaf not stamped" preconditions.
886 g.push(Node {
887 op,
888 inputs,
889 shape: Shape::from_dims(&[4]),
890 dtype: DType::F32,
891 })
892 }
893
894 /// A representative branchless CPU graph the optimizer can fully
895 /// place: a fan-in (`Add` over two unary chains) feeding a unary
896 /// tail. Every kernel-bearing op has a CPU binding registered. The
897 /// fan-in exercises the run extractor's multi-predecessor boundary,
898 /// so the equivalence holds across more than a single straight
899 /// chain.
900 fn build_branchless_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
901 register_elementwise(table, OpKind::ReluElementwise, 1);
902 register_elementwise(table, OpKind::SiluElementwise, 1);
903 register_elementwise(table, OpKind::AddElementwise, 2);
904 register_elementwise(table, OpKind::TanhElementwise, 1);
905
906 let mut g = Graph::new();
907 let a = f32_node(&mut g, Op::Const, vec![]);
908 let a1 = f32_node(&mut g, Op::Relu, vec![a]);
909 let b = f32_node(&mut g, Op::Const, vec![]);
910 let b1 = f32_node(&mut g, Op::Silu, vec![b]);
911 let sum = f32_node(&mut g, Op::Add, vec![a1, b1]);
912 let out = f32_node(&mut g, Op::Tanh, vec![sum]);
913 (g, out)
914 }
915
916 /// ROADMAP row 67 (I1): a graph whose analysed peak exceeds a small budget. `a` is read by `b` early and
917 /// by `c` late, so its longest inactive gap is evictable (the same shape the residency tests use).
918 fn build_over_budget_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
919 register_elementwise(table, OpKind::ReluElementwise, 1);
920 register_elementwise(table, OpKind::NegElementwise, 1);
921 register_elementwise(table, OpKind::MulElementwise, 2);
922 register_elementwise(table, OpKind::AddElementwise, 2);
923 let mut g = Graph::new();
924 let a = f32_node(&mut g, Op::Const, vec![]);
925 let b = f32_node(&mut g, Op::Relu, vec![a]);
926 let pad = f32_node(&mut g, Op::Neg, vec![b]);
927 let pad2 = f32_node(&mut g, Op::Neg, vec![pad]);
928 let c = f32_node(&mut g, Op::Mul, vec![pad2, a]);
929 let out = f32_node(&mut g, Op::Add, vec![b, c]);
930 (g, out)
931 }
932
933 fn count_ops(g: &Graph, pred: impl Fn(&Op) -> bool) -> usize {
934 (0..g.len())
935 .filter(|i| pred(&g.node(NodeId(*i)).op))
936 .count()
937 }
938
939 fn peak_bytes(g: &Graph, root: NodeId) -> usize {
940 crate::residency::ResidencyPlanner::analyze(g, &[root]).peak_bytes
941 }
942
943 #[test]
944 fn a_device_budget_below_the_peak_inserts_evict_reload_chains() {
945 let mut table = KernelBindingTable::new();
946 let (mut g, root) = build_over_budget_graph(&mut table);
947 let before = peak_bytes(&g, root);
948 let opts = cpu_opts().with_device_budget_bytes(before - 1);
949 let optimized =
950 optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph under a budget");
951 let outcome = optimized
952 .eviction
953 .as_ref()
954 .expect("a budgeted run reports what the eviction pass did");
955 assert!(
956 !outcome.chains.is_empty(),
957 "the outcome lists the inserted chains"
958 );
959 assert_eq!(outcome.budget_bytes, before - 1);
960 assert!(
961 count_ops(&g, |op| matches!(op, Op::Move { .. })) >= 1,
962 "a budget below the peak must insert an Op::Move eviction"
963 );
964 assert!(
965 count_ops(&g, |op| matches!(op, Op::Copy { .. })) >= 1,
966 "and its reload Op::Copy"
967 );
968 // Not asserted here: a drop in the analysed peak. This graph is pinned to the CPU, and a
969 // spill to the CPU cannot lower CPU residency; that property is pinned in
970 // `residency::tests::today_the_reload_runs_eagerly_so_the_device_peak_does_not_drop`
971 // (which documents that no round lowers the analysed peak until ROADMAP row 67 I3).
972 }
973
974 #[test]
975 fn the_plan_report_names_where_the_budget_came_from() {
976 use crate::device_budget::{BudgetSource, ResolvedBudget};
977 let run = |opts: PlanOptions<'_>| {
978 let mut table = KernelBindingTable::new();
979 let (mut g, root) = build_over_budget_graph(&mut table);
980 optimize_graph(&mut g, &[root], &table, &opts)
981 .expect("optimize_graph")
982 .eviction
983 .expect("a budgeted run reports an outcome")
984 };
985 let mut table = KernelBindingTable::new();
986 let (g, root) = build_over_budget_graph(&mut table);
987 let budget = peak_bytes(&g, root) - 1;
988 let resolved = ResolvedBudget {
989 bytes: budget,
990 source: BudgetSource::Probed {
991 available: (budget as u64) * 10 / 9,
992 fraction: 0.9,
993 },
994 };
995 let from_policy = run(cpu_opts().with_resolved_device_budget(resolved));
996 assert_eq!(from_policy.budget_bytes, budget);
997 assert_eq!(from_policy.budget_source, Some(resolved.source));
998 // Control: a hand-set number carries no source, so the two paths are told apart.
999 let by_hand = run(cpu_opts().with_device_budget_bytes(budget));
1000 assert_eq!(by_hand.budget_source, None);
1001 }
1002
1003 #[test]
1004 fn no_budget_a_roomy_budget_or_no_pinned_device_leave_the_graph_alone() {
1005 let nodes_of = |opts: &PlanOptions<'_>| {
1006 let mut table = KernelBindingTable::new();
1007 let (mut g, root) = build_over_budget_graph(&mut table);
1008 if opts.pinned_device.is_none() {
1009 // No pinned device: nodes need explicit placements to plan at all.
1010 for i in 0..g.len() {
1011 g.set_placement(NodeId(i), DeviceLocation::Cpu);
1012 }
1013 }
1014 let optimized = optimize_graph(&mut g, &[root], &table, opts).expect("optimize_graph");
1015 if opts.device_budget_bytes.is_none() {
1016 assert!(optimized.eviction.is_none(), "no budget: no outcome");
1017 }
1018 (g.len(), count_ops(&g, |op| matches!(op, Op::Move { .. })))
1019 };
1020 // Negative control: no budget at all.
1021 assert_eq!(nodes_of(&cpu_opts()).1, 0, "no budget: no eviction");
1022 // A budget the graph already fits.
1023 assert_eq!(
1024 nodes_of(&cpu_opts().with_device_budget_bytes(usize::MAX)).1,
1025 0,
1026 "roomy budget: no eviction"
1027 );
1028 // The pass is gated on a pinned device, like the residency pass it follows.
1029 let unpinned = PlanOptions::new()
1030 .without_cost_population()
1031 .with_device_budget_bytes(1);
1032 assert_eq!(nodes_of(&unpinned).1, 0, "no pinned device: no eviction");
1033 // Node counts match the no-budget run exactly.
1034 assert_eq!(
1035 nodes_of(&cpu_opts()).0,
1036 nodes_of(&cpu_opts().with_device_budget_bytes(usize::MAX)).0
1037 );
1038 }
1039
1040 /// A pure straight-line CPU graph — the simplest no-competing-route
1041 /// case (exactly one run by construction).
1042 fn build_straight_line_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
1043 register_elementwise(table, OpKind::ReluElementwise, 1);
1044 register_elementwise(table, OpKind::SiluElementwise, 1);
1045 register_elementwise(table, OpKind::TanhElementwise, 1);
1046
1047 let mut g = Graph::new();
1048 let a = f32_node(&mut g, Op::Const, vec![]);
1049 let b = f32_node(&mut g, Op::Relu, vec![a]);
1050 let c = f32_node(&mut g, Op::Silu, vec![b]);
1051 let d = f32_node(&mut g, Op::Tanh, vec![c]);
1052 (g, d)
1053 }
1054
1055 fn cpu_opts() -> PlanOptions<'static> {
1056 // No cost machinery: A3a only needs placement/validation, not
1057 // ranking. Pin the realize device so every node resolves.
1058 PlanOptions::new()
1059 .without_cost_population()
1060 .with_pinned_device(DeviceLocation::Cpu)
1061 }
1062
1063 /// Cleanup Step A: `optimize_graph` stamps each computational node's
1064 /// chosen backend onto the graph (the optimizer writes its placement
1065 /// decision INTO the graph). On a pinned-CPU straight-line graph every
1066 /// kernel-bearing node is stamped `Cpu`; the leaf `Op::Const` is
1067 /// skipped (it inherits / needs no stamp). When `pinned_device` is
1068 /// unset, no stamping occurs (the bare-graph test contract).
1069 #[test]
1070 fn optimize_graph_stamps_backends_onto_the_graph() {
1071 let mut table = KernelBindingTable::new();
1072 let (mut g, root) = build_straight_line_graph(&mut table);
1073 // a=Const(0), b=Relu(1), c=Silu(2), d=Tanh(3) by construction.
1074 let (a, b, c, d) = (NodeId(0), NodeId(1), NodeId(2), NodeId(3));
1075 assert!(g.target_backend(b).is_none(), "unstamped before optimize");
1076
1077 let _optimized = optimize_graph(&mut g, &[root], &table, &cpu_opts())
1078 .expect("optimize_graph on a straight-line CPU graph");
1079
1080 assert_eq!(
1081 g.target_backend(b),
1082 Some(BackendId::Cpu),
1083 "Relu stamped Cpu"
1084 );
1085 assert_eq!(
1086 g.target_backend(c),
1087 Some(BackendId::Cpu),
1088 "Silu stamped Cpu"
1089 );
1090 assert_eq!(
1091 g.target_backend(d),
1092 Some(BackendId::Cpu),
1093 "Tanh stamped Cpu"
1094 );
1095 assert!(
1096 g.target_backend(a).is_none(),
1097 "Op::Const leaf is not stamped"
1098 );
1099 }
1100
1101 /// `OptimizedGraph::placement_of` makes the placement DECISION observable,
1102 /// so a consumer can check where work landed instead of inferring it from
1103 /// timing (or from `Graph::placement`, which is only level 2 of the six-way
1104 /// resolution and returns `None` for exactly the compute nodes that matter).
1105 ///
1106 /// Two halves, and the second is the **positive control**: an accessor that
1107 /// silently returned `None` for everything would satisfy any test that only
1108 /// asserted `is_none()` on the unpinned path. So the pinned path asserts
1109 /// concrete `Some(Cpu)` values AND a non-empty map — if placement were never
1110 /// captured, that half fails loudly rather than passing vacuously.
1111 #[test]
1112 fn placement_of_observes_the_decision_and_marks_not_computed() {
1113 // --- pinned: the residency pass runs, placements are captured ---
1114 let mut table = KernelBindingTable::new();
1115 let (mut g, root) = build_straight_line_graph(&mut table);
1116 let (_a, b, c, d) = (NodeId(0), NodeId(1), NodeId(2), NodeId(3));
1117
1118 let optimized = optimize_graph(&mut g, &[root], &table, &cpu_opts())
1119 .expect("optimize_graph on a straight-line CPU graph");
1120
1121 assert!(
1122 optimized.has_placements(),
1123 "a pinned device runs the residency pass, so placements must be computed",
1124 );
1125 // POSITIVE CONTROL: concrete values, not merely "not None". An empty or
1126 // never-populated map would fail here instead of passing quietly.
1127 assert_eq!(
1128 optimized.placement_of(b),
1129 Some(DeviceLocation::Cpu),
1130 "Relu placed Cpu"
1131 );
1132 assert_eq!(
1133 optimized.placement_of(c),
1134 Some(DeviceLocation::Cpu),
1135 "Silu placed Cpu"
1136 );
1137 assert_eq!(
1138 optimized.placement_of(d),
1139 Some(DeviceLocation::Cpu),
1140 "Tanh placed Cpu"
1141 );
1142 assert!(
1143 optimized.placements().count() >= 3,
1144 "the map must actually be populated, got {} entries",
1145 optimized.placements().count(),
1146 );
1147
1148 // --- unpinned: the pass is skipped, and that is DISTINGUISHABLE ---
1149 // This is the property that keeps a `None` from being misread as
1150 // "placed nowhere" — the failure mode this accessor exists to prevent.
1151 //
1152 // Device context has to come from SOMEWHERE or `compile_plan` refuses
1153 // outright ("node has no device context — set PlanOptions::pinned_device,
1154 // a graph placement, or the node's target_backend"). So supply it via
1155 // per-node graph placement instead of a pin: the graph optimizes fine,
1156 // but `pinned_device` is unset so the residency pass never runs — which
1157 // is exactly the "optimized successfully, placement not computed" state
1158 // a caller must be able to tell apart from "placed nowhere".
1159 let mut table2 = KernelBindingTable::new();
1160 let (mut g2, root2) = build_straight_line_graph(&mut table2);
1161 for n in [NodeId(0), NodeId(1), NodeId(2), NodeId(3)] {
1162 g2.set_placement(n, DeviceLocation::Cpu);
1163 }
1164 let bare = PlanOptions::new().without_cost_population();
1165 let unpinned = optimize_graph(&mut g2, &[root2], &table2, &bare)
1166 .expect("optimize_graph with graph placements but no pinned device");
1167
1168 assert!(
1169 !unpinned.has_placements(),
1170 "no pinned device => residency pass skipped => placements NOT computed",
1171 );
1172 assert_eq!(
1173 unpinned.placement_of(b),
1174 None,
1175 "and every lookup is None — which `has_placements()` explains as \
1176 'not computed', never 'placed nowhere'",
1177 );
1178 }
1179
1180 /// Dtype-reconciliation declines on the REAL CPU table: the mixed-precision `[F32, BF16, F32]`
1181 /// and `[F32, F16, F32]` matmuls (f32 activation x half weight) are served natively by the CPU
1182 /// kernels `matmul_f32_bf16` / `matmul_f32_f16` (ROADMAP row 34), so `optimize_graph` plans them
1183 /// as they are and inserts no `Cast`: the weight stays half-width instead of being promoted to a
1184 /// resident f32 copy. Before row 34 this test asserted the opposite (a `Cast(F32)` on the
1185 /// weight, the fallback that the local-table tests below still pin for a backend WITHOUT the
1186 /// native key).
1187 #[test]
1188 fn optimize_graph_keeps_mixed_precision_matmul_native_on_cpu() {
1189 for weight in [DType::BF16, DType::F16] {
1190 let bindings = crate::dispatch::global_bindings(); // real populated CPU table
1191 let mut g = Graph::new();
1192 let lhs = g.push(Node {
1193 op: Op::Const,
1194 inputs: vec![],
1195 shape: Shape::from_dims(&[2, 3]),
1196 dtype: DType::F32,
1197 });
1198 let rhs = g.push(Node {
1199 op: Op::Const,
1200 inputs: vec![],
1201 shape: Shape::from_dims(&[3, 2]),
1202 dtype: weight,
1203 });
1204 let mm = g.push(Node {
1205 op: Op::MatMul,
1206 inputs: vec![lhs, rhs],
1207 shape: Shape::from_dims(&[2, 2]),
1208 dtype: DType::F32,
1209 });
1210
1211 optimize_graph(&mut g, &[mm], &bindings, &cpu_opts())
1212 .expect("mixed-precision matmul plans natively on CPU");
1213
1214 assert_eq!(
1215 g.node(mm).inputs,
1216 vec![lhs, rhs],
1217 "{weight:?}: no Cast, the CPU serves [F32, {weight:?}, F32] natively",
1218 );
1219 assert_eq!(g.node(rhs).dtype, weight, "the weight stays {weight:?}");
1220 }
1221 }
1222
1223 fn register_matmul(table: &mut KernelBindingTable, dtypes: &[DType], backend: BackendId) {
1224 table.register_full(
1225 OpKind::MatMul,
1226 dtypes,
1227 backend,
1228 noop_kernel,
1229 KernelCaps::empty(),
1230 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1231 unknown_cost,
1232 );
1233 }
1234
1235 /// The reconciling `Op::Cast` the pass inserts needs a binding of its own to
1236 /// plan. The production table has these (`(Cpu, Cast, [BF16, F32])`); a
1237 /// hand-built test table must register them explicitly.
1238 fn register_cast(table: &mut KernelBindingTable, from: DType, to: DType, backend: BackendId) {
1239 table.register_full(
1240 OpKind::Cast,
1241 &[from, to],
1242 backend,
1243 noop_kernel,
1244 KernelCaps::empty(),
1245 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1246 unknown_cost,
1247 );
1248 }
1249
1250 /// `[F32] @ [BF16] -> [F32]` on a graph pinned to `pinned`.
1251 fn mixed_matmul_graph() -> (Graph, NodeId, NodeId, NodeId) {
1252 let mut g = Graph::new();
1253 let lhs = g.push(Node {
1254 op: Op::Const,
1255 inputs: vec![],
1256 shape: Shape::from_dims(&[2, 3]),
1257 dtype: DType::F32,
1258 });
1259 let rhs = g.push(Node {
1260 op: Op::Const,
1261 inputs: vec![],
1262 shape: Shape::from_dims(&[3, 2]),
1263 dtype: DType::BF16,
1264 });
1265 let mm = g.push(Node {
1266 op: Op::MatMul,
1267 inputs: vec![lhs, rhs],
1268 shape: Shape::from_dims(&[2, 2]),
1269 dtype: DType::F32,
1270 });
1271 (g, lhs, rhs, mm)
1272 }
1273
1274 /// **Born-red regression guard: a backend must never break a graph that
1275 /// isn't running on it.**
1276 ///
1277 /// `insert_dtype_fixups` used to guard on `any_backend_supports` — a
1278 /// predicate over the WHOLE binding table that ignores the key's backend
1279 /// component. `compile_plan` enumerates over the node's *candidate
1280 /// placement set*. So when a non-candidate backend owned the only native
1281 /// mixed-dtype kernel, the pass saw "someone serves it", declined to
1282 /// reconcile, and the planner then dead-ended at `NoBackendForOp`.
1283 ///
1284 /// In-tree that surfaced as `--features vulkan` breaking CPU-pinned
1285 /// mixed-precision matmul, because Vulkan happens to be the only backend
1286 /// registering `MatMul[F32, BF16, F32]`. This test builds that situation
1287 /// from a LOCAL table so it reproduces in **every** build configuration —
1288 /// the feature-gated version is why the defect shipped unnoticed.
1289 #[test]
1290 fn dtype_reconciliation_ignores_kernels_on_non_candidate_backends() {
1291 let mut table = KernelBindingTable::new();
1292 // The pinned backend serves only the uniform key...
1293 register_matmul(
1294 &mut table,
1295 &[DType::F32, DType::F32, DType::F32],
1296 BackendId::Cpu,
1297 );
1298 // ...while a backend this graph will never run on owns the mixed key.
1299 register_matmul(
1300 &mut table,
1301 &[DType::F32, DType::BF16, DType::F32],
1302 BackendId::Vulkan,
1303 );
1304 register_cast(&mut table, DType::BF16, DType::F32, BackendId::Cpu);
1305
1306 let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
1307 optimize_graph(&mut g, &[mm], &table, &cpu_opts()).expect(
1308 "CPU-pinned mixed-precision matmul must reconcile via Cast even though \
1309 a NON-candidate backend owns the native mixed kernel",
1310 );
1311
1312 let mm_inputs = g.node(mm).inputs.clone();
1313 assert_eq!(mm_inputs[0], lhs, "lhs (already F32) untouched");
1314 let cast_id = mm_inputs[1];
1315 assert_ne!(cast_id, rhs, "rhs was rewired to a Cast");
1316 assert!(
1317 matches!(g.node(cast_id).op, Op::Cast(DType::F32)),
1318 "rhs cast to F32"
1319 );
1320 assert_eq!(
1321 g.node(cast_id).inputs,
1322 vec![rhs],
1323 "cast reads the original BF16 weight"
1324 );
1325 }
1326
1327 /// The converse guard — the fix must not over-cast. When the node's own
1328 /// candidate backend serves the mixed key natively, reconciliation must
1329 /// decline, so the native mixed-precision kernel is preserved (casting
1330 /// would change numerics and double the promoted operand's bytes).
1331 #[test]
1332 fn dtype_reconciliation_declines_when_the_candidate_backend_serves_it_natively() {
1333 let mut table = KernelBindingTable::new();
1334 register_matmul(
1335 &mut table,
1336 &[DType::F32, DType::BF16, DType::F32],
1337 BackendId::Cpu,
1338 );
1339
1340 let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
1341 optimize_graph(&mut g, &[mm], &table, &cpu_opts()).expect("native mixed kernel plans");
1342
1343 assert_eq!(
1344 g.node(mm).inputs,
1345 vec![lhs, rhs],
1346 "no Cast: the candidate backend has the native mixed kernel",
1347 );
1348 }
1349
1350 /// Multi-device behavior must be PRESERVED, not sacrificed to fix the bug
1351 /// above. When an off-device fallback is admitted, the foreign backend IS
1352 /// a candidate for this node — so its native mixed kernel is reachable and
1353 /// reconciliation must still decline. This is why the fix mirrors the
1354 /// planner's candidate set rather than narrowing to the pinned device.
1355 #[test]
1356 fn dtype_reconciliation_counts_admitted_off_device_fallback_as_a_candidate() {
1357 let mut table = KernelBindingTable::new();
1358 register_matmul(
1359 &mut table,
1360 &[DType::F32, DType::F32, DType::F32],
1361 BackendId::Cpu,
1362 );
1363 register_matmul(
1364 &mut table,
1365 &[DType::F32, DType::BF16, DType::F32],
1366 BackendId::Vulkan,
1367 );
1368
1369 let fallback = |_from: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
1370 vec![(BackendId::Vulkan, DeviceLocation::Vulkan { gpu_id: 0 })]
1371 };
1372 let opts = PlanOptions::new()
1373 .without_cost_population()
1374 .with_pinned_device(DeviceLocation::Cpu)
1375 .with_fallback_placements_for(&fallback);
1376
1377 let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
1378 optimize_graph(&mut g, &[mm], &table, &opts).expect("off-device native mixed kernel plans");
1379
1380 assert_eq!(
1381 g.node(mm).inputs,
1382 vec![lhs, rhs],
1383 "no Cast: the admitted off-device fallback backend serves the mixed key natively",
1384 );
1385 }
1386
1387 /// The stamping is guarded on a pinned device — an `optimize_graph`
1388 /// with no `pinned_device` leaves the graph unstamped (so the bare
1389 /// optimize.rs test callers below are unaffected by Step A).
1390 #[test]
1391 fn optimize_graph_without_pinned_device_does_not_stamp() {
1392 let mut table = KernelBindingTable::new();
1393 let (mut g, root) = build_straight_line_graph(&mut table);
1394 // Give each node a device context via a graph PLACEMENT (a distinct
1395 // side-table from `target_backend`), so `compile_plan` resolves without
1396 // a pinned device — then assert `optimize_graph` performs no
1397 // `target_backend` stamping (the stamping arm is guarded on
1398 // `pinned_device`, so without a pin nothing is stamped).
1399 for id in [NodeId(0), NodeId(1), NodeId(2), NodeId(3)] {
1400 g.set_placement(id, DeviceLocation::Cpu);
1401 }
1402 let opts = PlanOptions::new().without_cost_population(); // no pinned device
1403 let _ = optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph");
1404 assert!(
1405 g.target_backend(NodeId(1)).is_none(),
1406 "no pinned device ⇒ no target_backend stamping",
1407 );
1408 }
1409
1410 /// Cleanup Step B (layout): `optimize_graph` inserts an `Op::Contiguize`
1411 /// before a kernel whose chosen winner rejects strided inputs
1412 /// (`caps.strided_input == false`, e.g. the `KernelCaps::empty()`
1413 /// elementwise bindings) and whose input layout is non-contiguous — the
1414 /// layout-fixup pass moved from the realize-time bridge into the optimizer.
1415 /// The pass itself is exhaustively tested in `fuel-graph::opt`; this guards
1416 /// the optimizer-side wiring (callback reads the plan winner's caps, runs
1417 /// inside the pinned guard).
1418 #[test]
1419 fn optimize_graph_inserts_layout_fixup_for_strided_input() {
1420 let mut table = KernelBindingTable::new();
1421 register_elementwise(&mut table, OpKind::ReluElementwise, 1); // empty caps ⇒ rejects strided
1422 let mut g = Graph::new();
1423 let a = f32_node(&mut g, Op::Const, vec![]);
1424 let r = f32_node(&mut g, Op::Relu, vec![a]);
1425 // Make `a`'s effective layout non-contiguous (non-zero start_offset),
1426 // so the strided-rejecting Relu needs a Contiguize on its input.
1427 g.set_layout(a, Layout::contiguous_with_offset(Shape::from_dims(&[4]), 1));
1428
1429 let _optimized = optimize_graph(&mut g, &[r], &table, &cpu_opts())
1430 .expect("optimize_graph with a strided input");
1431
1432 // Relu's input was `a`; after the fixup it must read through an inserted
1433 // Op::Contiguize wrapping `a`.
1434 let relu_input = g.node(r).inputs[0];
1435 assert!(
1436 matches!(g.node(relu_input).op, Op::Contiguize),
1437 "strided input to a strided-rejecting kernel must be fixed up via \
1438 Op::Contiguize, got {:?}",
1439 g.node(relu_input).op,
1440 );
1441 assert_eq!(
1442 g.node(relu_input).inputs,
1443 vec![a],
1444 "the inserted Op::Contiguize wraps the original strided input",
1445 );
1446 }
1447
1448 // ---- Cleanup Step B (residency) — insert_residency_copies tests ----
1449 // (migrated from the bridge's insert_resident_input_copies unit tests;
1450 // cache residency is supplied via an `input_residency` closure instead of a
1451 // live StorageCache. Placement metadata only — no GPU needed; the unprobed
1452 // test `SystemTopology` reports Cpu/Cuda as non-sharing, so a crossing is
1453 // detected and a copy inserted.)
1454
1455 /// Co-located graph ⇒ `insert_residency_copies` is a no-op (no crossings).
1456 #[test]
1457 fn residency_noop_when_colocated() {
1458 let mut g = Graph::new();
1459 let c1 = f32_node(&mut g, Op::Const, vec![]);
1460 let c2 = f32_node(&mut g, Op::Const, vec![]);
1461 let add = f32_node(&mut g, Op::Add, vec![c1, c2]);
1462 g.set_target_backend(add, BackendId::Cpu);
1463 let residency = |id: NodeId| (id == c1 || id == c2).then_some(DeviceLocation::Cpu);
1464 let pre = g.len();
1465 insert_residency_copies(
1466 &mut g,
1467 &[add],
1468 &ExecutionPlan::empty(),
1469 DeviceLocation::Cpu,
1470 Some(&residency),
1471 );
1472 assert_eq!(g.len(), pre, "co-located graph must be a no-op");
1473 assert_eq!(g.node(add).inputs, vec![c1, c2], "edges untouched");
1474 }
1475
1476 /// A CPU-resident input feeding two CUDA-pinned consumers ⇒ exactly ONE
1477 /// `Op::Copy` bridges the crossing (CSE-deduped), targeting the consumer
1478 /// device, stamped `target_backend = SOURCE` (Cpu, the H2D wrapper) with
1479 /// its output placed on the consumer device.
1480 #[test]
1481 fn residency_one_copy_per_crossing_deduped() {
1482 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
1483 let mut g = Graph::new();
1484 let c1 = f32_node(&mut g, Op::Const, vec![]);
1485 let neg = f32_node(&mut g, Op::Neg, vec![c1]);
1486 let sqr = f32_node(&mut g, Op::Sqr, vec![c1]);
1487 g.set_target_backend(neg, BackendId::Cuda);
1488 g.set_target_backend(sqr, BackendId::Cuda);
1489 let residency = |id: NodeId| (id == c1).then_some(DeviceLocation::Cpu);
1490
1491 let pre = g.len();
1492 insert_residency_copies(
1493 &mut g,
1494 &[neg, sqr],
1495 &ExecutionPlan::empty(),
1496 cuda0,
1497 Some(&residency),
1498 );
1499
1500 assert_eq!(g.len(), pre + 1, "one crossing → one copy, CSE-deduped");
1501 let neg_in = g.node(neg).inputs[0];
1502 let sqr_in = g.node(sqr).inputs[0];
1503 assert_eq!(neg_in, sqr_in, "both consumers share the one copy");
1504 assert_ne!(neg_in, c1, "consumers rewired off the raw input");
1505 let copy = g.node(neg_in);
1506 assert!(
1507 matches!(copy.op, Op::Copy { target } if target == cuda0),
1508 "copy targets the consumer device; got {:?}",
1509 copy.op,
1510 );
1511 assert_eq!(copy.inputs, vec![c1], "copy reads the resident slot");
1512 assert_eq!(
1513 g.target_backend(neg_in),
1514 Some(BackendId::Cpu),
1515 "stamped with the SOURCE backend (H2D runs on the CPU wrapper)",
1516 );
1517 assert_eq!(
1518 g.placement(neg_in),
1519 Some(cuda0),
1520 "copy output placed on the consumer device",
1521 );
1522 }
1523
1524 /// Idempotence + re-stamp: a second pass on the rewritten graph inserts
1525 /// nothing and restores the source-backend stamp even after a clobber
1526 /// (mimicking `stamp_plan_backends` overwriting it with the pinned backend).
1527 #[test]
1528 fn residency_idempotent_and_restamped_on_second_call() {
1529 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
1530 let mut g = Graph::new();
1531 let c1 = f32_node(&mut g, Op::Const, vec![]);
1532 let neg = f32_node(&mut g, Op::Neg, vec![c1]);
1533 g.set_target_backend(neg, BackendId::Cuda);
1534 let residency = |id: NodeId| (id == c1).then_some(DeviceLocation::Cpu);
1535
1536 insert_residency_copies(
1537 &mut g,
1538 &[neg],
1539 &ExecutionPlan::empty(),
1540 cuda0,
1541 Some(&residency),
1542 );
1543 let copy_id = g.node(neg).inputs[0];
1544 // Simulate stamp_plan_backends clobbering the copy with the pinned backend.
1545 g.set_target_backend(copy_id, BackendId::Cuda);
1546
1547 let pre = g.len();
1548 insert_residency_copies(
1549 &mut g,
1550 &[neg],
1551 &ExecutionPlan::empty(),
1552 cuda0,
1553 Some(&residency),
1554 );
1555 assert_eq!(g.len(), pre, "re-run inserts nothing");
1556 assert_eq!(
1557 g.target_backend(copy_id),
1558 Some(BackendId::Cpu),
1559 "re-stamp sweep restores the source-backend stamp",
1560 );
1561 }
1562
1563 // ---- Step E Phase C, PR C-0: arm residency-copy audit ----
1564 //
1565 // C2 lets the executor re-pick an `Op::Branch` arm at runtime by live
1566 // device load — it may choose arm-1+ instead of the static arm-0 winner.
1567 // That is only legal if the optimizer's residency pass has ALREADY
1568 // stitched the inbound cross-device `Op::Copy` for EVERY surviving arm,
1569 // so whichever arm the executor picks, that arm's device-inputs are
1570 // resident on its device. This test builds a 2-arm diamond whose two arms
1571 // live on DIFFERENT devices (arm-0 CPU, arm-1 CUDA) sharing one CPU
1572 // producer, runs the residency pass, and asserts BOTH arms' cross-device
1573 // inputs got their copy — not just arm-0's.
1574 //
1575 // The finalized `Op::Branch` is orphaned (its `reconverge_at` reads arm-0
1576 // directly, per the PR-A1 runnability invariant), so arm-1 is reachable
1577 // ONLY through the Branch node. `insert_residency_copies` walks
1578 // `topo_order_multi(roots)` directly (NOT `effective_roots`), so it never
1579 // reaches an orphaned Branch — and therefore never reaches arm-1. The
1580 // run/route machinery (`extract_runs_multi`, `branches_in_topo_order`)
1581 // does use `effective_roots`; the residency pass does not. This is the
1582 // C-0 prerequisite gap.
1583
1584 /// Build a 2-arm diamond: a CPU producer `diverge` fans into arm-0 (CPU)
1585 /// and arm-1 (`arm1_loc`); `reconverge` reads arm-0 (the runnability
1586 /// invariant); the Branch merges {arm0, arm1} at `reconverge`. Returns
1587 /// `(graph, branch, diverge, arm0, arm1, post)`. Placements are set via
1588 /// `set_placement` so the residency pass reads them with no plan/winner.
1589 fn residency_diamond(
1590 arm1_loc: DeviceLocation,
1591 ) -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId) {
1592 let mut g = Graph::new();
1593 let pre = f32_node(&mut g, Op::Const, vec![]);
1594 let diverge = f32_node(&mut g, Op::Relu, vec![pre]);
1595 let arm0 = f32_node(&mut g, Op::Silu, vec![diverge]);
1596 let arm1 = f32_node(&mut g, Op::GeluTanh, vec![diverge]);
1597 let reconverge = f32_node(&mut g, Op::Relu, vec![arm0]);
1598 let mut b = g.open_branch(diverge);
1599 b.add_arm(arm0);
1600 b.add_arm(arm1);
1601 let branch = b
1602 .finalize_branches(&mut g, reconverge)
1603 .expect("well-formed 2-arm branch")
1604 .expect("2 arms survive");
1605 let post = f32_node(&mut g, Op::Tanh, vec![reconverge]);
1606 // Producer + arm-0 + the post-merge region on CPU; arm-1 elsewhere.
1607 g.set_placement(pre, DeviceLocation::Cpu);
1608 g.set_placement(diverge, DeviceLocation::Cpu);
1609 g.set_placement(arm0, DeviceLocation::Cpu);
1610 g.set_placement(reconverge, DeviceLocation::Cpu);
1611 g.set_placement(post, DeviceLocation::Cpu);
1612 g.set_placement(arm1, arm1_loc);
1613 (g, branch, diverge, arm0, arm1, post)
1614 }
1615
1616 /// C-0 PREREQUISITE: the residency pass must insert the inbound
1617 /// cross-device `Op::Copy` for BOTH arms of a 2-device branch — arm-0
1618 /// (CPU, same device as the producer ⇒ no copy needed) AND arm-1 (CUDA,
1619 /// crosses ⇒ MUST get a copy). If only arm-0 were stitched, re-picking
1620 /// arm-1 at runtime (C2) would dispatch a CUDA kernel whose input was
1621 /// never copied to the GPU → the un-bridged-mixed-edge error / a UAF.
1622 #[test]
1623 fn residency_stitches_every_branch_arm_not_just_arm0() {
1624 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
1625 let (mut g, _branch, diverge, arm0, arm1, post) = residency_diamond(cuda0);
1626
1627 insert_residency_copies(
1628 &mut g,
1629 &[post],
1630 &ExecutionPlan::empty(),
1631 DeviceLocation::Cpu,
1632 None,
1633 );
1634
1635 // arm-0 is CPU, same substrate as the CPU producer ⇒ its input edge
1636 // does NOT cross ⇒ no copy (and must stay reading `diverge`).
1637 assert_eq!(
1638 g.node(arm0).inputs,
1639 vec![diverge],
1640 "arm-0 is co-located with its producer ⇒ no copy, edge untouched",
1641 );
1642
1643 // arm-1 is CUDA, its producer `diverge` is CPU ⇒ the edge crosses ⇒
1644 // the residency pass MUST have inserted an Op::Copy targeting CUDA on
1645 // arm-1's input. THIS is the C-0 invariant: every surviving arm's
1646 // device-inputs are made resident, not just arm-0's.
1647 let arm1_in = g.node(arm1).inputs[0];
1648 assert_ne!(
1649 arm1_in, diverge,
1650 "arm-1 (CUDA) reads the CPU producer directly — its inbound \
1651 cross-device Op::Copy was NEVER inserted. Re-picking arm-1 at \
1652 runtime (C2) would dispatch a CUDA kernel over un-copied CPU \
1653 bytes. The residency pass stitched only arm-0's route.",
1654 );
1655 let copy = g.node(arm1_in);
1656 assert!(
1657 matches!(copy.op, Op::Copy { target } if target == cuda0),
1658 "arm-1's inbound copy must target CUDA; got {:?}",
1659 copy.op,
1660 );
1661 assert_eq!(
1662 copy.inputs,
1663 vec![diverge],
1664 "arm-1's copy reads the shared CPU producer",
1665 );
1666 }
1667
1668 // ---- PR-A4 deliberate-fork-seed test substrate ----
1669
1670 fn noop_kernel_b(
1671 _i: &[Arc<RwLock<Storage>>],
1672 _o: &mut [Arc<RwLock<Storage>>],
1673 _l: &[Layout],
1674 _p: &OpParams,
1675 ) -> FuelResult<()> {
1676 Ok(())
1677 }
1678
1679 /// Register a CPU AND a (synthetic) CUDA binding for `op` so a node
1680 /// enumerated against both placements gets two viable
1681 /// `(backend, device)` candidates — the genuine placement fork the
1682 /// A4 pathfinder seeds a branch from.
1683 fn register_two_backend(table: &mut KernelBindingTable, op: OpKind, n_in: usize) {
1684 let mut dtypes = vec![DType::F32; n_in];
1685 dtypes.push(DType::F32);
1686 table.register_full(
1687 op,
1688 &dtypes,
1689 BackendId::Cpu,
1690 noop_kernel,
1691 KernelCaps::empty(),
1692 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1693 unknown_cost,
1694 );
1695 table.register_full(
1696 op,
1697 &dtypes,
1698 BackendId::Cuda,
1699 noop_kernel_b,
1700 KernelCaps::empty(),
1701 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1702 unknown_cost,
1703 );
1704 }
1705
1706 fn two_backend_placements(dev: DeviceLocation) -> Vec<BackendId> {
1707 if dev == DeviceLocation::Cpu {
1708 vec![BackendId::Cpu, BackendId::Cuda]
1709 } else {
1710 vec![]
1711 }
1712 }
1713
1714 /// Two backends co-located at the realize device, so every
1715 /// kernel-bearing node enumerates ≥2 placements — the multi-backend
1716 /// build the A4 pathfinder forks on. CPU-only builds (one placement
1717 /// per node) never hit this; the equivalence/idempotence gates above
1718 /// cover that.
1719 fn two_backend_opts() -> PlanOptions<'static> {
1720 PlanOptions::new()
1721 .without_cost_population()
1722 .with_pinned_device(DeviceLocation::Cpu)
1723 .with_placements_for_device(&two_backend_placements)
1724 }
1725
1726 /// A graph with a single kernel-bearing node that has a genuine
1727 /// ≥2-placement choice AND exactly one consumer (so it is a
1728 /// deliberate fork, not plain fan-out). Only `fork`'s op (`Silu`) is
1729 /// registered on two backends, so it is the ONLY node with a real
1730 /// ≥2-placement choice — exactly the "most ops are CPU-only, the
1731 /// matmul has cuBLAS too" shape.
1732 ///
1733 /// A long CPU-only `Relu` body surrounds the fork so the single
1734 /// deliberate branch sits far below the fewness threshold (a tiny
1735 /// graph would be all-branch by node count): `c -> body* -> prod ->
1736 /// fork -> tail -> body*`. `prod` is the diverge; `tail` is the
1737 /// reconverge (it reads `fork`).
1738 fn build_single_fork_graph(
1739 table: &mut KernelBindingTable,
1740 ) -> (Graph, NodeId, NodeId, NodeId, NodeId) {
1741 register_elementwise(table, OpKind::ReluElementwise, 1);
1742 register_two_backend(table, OpKind::SiluElementwise, 1); // the fork
1743 register_elementwise(table, OpKind::TanhElementwise, 1);
1744
1745 let mut g = Graph::new();
1746 let mut prev = f32_node(&mut g, Op::Const, vec![]);
1747 // Straight-line CPU body before the fork.
1748 for _ in 0..20 {
1749 prev = f32_node(&mut g, Op::Relu, vec![prev]);
1750 }
1751 let prod = prev; // the diverge (fork's producer)
1752 let fork = f32_node(&mut g, Op::Silu, vec![prod]);
1753 let tail = f32_node(&mut g, Op::Tanh, vec![fork]); // reconverge
1754 // Straight-line CPU body after the reconverge — the realize root
1755 // is the body's tail, so the whole graph is reachable and the
1756 // single fork sits far below the fewness threshold.
1757 let mut prev = tail;
1758 for _ in 0..20 {
1759 prev = f32_node(&mut g, Op::Relu, vec![prev]);
1760 }
1761 let root = prev;
1762 (g, prod, fork, tail, root)
1763 }
1764
1765 /// THE A4 DELIBERATE-FORK GATE (born-red until the pathfinder
1766 /// emits a Branch).
1767 ///
1768 /// (a) A node with two viable `(backend, device)` placements and a
1769 /// single consumer ⇒ `optimize_graph` emits exactly ONE 2-arm
1770 /// `Op::Branch` whose arm-0 is the DP winner, and the result passes
1771 /// the fewness gate.
1772 #[test]
1773 fn deliberate_fork_emits_one_two_arm_branch() {
1774 use fuel_graph::{branch_density, passes_fewness_gate};
1775 let mut table = KernelBindingTable::new();
1776 let (mut g, _prod, fork, _tail, root) = build_single_fork_graph(&mut table);
1777 let opts = two_backend_opts();
1778
1779 let nodes_before = g.len();
1780 let optimized = optimize_graph(&mut g, &[root], &table, &opts)
1781 .expect("optimize_graph succeeds on a 2-placement graph");
1782
1783 // Exactly one Op::Branch in the arena.
1784 assert_eq!(
1785 optimized.branch_count(&g),
1786 1,
1787 "a single genuine placement fork emits exactly one Op::Branch",
1788 );
1789
1790 // It is a 2-arm branch (arm-0 = the winner = `fork`).
1791 let branch_id = (nodes_before..g.len())
1792 .map(NodeId)
1793 .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
1794 .expect("a Branch node was appended");
1795 let branch = g.node(branch_id);
1796 assert_eq!(branch.inputs.len(), 2, "the branch has exactly two arms");
1797 assert_eq!(
1798 branch.inputs[0], fork,
1799 "arm-0 is the DP winner node (the route realize uses today)",
1800 );
1801 assert_ne!(
1802 branch.inputs[1], fork,
1803 "arm-1 is a distinct (runner-up placement) node",
1804 );
1805
1806 // The fewness gate holds — one branch among many nodes.
1807 assert!(
1808 passes_fewness_gate(&g, root),
1809 "a single deliberate fork passes the fewness gate; density={}",
1810 branch_density(&g, root),
1811 );
1812 }
1813
1814 /// (b) An ordinary DAG fan-out (one result, two distinct consumers)
1815 /// with the SAME 2-placement freedom is NOT flagged as a branch —
1816 /// fan-out is not a decision point.
1817 #[test]
1818 fn plain_fan_out_is_not_a_branch() {
1819 let mut table = KernelBindingTable::new();
1820 // Only the fan-out node's op (`Relu`) is dual-backend, so it is
1821 // the sole ≥2-placement candidate — and it is excluded purely
1822 // because it fans out (two consumers), not because it lacks a
1823 // placement choice. The consumers are CPU-only.
1824 register_two_backend(&mut table, OpKind::ReluElementwise, 1);
1825 register_elementwise(&mut table, OpKind::SiluElementwise, 1);
1826 register_elementwise(&mut table, OpKind::TanhElementwise, 1);
1827 register_elementwise(&mut table, OpKind::AddElementwise, 2);
1828
1829 // `shared` has two distinct consumers (c0, c1) that join at
1830 // `out` — plain fan-out, not a fork — even though it has a real
1831 // 2-placement choice.
1832 let mut g = Graph::new();
1833 let c = f32_node(&mut g, Op::Const, vec![]);
1834 let shared = f32_node(&mut g, Op::Relu, vec![c]);
1835 let c0 = f32_node(&mut g, Op::Silu, vec![shared]);
1836 let c1 = f32_node(&mut g, Op::Tanh, vec![shared]);
1837 let out = f32_node(&mut g, Op::Add, vec![c0, c1]);
1838 let opts = two_backend_opts();
1839
1840 let optimized =
1841 optimize_graph(&mut g, &[out], &table, &opts).expect("optimize_graph succeeds");
1842 assert_eq!(
1843 optimized.branch_count(&g),
1844 0,
1845 "plain fan-out (multiple consumers) is not a deliberate fork",
1846 );
1847 let _ = shared;
1848 }
1849
1850 /// (c) A branched graph realizes correctly via arm-0: the dispatch
1851 /// order follows {pre, arm-0, post} and SKIPS arm-1's run.
1852 #[test]
1853 fn branched_graph_realizes_via_arm0() {
1854 let mut table = KernelBindingTable::new();
1855 let (mut g, prod, fork, tail, root) = build_single_fork_graph(&mut table);
1856 let opts = two_backend_opts();
1857
1858 // Capture the single-route order BEFORE the branch is emitted —
1859 // this is the order realize must reproduce on arm-0.
1860 let pre_order = execution_plan(&g, &[root]);
1861
1862 let optimized =
1863 optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
1864 assert_eq!(optimized.branch_count(&g), 1, "exactly one branch");
1865
1866 // The arm-1 node is the branch's second input — it must NOT
1867 // appear in the arm-0 dispatch order.
1868 let branch_id = (0..g.len())
1869 .map(NodeId)
1870 .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
1871 .expect("a Branch node exists");
1872 let arm1 = g.node(branch_id).inputs[1];
1873
1874 let order = optimized.dispatch_order(&g);
1875 assert!(
1876 !order.contains(&arm1),
1877 "arm-0 lowering must skip arm-1's run; order={order:?} arm1={arm1:?}",
1878 );
1879 // arm-0 (fork) and the pre/post nodes ARE executed.
1880 assert!(order.contains(&prod), "pre-run (diverge producer) executes");
1881 assert!(order.contains(&fork), "arm-0 (the winner) executes");
1882 assert!(order.contains(&tail), "post-run (reconverge) executes");
1883 assert!(order.contains(&root), "the realize root executes");
1884
1885 // Behavior preserving: arm-0 lowering reproduces exactly the
1886 // pre-branch single-route order (arm-0 = the DP winner = the
1887 // graph realize used before the branch was recorded).
1888 assert_eq!(
1889 order, pre_order,
1890 "arm-0 dispatch order equals the pre-branch single-route order",
1891 );
1892 }
1893
1894 /// Return type of [`cached_env_test_fixture`] — named purely to dodge
1895 /// `clippy::type_complexity`, not because any caller needs the alias.
1896 type CachedEnvTestFixture = (
1897 Arc<RwLock<Graph>>,
1898 crate::pipelined::StorageCache,
1899 OptimizedGraph,
1900 std::sync::OnceLock<Vec<NodeId>>,
1901 Arc<dyn crate::ranker::RuntimeSelector>,
1902 NodeId,
1903 );
1904
1905 /// Shared setup for the two `cached_env_*` tests below: a single-fork
1906 /// graph, a two-backend `OptimizedGraph`, a seeded `StorageCache`, a
1907 /// fresh `order_cache`, and a real (non-stub) `WinnerSelector`.
1908 /// Factored out purely to keep each test under Codacy's method-length
1909 /// bound — no behavior lives here that either test's own body needs to
1910 /// see inline.
1911 fn cached_env_test_fixture() -> CachedEnvTestFixture {
1912 use crate::pipelined::StorageCache;
1913 use crate::ranker::runtime_selector::WinnerSelector;
1914
1915 let mut table = KernelBindingTable::new();
1916 let (mut g, _prod, _fork, _tail, root) = build_single_fork_graph(&mut table);
1917 let opts = two_backend_opts();
1918 let optimized =
1919 optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
1920 assert_eq!(optimized.branch_count(&g), 1, "exactly one branch");
1921
1922 let graph = Arc::new(RwLock::new(g));
1923 let mut cache = StorageCache::new();
1924 cache.insert(
1925 NodeId(0), // the leaf Const build_single_fork_graph pushes first.
1926 Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
1927 1.0_f32, 2.0, 3.0, 4.0,
1928 ]))),
1929 );
1930 let order_cache: std::sync::OnceLock<Vec<NodeId>> = std::sync::OnceLock::new();
1931 let selector: Arc<dyn crate::ranker::RuntimeSelector> = Arc::new(WinnerSelector);
1932 (graph, cache, optimized, order_cache, selector, root)
1933 }
1934
1935 /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
1936 /// §5), answering the PM's review question directly: on a graph with a
1937 /// REAL `Op::Branch` and a REAL selector (so the executor's picking
1938 /// entry point resolves a genuine pick, not just "no branches to
1939 /// pick"), `realize_with_optimized_picking_cached_env` must route
1940 /// through `OrderSource::Streaming`, NEVER through `OrderSource::Cached`
1941 /// — proven here by checking `order_cache` stays EMPTY across two
1942 /// separate picking realizes, not merely by reading the routing code.
1943 /// This is the stronger property PR review asked for: the fix doesn't
1944 /// need a cache key that "covers the pick" because picked graphs never
1945 /// reach the cache in the first place — `realize_with_optimized_picking_env`'s
1946 /// OWN routing (`streaming_pick_for` returning `Some` whenever a
1947 /// selector is given over a branched graph) already excludes them, and
1948 /// this test is what proves that exclusion actually holds for the
1949 /// cached sibling too, not just the uncached original.
1950 ///
1951 /// `result`/`result2` tolerate `Error::TopologyChanged` as a passing
1952 /// outcome, not just `Ok`: `optimized.generation` is stamped once, from
1953 /// the process-wide `topology_generation()` counter, at `optimize_graph`
1954 /// time above — and that counter is shared by every test in this binary
1955 /// (`register_runtime_kernel`/`extend_global_bindings`'s own doc admits
1956 /// this; see `register_runtime_kernel_into`'s test-only escape hatch).
1957 /// A sibling test registering a runtime-fused kernel between here and
1958 /// either realize call bumps it, and `realize_inner`'s chunk-boundary
1959 /// check (pipelined.rs) deliberately does NOT retry at this layer —
1960 /// only `pipelined_bridge`'s wrapper does (by design, so a low-level
1961 /// `PipelinedExecutor` caller sees the typed error, not a silent stall).
1962 /// A real retry would need a fresh `optimize_graph` call, which would
1963 /// defeat this test's actual subject (whether the same `OptimizedGraph`
1964 /// and `order_cache` stay consistent across repeat calls), so instead
1965 /// of retrying we just don't fail on the one outcome this test was
1966 /// never about. The `order_cache`-emptiness assertions stay
1967 /// unconditional: the `Streaming` path never touches `order_cache`
1968 /// regardless of whether the realize that invoked it succeeded or hit
1969 /// this race.
1970 #[test]
1971 fn cached_env_never_caches_a_branched_graph_with_a_real_selector() {
1972 use crate::PipelinedExecutor;
1973 use fuel_ir::{Error, SymEnv};
1974
1975 let (graph, cache, optimized, order_cache, selector, root) = cached_env_test_fixture();
1976
1977 let result = PipelinedExecutor::realize_with_optimized_picking_cached_env(
1978 graph.clone(),
1979 root,
1980 cache.clone(),
1981 &optimized,
1982 &order_cache,
1983 Some(selector.clone()),
1984 None,
1985 SymEnv::default(),
1986 );
1987 assert!(
1988 result.is_ok() || matches!(result, Err(Error::TopologyChanged { .. })),
1989 "a picked realize over a branched graph must either succeed or hit the \
1990 (unrelated, expected-under-concurrency) TopologyChanged race: {:?}",
1991 result.err()
1992 );
1993 assert!(
1994 order_cache.get().is_none(),
1995 "a branched graph with a real selector pick must NEVER populate order_cache — \
1996 it must route through OrderSource::Streaming, not OrderSource::Cached",
1997 );
1998
1999 // A second call, same cache slot: still must not populate it.
2000 let result2 = PipelinedExecutor::realize_with_optimized_picking_cached_env(
2001 graph,
2002 root,
2003 cache,
2004 &optimized,
2005 &order_cache,
2006 Some(selector),
2007 None,
2008 SymEnv::default(),
2009 );
2010 assert!(
2011 result2.is_ok() || matches!(result2, Err(Error::TopologyChanged { .. })),
2012 "second picked realize must either succeed or hit the same expected-under- \
2013 concurrency TopologyChanged race: {:?}",
2014 result2.err()
2015 );
2016 assert!(
2017 order_cache.get().is_none(),
2018 "order_cache must still be empty after a second picked realize",
2019 );
2020 }
2021
2022 /// Deterministic sibling of the test above: forces the EXACT race
2023 /// `Error::TopologyChanged` tolerance was added for, instead of relying
2024 /// on another test in the binary to collide by chance. Proves two
2025 /// things the flaky-under-`-j4` observation alone couldn't: (1) that a
2026 /// stale `optimized.generation` is SUFFICIENT to reproduce the exact
2027 /// failure this test's sibling hit (confirming the root cause, not
2028 /// just a plausible story), and (2) that `order_cache` stays empty
2029 /// even on the `Err` branch (the property this test file is actually
2030 /// about, independent of the race).
2031 ///
2032 /// Deliberately does NOT call the real, process-wide
2033 /// `bump_topology_generation()` to force this — that would inflict the
2034 /// exact `-j4` cross-test hazard this test documents onto every OTHER
2035 /// concurrently-running test in the binary that assumes a stable
2036 /// generation (an earlier draft of this test did exactly that, and
2037 /// broke `realize_with_optimized_picking_cached_env_matches_arm0_cold_and_warm`
2038 /// under `-j4`). `OptimizedGraph::generation` is `pub`, so mutating
2039 /// this test's own LOCAL copy to a value that can't match the live
2040 /// counter reproduces the identical code path with zero blast radius.
2041 #[test]
2042 fn cached_env_tolerates_a_concurrent_topology_generation_bump() {
2043 use crate::PipelinedExecutor;
2044 use fuel_ir::{Error, SymEnv};
2045
2046 let (graph, cache, mut optimized, order_cache, selector, root) = cached_env_test_fixture();
2047
2048 // Simulate a sibling test's legitimate `register_runtime_kernel`/
2049 // `extend_global_bindings` call landing between `optimize_graph`
2050 // (which stamped `optimized.generation` above) and this realize —
2051 // exactly the collision `cached_env_never_caches_a_branched_graph_with_a_real_selector`
2052 // hit under `-j4` — by staling THIS test's own copy of the stamp,
2053 // not the shared live counter every other test also reads.
2054 optimized.generation = optimized.generation.wrapping_add(1);
2055
2056 let result = PipelinedExecutor::realize_with_optimized_picking_cached_env(
2057 graph,
2058 root,
2059 cache,
2060 &optimized,
2061 &order_cache,
2062 Some(selector),
2063 None,
2064 SymEnv::default(),
2065 );
2066 assert!(
2067 matches!(result, Err(Error::TopologyChanged { .. })),
2068 "a forced generation bump before realize must surface as TopologyChanged, \
2069 not silently succeed or fail some other way: {:?}",
2070 result
2071 );
2072 assert!(
2073 order_cache.get().is_none(),
2074 "order_cache must stay empty even when the realize that would have \
2075 populated it (if it were ever going to) failed with TopologyChanged",
2076 );
2077 }
2078
2079 /// (d) No `DEFAULT_MAX_N` truncation: the fork records the winner +
2080 /// a runner-up without a fixed top-N cap stranding placements. Both
2081 /// arms survive; the per-device frontier — not a fixed N — bounds
2082 /// the arms.
2083 #[test]
2084 fn no_default_max_n_truncation() {
2085 let mut table = KernelBindingTable::new();
2086 let (mut g, _prod, fork, _tail, root) = build_single_fork_graph(&mut table);
2087 let opts = two_backend_opts();
2088
2089 let optimized =
2090 optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
2091 assert_eq!(optimized.branch_count(&g), 1);
2092 let branch_id = (0..g.len())
2093 .map(NodeId)
2094 .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
2095 .expect("a Branch node exists");
2096 // Two distinct placements ⇒ two arms survive; the runner-up was
2097 // not dropped by any top-N cap.
2098 assert_eq!(g.node(branch_id).inputs.len(), 2);
2099 assert_eq!(g.node(branch_id).inputs[0], fork);
2100 }
2101
2102 /// THE EQUIVALENCE GATE (born-red until `optimize_graph` exists and
2103 /// its lowered order matches `compile_plan`).
2104 ///
2105 /// On representative no-competing-route graphs, assert:
2106 /// (a) `optimize_graph` leaves ZERO `Op::Branch` nodes, and
2107 /// (b) the concatenated `extract_runs`/`lower_run` dispatch order
2108 /// EQUALS today's `compile_plan(...).order` exactly (same
2109 /// NodeIds, same order).
2110 #[test]
2111 fn equivalence_gate_branchless_order_matches_compile_plan() {
2112 for build in [
2113 build_straight_line_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2114 build_branchless_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2115 ] {
2116 let mut table = KernelBindingTable::new();
2117 let (mut g, root) = build(&mut table);
2118 let opts = cpu_opts();
2119
2120 // Today's path: the exact order the executor walks.
2121 let order = execution_plan(&g, &[root]);
2122 let plan = compile_plan(&g, &order, &table, &opts)
2123 .expect("today's compile_plan succeeds on a placeable graph");
2124
2125 // New path.
2126 let optimized = optimize_graph(&mut g, &[root], &table, &opts)
2127 .expect("optimize_graph succeeds on the same graph");
2128
2129 // (a) zero competing routes => zero Branch nodes.
2130 assert_eq!(
2131 optimized.branch_count(&g),
2132 0,
2133 "a no-competing-route graph optimizes to zero Op::Branch nodes",
2134 );
2135
2136 // (b) EXACT order equality against compile_plan(...).order.
2137 let lowered = optimized.dispatch_order(&g);
2138 assert_eq!(
2139 lowered, plan.order,
2140 "the extract_runs/lower_run dispatch order must equal \
2141 compile_plan(...).order exactly (same NodeIds, same order)",
2142 );
2143 // And it covers every reachable node — the executor walks
2144 // the whole graph, runs partition it with no gaps/dupes.
2145 assert_eq!(
2146 lowered.len(),
2147 order.len(),
2148 "the lowered order covers every node compile_plan ordered",
2149 );
2150 }
2151 }
2152
2153 /// `optimize_graph` on a branchless graph is idempotent and adds no
2154 /// nodes: the node count is unchanged across repeated calls, the
2155 /// branch count stays zero, and the lowered order is stable.
2156 #[test]
2157 fn optimize_graph_branchless_is_idempotent_and_adds_no_nodes() {
2158 let mut table = KernelBindingTable::new();
2159 let (mut g, root) = build_branchless_graph(&mut table);
2160 let opts = cpu_opts();
2161
2162 let nodes_before = g.len();
2163 let first =
2164 optimize_graph(&mut g, &[root], &table, &opts).expect("first optimize succeeds");
2165 let order_first = first.dispatch_order(&g);
2166 let nodes_after_first = g.len();
2167
2168 let second =
2169 optimize_graph(&mut g, &[root], &table, &opts).expect("second optimize succeeds");
2170 let order_second = second.dispatch_order(&g);
2171 let nodes_after_second = g.len();
2172
2173 assert_eq!(
2174 nodes_before, nodes_after_first,
2175 "optimize_graph adds no nodes (A3a is single-route-only)",
2176 );
2177 assert_eq!(
2178 nodes_after_first, nodes_after_second,
2179 "a second optimize_graph adds no further nodes — idempotent",
2180 );
2181 assert_eq!(first.branch_count(&g), 0, "no branches after first");
2182 assert_eq!(second.branch_count(&g), 0, "no branches after second");
2183 assert_eq!(
2184 order_first, order_second,
2185 "the lowered dispatch order is stable across repeated optimize",
2186 );
2187 }
2188
2189 /// Identity proof for `docs/design/incremental-consumer-index.md` §5's
2190 /// `order_for` fix track: that fix proposes memoizing `dispatch_order`'s
2191 /// output WHOLESALE once per plan-once session, instead of recomputing
2192 /// it (via `extract_runs_multi` + `non_chosen_arm_nodes`, measured
2193 /// ~56ms/step, the single largest named sub-cost in a live decode step)
2194 /// on every `realize_inner` call. That's only valid if calling
2195 /// `dispatch_order` repeatedly on the SAME `OptimizedGraph` view with NO
2196 /// intervening graph mutation — exactly the plan-once decode shape,
2197 /// where only leaf values are rebound between tokens, never the graph's
2198 /// structure — yields a byte-identical `Vec<NodeId>` every time. Proven
2199 /// here, not assumed: five repeated calls, two structurally different
2200 /// branchless graphs (a fan-in boundary and a plain chain), zero
2201 /// mutation between calls (deliberately — this is NOT the existing
2202 /// `optimize_graph_branchless_is_idempotent_and_adds_no_nodes` test
2203 /// above, which re-runs `optimize_graph` itself between its two
2204 /// `dispatch_order` calls; this one proves `dispatch_order` is pure on
2205 /// its own, independent of re-optimizing).
2206 #[test]
2207 fn dispatch_order_is_stable_across_repeated_calls_with_no_mutation() {
2208 for build in [
2209 build_branchless_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2210 build_straight_line_graph,
2211 ] {
2212 let mut table = KernelBindingTable::new();
2213 let (mut g, root) = build(&mut table);
2214 let opts = cpu_opts();
2215 let optimized = optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph");
2216
2217 let orders: Vec<Vec<NodeId>> = (0..5).map(|_| optimized.dispatch_order(&g)).collect();
2218 for (i, order) in orders.iter().enumerate().skip(1) {
2219 assert_eq!(
2220 &orders[0], order,
2221 "dispatch_order call {i} diverged from call 0 with no intervening \
2222 mutation — the order_for memoization fix would be UNSAFE if this failed",
2223 );
2224 }
2225 }
2226 }
2227
2228 /// Build-time validation: optimize_graph fails fast (Result, never
2229 /// panic) when a kernel-bearing node has no registered binding —
2230 /// reusing compile_plan's missing-binding diagnostic.
2231 #[test]
2232 fn optimize_graph_fails_fast_on_missing_binding() {
2233 let table = KernelBindingTable::new(); // empty — no bindings.
2234 let mut g = Graph::new();
2235 let a = f32_node(&mut g, Op::Const, vec![]);
2236 let relu = f32_node(&mut g, Op::Relu, vec![a]);
2237 let opts = cpu_opts();
2238
2239 let err = optimize_graph(&mut g, &[relu], &table, &opts)
2240 .map(|_| ())
2241 .unwrap_err();
2242 match err {
2243 fuel_ir::Error::NoBackendForOp { op, .. } => {
2244 assert_eq!(op, OpKind::ReluElementwise);
2245 }
2246 other => panic!("expected NoBackendForOp, got {other:?}"),
2247 }
2248 }
2249
2250 // ===== Phase B PR-B3: the lock-step pathfinder/ranker/optimizer
2251 // driver. =====
2252
2253 use crate::driver::{
2254 FrontierConvergenceOptimizer, OptimizationContext, Optimizer, PassRegistry, Pathfinder,
2255 PlacementForkPathfinder,
2256 };
2257 use std::collections::HashSet;
2258
2259 /// Snapshot of a graph's `Op::Branch` decision points, keyed by
2260 /// arena order: `(branch_id, reconverge_at, arm NodeIds)`. Two
2261 /// optimization paths that produce the same snapshot produced the
2262 /// same multi-path graph (behavior-preservation).
2263 fn branch_snapshot(g: &Graph) -> Vec<(NodeId, NodeId, Vec<NodeId>)> {
2264 (0..g.len())
2265 .map(NodeId)
2266 .filter_map(|id| match g.node(id).op {
2267 Op::Branch { reconverge_at } => {
2268 Some((id, reconverge_at, g.node(id).inputs.clone()))
2269 }
2270 _ => None,
2271 })
2272 .collect()
2273 }
2274
2275 /// THE LOAD-BEARING BEHAVIOR-PRESERVATION GATE (born-red until
2276 /// `optimize_graph` routes through the lock-step driver).
2277 ///
2278 /// On a representative multi-placement graph, the driver
2279 /// (`PassRegistry::default_passes().run_lockstep`) produces the
2280 /// **identical** multi-path graph as the old hardcoded sequence
2281 /// (pathfinder then optimizer, in that order): same branch count,
2282 /// same arm-0 winner, same arms, same reconverge points, and the
2283 /// same arm-0 dispatch order. B3 is a structural refactor — the
2284 /// optimized result must not change.
2285 #[test]
2286 fn driver_matches_legacy_sequence() {
2287 // (A) The reference: drive the registered passes BY HAND in the
2288 // legacy order (propose, then prune) onto a freshly compiled
2289 // plan — exactly what the pre-B3 hardcoded sequence did.
2290 let mut ref_table = KernelBindingTable::new();
2291 let (mut ref_g, _prod, ref_fork, _tail, ref_root) = build_single_fork_graph(&mut ref_table);
2292 let opts = two_backend_opts();
2293 let ref_order = execution_plan(&ref_g, &[ref_root]);
2294 let ref_plan = compile_plan(&ref_g, &ref_order, &ref_table, &opts)
2295 .expect("reference compile_plan succeeds");
2296 {
2297 let guard: HashSet<NodeId> = HashSet::new();
2298 let ctx = OptimizationContext {
2299 order: &ref_order,
2300 plan: &ref_plan,
2301 cycle_guard: &guard,
2302 bindings: &ref_table,
2303 };
2304 // Legacy order: the pathfinder ADDs, then the optimizer
2305 // prunes — the same two operations the hardcoded sequence ran.
2306 PlacementForkPathfinder
2307 .propose(&mut ref_g, &ctx)
2308 .expect("pathfinder proposes");
2309 FrontierConvergenceOptimizer
2310 .prune(&mut ref_g, &ctx)
2311 .expect("optimizer prunes");
2312 }
2313 let ref_snapshot = branch_snapshot(&ref_g);
2314 let ref_dispatch = fuel_graph::lower_runs_arm0(&ref_g, &[ref_root]);
2315
2316 // (B) The driver path: optimize_graph routes through
2317 // PassRegistry::default_passes().run_lockstep.
2318 let mut table = KernelBindingTable::new();
2319 let (mut g, _p, fork, _t, root) = build_single_fork_graph(&mut table);
2320 let optimized =
2321 optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
2322 let got_snapshot = branch_snapshot(&g);
2323 let got_dispatch = optimized.dispatch_order(&g);
2324
2325 // Identical multi-path graph: same branches, arms, reconverge.
2326 assert_eq!(
2327 got_snapshot, ref_snapshot,
2328 "driver produces the identical Op::Branch structure as the legacy \
2329 pathfinder→optimizer sequence",
2330 );
2331 assert_eq!(
2332 got_snapshot.len(),
2333 1,
2334 "the representative multi-placement graph produces exactly one branch",
2335 );
2336 assert_eq!(
2337 got_snapshot[0].2[0], fork,
2338 "arm-0 is the DP winner (the route realize uses)",
2339 );
2340 // Identical dispatch order (arm-0 single-route lowering).
2341 assert_eq!(
2342 got_dispatch, ref_dispatch,
2343 "driver yields the identical arm-0 dispatch order as the legacy sequence",
2344 );
2345 let _ = ref_fork;
2346 }
2347
2348 /// A no-op registry (no registered pathfinders) leaves a branchless
2349 /// graph unchanged: no nodes added, zero branches, identical
2350 /// dispatch order. Proves the driver itself introduces no structure.
2351 #[test]
2352 fn noop_registry_leaves_branchless_graph_unchanged() {
2353 let mut table = KernelBindingTable::new();
2354 let (mut g, root) = build_branchless_graph(&mut table);
2355 let opts = cpu_opts();
2356
2357 let order = execution_plan(&g, &[root]);
2358 let plan = compile_plan(&g, &order, &table, &opts).expect("compile_plan succeeds");
2359
2360 let dispatch_before = fuel_graph::lower_runs_arm0(&g, &[root]);
2361 let nodes_before = g.len();
2362
2363 let registry = PassRegistry::new(); // empty — no passes.
2364 assert_eq!(registry.pathfinder_count(), 0);
2365 assert_eq!(registry.optimizer_count(), 0);
2366
2367 let guard: HashSet<NodeId> = HashSet::new();
2368 let ctx = OptimizationContext {
2369 order: &order,
2370 plan: &plan,
2371 cycle_guard: &guard,
2372 bindings: &table,
2373 };
2374 registry
2375 .run_lockstep(&mut g, &ctx)
2376 .expect("empty registry runs cleanly");
2377
2378 assert_eq!(g.len(), nodes_before, "no-op registry adds no nodes");
2379 let branches = (0..g.len())
2380 .map(NodeId)
2381 .filter(|&id| matches!(g.node(id).op, Op::Branch { .. }))
2382 .count();
2383 assert_eq!(branches, 0, "no-op registry adds no branches");
2384 let dispatch_after = fuel_graph::lower_runs_arm0(&g, &[root]);
2385 assert_eq!(
2386 dispatch_before, dispatch_after,
2387 "no-op registry leaves the dispatch order unchanged",
2388 );
2389 }
2390
2391 /// Lock-step ordering: a pathfinder ADDs before its dependent
2392 /// optimizer PRUNEs. We register a recording pathfinder and a
2393 /// recording optimizer that each stamp a shared log when invoked;
2394 /// `run_lockstep` must invoke the pathfinder strictly before the
2395 /// optimizer (prune-as-you-go, never optimizer-first).
2396 #[test]
2397 fn lockstep_runs_pathfinder_before_dependent_optimizer() {
2398 use std::sync::{Arc, Mutex};
2399
2400 #[derive(Clone)]
2401 struct RecordPathfinder(Arc<Mutex<Vec<&'static str>>>);
2402 impl Pathfinder for RecordPathfinder {
2403 fn name(&self) -> &'static str {
2404 "RecordPathfinder"
2405 }
2406 fn propose(
2407 &self,
2408 _g: &mut Graph,
2409 _ctx: &OptimizationContext<'_>,
2410 ) -> fuel_ir::Result<()> {
2411 self.0.lock().unwrap().push("propose");
2412 Ok(())
2413 }
2414 }
2415 #[derive(Clone)]
2416 struct RecordOptimizer(Arc<Mutex<Vec<&'static str>>>);
2417 impl Optimizer for RecordOptimizer {
2418 fn name(&self) -> &'static str {
2419 "RecordOptimizer"
2420 }
2421 fn prune(&self, _g: &mut Graph, _ctx: &OptimizationContext<'_>) -> fuel_ir::Result<()> {
2422 self.0.lock().unwrap().push("prune");
2423 Ok(())
2424 }
2425 }
2426
2427 let log = Arc::new(Mutex::new(Vec::new()));
2428 let registry = PassRegistry::new()
2429 .with_pathfinder(Box::new(RecordPathfinder(log.clone())))
2430 .with_optimizer(Box::new(RecordOptimizer(log.clone())));
2431
2432 let mut g = Graph::new();
2433 let _a = f32_node(&mut g, Op::Const, vec![]);
2434 let plan = ExecutionPlan::empty();
2435 let order: Vec<NodeId> = Vec::new();
2436 let guard: HashSet<NodeId> = HashSet::new();
2437 let table = KernelBindingTable::new();
2438 let ctx = OptimizationContext {
2439 order: &order,
2440 plan: &plan,
2441 cycle_guard: &guard,
2442 bindings: &table,
2443 };
2444 registry.run_lockstep(&mut g, &ctx).expect("drive runs");
2445
2446 let seq = log.lock().unwrap().clone();
2447 assert_eq!(
2448 seq,
2449 vec!["propose", "prune"],
2450 "lock-step drive runs the pathfinder ADD strictly before its \
2451 dependent optimizer PRUNE (prune-as-you-go)",
2452 );
2453 }
2454
2455 /// **Where does `PagedAttn`'s DECOMPOSED form land on CUDA?** — the
2456 /// measurement that gates whether offering a decomposed arm is worth
2457 /// building, and what to ask Baracuda for.
2458 ///
2459 /// Established already: the FUSED `Op::PagedAttn` node executes on the CPU
2460 /// under CUDA decode (`paged_decode_node_placement_report_cuda`), because
2461 /// no CUDA backend advertises it — so "runs on host" is not a decision the
2462 /// planner made, it is the only move it had. `decompose` exists and is
2463 /// closed-basis, but the planner is never offered it.
2464 ///
2465 /// This asks the question that decides the next build, and it is a
2466 /// GPU-vs-GPU question that the 186× host-ward figure cannot answer —
2467 /// **any** on-device path removes that round-trip equally, so its magnitude
2468 /// says something must be built without saying what:
2469 ///
2470 /// - **every recipe node CUDA-placed** → the round-trip is removable with
2471 /// NO kernel work at all; the ask to Baracuda may be nothing.
2472 /// - **some primitive falls back to host** → *that primitive* is the ask,
2473 /// far smaller and better-specified than "paged attention".
2474 ///
2475 /// A grep cannot answer this. I tried: it reported `Permute` in zero
2476 /// CUDA-backend files while the measured placement dump showed
2477 /// `Permute Cuda×6` — it undercounts ops served by generic dispatch. Only
2478 /// the planner's own resolved map settles it.
2479 ///
2480 /// REPORTS rather than asserting a verdict, for the same reason as the
2481 /// fused-node report: pre-committing to an answer is the error being
2482 /// corrected. What it DOES assert is that the instrument ran
2483 /// (`has_placements()`) and that decomposition actually happened (the root
2484 /// moved off the fused node) — an all-`None` dump would read as "nothing
2485 /// is on CUDA", a wrong answer wearing a null answer's clothes.
2486 #[test]
2487 #[ignore = "live GPU (CUDA); run via scripts/gpu-run.ps1"]
2488 #[cfg(feature = "cuda")]
2489 fn paged_attn_decomposed_arm_placement_report_cuda() {
2490 use fuel_graph::registry::{FusedOpParams, FusedOps};
2491 use std::collections::BTreeMap;
2492
2493 const B: usize = 1;
2494 const HQ: usize = 4;
2495 const HKV: usize = 4;
2496 const SQ: usize = 1;
2497 const D: usize = 4;
2498 const NUM_BLOCKS: usize = 32;
2499 const BLOCK_SIZE: usize = 4;
2500 const MAX_BLK: usize = 8;
2501
2502 let mut g = Graph::new();
2503 let leaf = |g: &mut Graph, dims: &[usize], dtype: DType| {
2504 g.push(Node {
2505 op: Op::Const,
2506 inputs: vec![],
2507 shape: Shape::from_dims(dims),
2508 dtype,
2509 })
2510 };
2511 let q = leaf(&mut g, &[B, HQ, SQ, D], DType::F32);
2512 let kc = leaf(&mut g, &[NUM_BLOCKS, BLOCK_SIZE, HKV, D], DType::F32);
2513 let vc = leaf(&mut g, &[NUM_BLOCKS, BLOCK_SIZE, HKV, D], DType::F32);
2514 let bt = leaf(&mut g, &[B, MAX_BLK], DType::U32);
2515 let cl = leaf(&mut g, &[B], DType::U32);
2516
2517 let params = FusedOpParams::PagedAttn {
2518 softmax_scale: 1.0 / (D as f32).sqrt(),
2519 block_size: BLOCK_SIZE,
2520 softcap: None,
2521 };
2522 let fused = g.push(Node {
2523 op: Op::Fused(FusedOps::PAGED_ATTN, params.clone()),
2524 inputs: vec![q, kc, vc, bt, cl],
2525 shape: Shape::from_dims(&[B, HQ, SQ, D]),
2526 dtype: DType::F32,
2527 });
2528
2529 // Lower the fused node to its primitive recipe — the arm the planner is
2530 // never currently offered.
2531 let root = fuel_graph::registry::paged_attn::decompose(&mut g, fused, ¶ms);
2532 assert_ne!(
2533 root, fused,
2534 "PRECONDITION: decompose must actually lower. A self-return is the \
2535 G2 fixpoint signal (malformed node / declined recipe), and every \
2536 placement below would then describe the FUSED node, silently \
2537 answering a different question than the one asked.",
2538 );
2539
2540 // THE PRODUCTION TABLE, not a hand-assembled one. An earlier version of
2541 // this test built the table with `register_cuda_kernels` alone and got
2542 // "no backend supports index_select" — which was an artifact of the
2543 // HARNESS, not a fact about Fuel: that function makes ~5 registrations
2544 // and the bulk of CUDA lives in `register_baracuda_cuda_kernels`, which
2545 // the real path (`register_optional_backends`) also calls, on top of
2546 // `register_cpu_kernels` and a cost fill. Reproducing that assembly by
2547 // hand is precisely the kind of thing that silently drifts, so ask for
2548 // the table the realize path actually uses.
2549 let table = crate::dispatch::global_bindings();
2550
2551 // POSITIVE CONTROL — the instrument must be able to see a CUDA binding
2552 // at all. Without this, an under-populated table reports "no CUDA
2553 // support" for EVERY op, which reads exactly like a real finding: it is
2554 // specific, it names a primitive, and it is completely wrong. That is
2555 // how the first run of this test nearly shipped a false Baracuda ask.
2556 // MatMul is the control because the fuel-core placement report measured
2557 // `MatMul Cuda×15` on a real decode graph — an independently observed
2558 // fact this table must reproduce.
2559 assert!(
2560 table
2561 .lookup(
2562 OpKind::MatMul,
2563 &[DType::F32, DType::F32, DType::F32],
2564 BackendId::Cuda
2565 )
2566 .is_ok(),
2567 "INSTRUMENT BROKEN: the binding table has no CUDA MatMul, so every \
2568 'no CUDA support' conclusion below would be an artifact of the \
2569 harness. Fix the table before reading any verdict from this test.",
2570 );
2571
2572 // ---- THE COMPLETE MISSING-BINDING SET, asked directly ----
2573 //
2574 // `optimize_graph` fails at the FIRST unplaceable node, so driving this
2575 // off its error yields one op per run — a trickle, and each run costs a
2576 // CUDA rebuild. Worse, it conflates two different things: "CUDA has no
2577 // kernel for this op" and "the planner could not place it under THIS
2578 // pin". Asking the binding table per node separates them and returns the
2579 // whole set at once.
2580 let mut missing_cuda: Vec<String> = Vec::new();
2581 let mut present_cuda: Vec<String> = Vec::new();
2582 for i in 0..g.len() {
2583 let id = NodeId(i);
2584 let node = g.node(id);
2585 let Some(kind) = crate::pipelined::op_to_op_kind(&node.op) else {
2586 continue; // Const / view / fused — not a binding-table lookup
2587 };
2588 let mut dtypes: Vec<DType> = node.inputs.iter().map(|&i| g.node(i).dtype).collect();
2589 dtypes.push(node.dtype); // binding key is [inputs.., output]
2590 let sig = format!(
2591 "{kind:?}{:?}",
2592 dtypes.iter().map(|d| format!("{d:?}")).collect::<Vec<_>>()
2593 );
2594 if table.lookup(kind, &dtypes, BackendId::Cuda).is_ok() {
2595 present_cuda.push(sig);
2596 } else {
2597 missing_cuda.push(sig);
2598 }
2599 }
2600 missing_cuda.sort();
2601 missing_cuda.dedup();
2602 present_cuda.sort();
2603 present_cuda.dedup();
2604
2605 println!("\n=== PagedAttn recipe: CUDA binding coverage (asked per node) ===");
2606 println!("PRESENT on CUDA ({}):", present_cuda.len());
2607 for s in &present_cuda {
2608 println!(" {s}");
2609 }
2610 println!("MISSING on CUDA ({}):", missing_cuda.len());
2611 for s in &missing_cuda {
2612 println!(" {s}");
2613 }
2614 // A run where NOTHING resolves would mean the table is empty again — the
2615 // MatMul control above already guards that, but state the invariant that
2616 // makes the "missing" list meaningful rather than vacuous.
2617 assert!(
2618 !present_cuda.is_empty(),
2619 "INSTRUMENT BROKEN: not one recipe node resolved on CUDA, so the \
2620 MISSING list is a property of the lookup, not of the backend",
2621 );
2622 println!(
2623 "\n>>> THE ASK: the {} signature(s) above are what CUDA lacks for the \
2624 §1 dense recipe. Each is a small, named primitive — not \"paged \
2625 attention\".\n",
2626 missing_cuda.len()
2627 );
2628
2629 let opts = PlanOptions::new().with_pinned_device(DeviceLocation::Cuda { gpu_id: 0 });
2630 let optimized = match optimize_graph(&mut g, &[root], &table, &opts) {
2631 Ok(o) => o,
2632 Err(e) => {
2633 println!("\n=== DECOMPOSED ARM DOES NOT PLAN ON CUDA ===");
2634 println!("optimize_graph error: {e:?}");
2635 println!("That is itself the answer: some recipe primitive has no CUDA");
2636 println!("binding, and the error names it. THAT is the Baracuda ask.");
2637 return;
2638 }
2639 };
2640
2641 assert!(
2642 optimized.has_placements(),
2643 "placement NOT COMPUTED — every placement_of would be None and the \
2644 report below would describe the missing instrument, not the graph",
2645 );
2646
2647 let mut by_op: BTreeMap<String, BTreeMap<String, usize>> = BTreeMap::new();
2648 let mut host_ops: Vec<String> = Vec::new();
2649 for i in 0..g.len() {
2650 let id = NodeId(i);
2651 let op_name = match &g.node(id).op {
2652 Op::Fused(fid, _) => format!("Fused({fid:?})"),
2653 other => format!("{other:?}")
2654 .split(' ')
2655 .next()
2656 .unwrap_or("?")
2657 .to_string(),
2658 };
2659 let place = match optimized.placement_of(id) {
2660 Some(d) => format!("{d:?}"),
2661 None => "None".to_string(),
2662 };
2663 if place.starts_with("Cpu") {
2664 host_ops.push(op_name.clone());
2665 }
2666 *by_op.entry(op_name).or_default().entry(place).or_insert(0) += 1;
2667 }
2668
2669 println!("\n=== PagedAttn DECOMPOSED arm: node placement (CUDA-pinned) ===");
2670 println!(
2671 "total nodes: {} (fused node #{} lowered to root #{})",
2672 g.len(),
2673 fused.0,
2674 root.0
2675 );
2676 for (op, places) in &by_op {
2677 let rendered: Vec<String> = places.iter().map(|(d, n)| format!("{d}×{n}")).collect();
2678 println!(" {op:<40} {}", rendered.join(" "));
2679 }
2680
2681 println!("\n--- VERDICT ---");
2682 if host_ops.is_empty() {
2683 println!(
2684 "EVERY recipe node is off-host. The decomposed paged attention runs \
2685 ON DEVICE, so the 186x round-trip is removable by OFFERING THIS ARM \
2686 — no Baracuda kernel required to eliminate it. A kernel would then \
2687 be a throughput question (the recipe materialises padded capacity, \
2688 not live context_len), not a round-trip one."
2689 );
2690 } else {
2691 host_ops.sort();
2692 host_ops.dedup();
2693 println!(
2694 "HOST-PLACED recipe primitives: {host_ops:?}\n\
2695 These are the ask — each is a far smaller and better-specified \
2696 request than \"paged attention\", and until they exist on device \
2697 the decomposed arm cannot win."
2698 );
2699 }
2700 println!("--- END VERDICT ---\n");
2701 }
2702}