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 mut order = fuel_graph::opt::execution_plan(graph, roots);
300
301 // (1a) GAP-380 (a1): lower a fused op with NO kernel on the pinned device to its primitive recipe
302 // BEFORE placement, so the recipe's nodes are placed on the device instead of the whole fused
303 // op landing on the host (a round trip of its device-resident operands every call). Runs first
304 // because it changes what the planner enumerates; the order is re-derived if it rewrote.
305 if lower_fused_unbound_on_pinned_device(graph, roots, opts, &|id, backend| {
306 crate::fused::default_kernel_registry()
307 .impls_for(id)
308 .iter()
309 .any(|(b, _)| *b == backend)
310 }) > 0
311 {
312 order = fuel_graph::opt::execution_plan(graph, roots);
313 }
314
315 // (2) Reuse the placement/cost/validation machinery. The plan is a
316 // transient, optimizer-INTERNAL by-product — we drive `compile_plan`
317 // so the same fail-fast diagnostics (missing binding, no device
318 // context) fire at optimize time, and so the placement DP / cost
319 // composer run unchanged. The plan is the working accumulator the
320 // stamp / residency / layout-fixup passes + the lock-step rankers
321 // read below; it is NOT returned or threaded (Step D — the graph
322 // stamps + arms are the only durable output).
323 // (2a) Dtype-reconciliation fixup — insert promoting `Op::Cast`s so a node
324 // whose per-operand key no compiled-in backend serves natively (e.g. a
325 // mixed-precision `[F32, BF16, F32]` matmul) becomes servable, instead of
326 // dead-ending in `compile_plan` below. Runs BEFORE the plan because it
327 // changes what's enumerable; if it rewrites, re-derive the execution
328 // order over the mutated graph. The layout/residency fixups are its
329 // post-plan siblings.
330 let order = if insert_dtype_fixups(graph, roots, bindings_table, opts) {
331 fuel_graph::opt::execution_plan(graph, roots)
332 } else {
333 order
334 };
335
336 let plan = compile_plan(graph, &order, bindings_table, opts)?;
337 let generation = plan.generation;
338
339 // (3) PR-B3: the lock-step pass driver. The pre-B3 hardcoded
340 // `seed_placement_fork_branches(...)` call is replaced by a
341 // registry of pathfinders + optimizers run lock-step
342 // (prune-as-you-go): for each registered pathfinder, ADD its
343 // candidate paths, then immediately run every registered
344 // optimizer to MERGE/DISCARD over the region just touched. The
345 // shipped configuration ([`PassRegistry::default_passes`]) is the
346 // PR-A4 `PlacementForkPathfinder` (the deliberate-fork seed) +
347 // the `FrontierConvergenceOptimizer` (duplicate-path convergence
348 // + the never-strand / no-active-cycle invariant guards) — which
349 // is exactly the pre-B3 sequence, re-expressed. A CPU-only build
350 // has one placement per node ⇒ the pathfinder proposes zero
351 // branches ⇒ today's single-route graph (unchanged).
352 //
353 // The *ranker* + the PR-B2 per-device Pareto frontier are applied
354 // per kernel-bearing node *inside* `compile_plan` (the MEASURE +
355 // per-node PRUNE), and the ranked, frontier-pruned result is the
356 // `plan` the driver reads via `OptimizationContext::plan`. Batch
357 // optimize has no executing region, so the cycle guard is empty.
358 let cycle_guard: HashSet<NodeId> = HashSet::new();
359 let ctx = OptimizationContext {
360 order: &order,
361 plan: &plan,
362 cycle_guard: &cycle_guard,
363 bindings: bindings_table,
364 };
365 passes.run_lockstep(graph, &ctx)?;
366
367 // "Plan IS the graph": commit the placement decision INTO the graph's
368 // `target_backend` side-table here, so a fully-optimized graph carries
369 // its own backend stamps and downstream consumers read the graph, not a
370 // threaded plan. Guarded on a pinned device — the production realize
371 // path always sets one (`PlanOptions::with_pinned_device`); bare-graph
372 // test callers that don't are unaffected. (Cleanup Step A: this is
373 // idempotent with the bridge's transitional `stamp_plan_backends`, which
374 // re-stamps the identical result; Step A2 removes the bridge copy.)
375 // Stays `None` when the residency pass below is skipped (no pinned device),
376 // so a caller can tell "not computed" from "no placement" — see
377 // `OptimizedGraph::has_placements`.
378 let mut resolved_placements: Option<HashMap<NodeId, DeviceLocation>> = None;
379 let mut eviction: Option<crate::residency::EvictionOutcome> = None;
380 if let Some(pinned) = opts.pinned_device {
381 stamp_plan_backends(graph, roots, &plan, pinned);
382 // Every node stamped for a backend must have an executor arm there (typed plan-time error
383 // rather than an executor failure mid-run).
384 crate::pipelined::check_direct_arms_wired(graph, roots)?;
385 // Optimize-time kernel-variant bake: resolve **same-device**
386 // kernel-variant branches (a decomposed region vs. a fused kernel on
387 // the SAME device — e.g. the CUDA flash decode arm) to their cost
388 // winner and COLLAPSE them, so the winning variant is selectable
389 // without a runtime pick (04-optimization: kernel-variant choice is
390 // "largely baked at optimize time"). Runs AFTER `stamp_plan_backends`
391 // (the arms now carry `target_backend`, which the same-device gate
392 // reads) and BEFORE `insert_residency_copies` (so the residency pass
393 // stitches inbound copies only for the surviving winner arm, not a
394 // pruned one). A **placement** branch (arms on ≥2 devices) is left
395 // LIVE for the runtime route picker; a graph with no same-device
396 // variant branch — every CPU/Vulkan build today, since no CUDA flash
397 // arm is offered there — is a strict no-op. Ties / unknown costs /
398 // capability-missing default to arm 0 (the decomposed oracle).
399 // The cost provider consults the Judge's MEASURED latency (Layer-2)
400 // FIRST per arm node, falling back to the Layer-1 composite where the
401 // Judge has no cell (the hybrid sum). With `opts.judge == None` this is
402 // byte-identical to the Layer-1-only provider, so the no-Judge path is
403 // unchanged. The same oracle `cost.rs`/`plan.rs` read is threaded here.
404 let judge = opts.judge;
405 crate::variant_bake::bake_variant_branches(graph, roots, &|g, branch, arm, interior| {
406 let backend = g.target_backend(g.node(branch).inputs.first().copied()?)?;
407 crate::variant_bake::decode_arm_composite_ns_judged(
408 g, branch, arm, interior, backend, judge,
409 )
410 });
411 // Cleanup Step B (residency): the optimizer-side cross-device copy pass
412 // (was the bridge's `insert_resident_input_copies`). Runs AFTER stamping
413 // (it reads `target_backend`) and BEFORE layout-fixup, preserving the
414 // prior residency→layout order. Cache residency (where persistent /
415 // const inputs already live) arrives via the `opts.input_residency`
416 // provider the realize path already threads in — the optimizer reads
417 // that fact, it does not touch realize-time storage.
418 // Capture the resolved placement map on the way past — it is the pass's
419 // own input, and surfacing it is what makes `OptimizedGraph::placement_of`
420 // an observation rather than an inference.
421 let placements = insert_residency_copies(graph, roots, &plan, pinned, opts.input_residency);
422 // ROADMAP row 67 (I1): with a device byte budget, evict + reload around the
423 // best candidates while the analysed peak exceeds it. Runs after the copy pass
424 // (it reads the resolved placements) and before layout fixups. No budget = no-op.
425 if let Some(budget) = opts.device_budget_bytes {
426 let mut outcome = crate::residency::insert_residency_evictions_in(
427 graph,
428 roots,
429 pinned,
430 budget,
431 RESIDENCY_EVICTION_MAX_ROUNDS,
432 |id| placements.get(&id).copied(),
433 )?;
434 outcome.budget_source = opts.device_budget_source;
435 eviction = Some(outcome);
436 }
437 resolved_placements = Some(placements);
438 // Cleanup Step B (layout): insert `Op::Contiguize` before any kernel
439 // whose chosen winner rejects strided inputs and whose input layout is
440 // non-contiguous — the optimizer writing the layout-fixup decision INTO
441 // the graph (was the bridge's `apply_layout_fixups`, now retired). No
442 // runtime deps: reads only the in-scope `plan` winner caps + graph
443 // layout. CSE-deduped + idempotent. Gated on `pinned_device` so it runs
444 // on the realize path (which always sets one), matching the prior
445 // bridge behavior; bare-graph test callers without a pin are unaffected.
446 fuel_graph::opt::insert_layout_fixups(graph, roots, |id| {
447 plan.alternatives(id)
448 .and_then(|set| set.winner())
449 .map(|cand| cand.caps.strided_input)
450 .unwrap_or(true)
451 });
452 }
453
454 Ok(OptimizedGraph {
455 roots: roots.to_vec(),
456 generation,
457 placements: resolved_placements,
458 eviction,
459 })
460}
461
462/// Fused ops the optimizer lowers to their primitive recipe when the pinned device has no kernel
463/// for them (GAP-380 / ROADMAP row 149 (a1)). Deliberately a short allowlist: a fused op belongs
464/// here only after the recipe's placement was measured on the device. `PAGED_ATTN`: 25 -> 1
465/// host-placed nodes and 104.8 -> 50.7 ms/token at the mid Llama decode fixture (Fuel 1,
466/// 2026-11-12, n=1, ROADMAP row 149).
467const LOWER_WHEN_NO_DEVICE_KERNEL: &[fuel_graph::registry::FusedOpId] =
468 &[fuel_graph::registry::FusedOps::PAGED_ATTN];
469
470/// Lower every reachable [`LOWER_WHEN_NO_DEVICE_KERNEL`] fused node whose pinned backend has no
471/// kernel (`bound(op, backend)` is false) to its primitive recipe, in place. A no-op unless the
472/// pinned device is CUDA (the measured case; a CPU or Vulkan pin keeps the fused host kernel),
473/// except for `CONV2D_EPILOGUE`, which is lowered the same way on EVERY pinned backend with no kernel for it.
474/// Returns the number of nodes lowered; reported through `tracing` so a deoptimization is visible
475/// (C-6: fuel never changes a plan silently).
476///
477/// Not a numerics-neutral swap: the recipe computes the attention in the primitives' dtype order,
478/// so a consumer that needs the fused kernel's exact bits must pin a backend that has one.
479fn lower_fused_unbound_on_pinned_device(
480 graph: &mut Graph,
481 roots: &[NodeId],
482 opts: &PlanOptions<'_>,
483 bound: &dyn Fn(fuel_graph::registry::FusedOpId, fuel_ir::probe::BackendId) -> bool,
484) -> usize {
485 let Some(pinned) = opts.pinned_device else {
486 return 0;
487 };
488 let backend = pinned.backend();
489 let on_cuda = backend == fuel_ir::probe::BackendId::Cuda;
490 let lowered = fuel_graph::opt::lower_selected_fused(graph, roots, &|g, id| {
491 matches!(&g.node(id).op, Op::Fused(fid, _)
492 if ((on_cuda && LOWER_WHEN_NO_DEVICE_KERNEL.contains(fid))
493 // Row 172 item 3: a region no kernel can absorb is never refused; on
494 // any backend it runs as the conv followed by its elementwise ops.
495 || *fid == fuel_graph::registry::FusedOps::CONV2D_EPILOGUE)
496 && !bound(*fid, backend))
497 });
498 if lowered > 0 {
499 tracing::info!(
500 lowered,
501 "GAP-380: lowered {lowered} fused node(s) with no {backend:?} kernel to their primitive recipe so they place on the pinned device instead of the host"
502 );
503 }
504 lowered
505}
506
507/// Dtype-reconciliation fixup (runs BEFORE `compile_plan`): for any kernel-
508/// bearing node whose per-operand `(op, dtypes)` key is not servable by any
509/// compiled-in backend, insert `Op::Cast`(s) promoting the mismatched input(s)
510/// to the node's OUTPUT dtype — IF that lossless upcast yields a key some backend
511/// DOES support. This is "backends advertise; the optimizer adapts"
512/// ([04-optimization], [05-backend-contract]) applied to dtype, and the sibling
513/// of `insert_layout_fixups` (`Op::Contiguize`) and `insert_residency_copies`
514/// (`Op::Copy`).
515///
516/// It is the non-native-kernel fallback the mixed-precision matmul path already
517/// ASSUMED exists — `vulkan_dispatch`'s matmul route picker documents "otherwise
518/// falls back to f32 matmul (after a Cast)" — but which was never built as a
519/// pass, so a graph builder emitting a mixed `[F32, BF16] → F32` matmul
520/// dead-ended at `NoBackendForOp` on every backend without the native mixed key
521/// (all but Vulkan; and CPU-only default builds have none).
522///
523/// SAFE + CONSERVATIVE: promotes ONLY by a value-LOSSLESS upcast to the output
524/// dtype ([`lossless_upcast`]), so it never changes op semantics (a comparison's
525/// `U8` output is not a lossless upcast target, so comparisons are left alone) and
526/// never corrupts a value.
527///
528/// **NUMERIC CAVEAT:** the upcast is value-lossless but the promoted op is NOT
529/// numerically identical to a native mixed-precision kernel — it accumulates in
530/// the higher precision, so the *same graph* can differ by which arm ran (a CPU
531/// upcast vs a native `[F32,BF16,F32]` kernel; and it already differs
532/// CPU-vs-CUDA). The pass REPORTS every promotion via `tracing` (visibility, per
533/// C-6's "never silently deoptimize"). Making a promoting cast **forbiddable
534/// under a C-5 determinism/tolerance constraint** (so a byte-exact-oracle or
535/// CPU-vs-CUDA-parity consumer gets the native path or a hard fail, not a silent
536/// upcast) and **accounting its extra resident bytes under C-4** (BF16→F32
537/// doubles a weight) are tracked ROADMAP follow-ups.
538///
539/// When no lossless promotion yields a supported key, the node is left unchanged
540/// and fails cleanly at `compile_plan` with the truthful coverage diagnostic — a
541/// genuine gap, surfaced honestly. Returns whether it changed the graph (so the
542/// caller re-derives the execution order).
543///
544/// The broader fix — expanding per-op dtype coverage across kernels (starting
545/// CPU) so fewer combos need reconciling — is a tracked ROADMAP item; this pass
546/// makes the graph builder's mixed-precision promise executable everywhere today.
547fn insert_dtype_fixups(
548 graph: &mut Graph,
549 roots: &[NodeId],
550 bindings: &KernelBindingTable,
551 options: &PlanOptions<'_>,
552) -> bool {
553 let order = topo_order_multi(graph, roots);
554 // Decision only (immutable graph reads): the `(consumer, input, target)` edges
555 // to promote. The mechanical Cast-insert + rewire is
556 // `fuel_graph::opt::insert_cast_fixups` (the dtype-changing sibling of the
557 // layout fixup). Built in topo order ⇒ deterministic cast-node assignment.
558 let mut casts: Vec<(NodeId, NodeId, DType)> = Vec::new();
559
560 for &id in &order {
561 let (op, inputs, out_dtype) = {
562 let node = graph.node(id);
563 (node.op.clone(), node.inputs.clone(), node.dtype)
564 };
565 let op_kind = match crate::pipelined::op_to_op_kind(&op) {
566 Some(k) => k,
567 None => continue, // view / Const / not-dispatched → no binding key
568 };
569 // The exact per-operand key the dispatcher will look up.
570 let native_key = crate::pipelined::build_lookup_dtypes(graph, graph.node(id));
571 // Only reconcile the generic `[in0, in1, …, out]` key shape. Ops whose
572 // key is canonicalized (Concat, WriteSlice*) share a uniform input dtype
573 // by construction, so they never present a mixed-input miss here.
574 if native_key.len() != inputs.len() + 1 {
575 continue;
576 }
577 // The backends THIS node may actually be placed on. Asked via the
578 // planner's own resolver so the two cannot drift: a weaker predicate
579 // here (e.g. "does any registered backend serve it?") lets a backend
580 // the node can never run on suppress the reconciliation the node needs,
581 // and `compile_plan` below then dead-ends at `NoBackendForOp`.
582 let candidates = crate::plan::candidate_backends_for(graph, options, id, graph.node(id));
583 let servable = |key: &[DType]| {
584 candidates
585 .iter()
586 .any(|&backend| bindings.backend_supports(op_kind, key, backend))
587 };
588
589 if servable(&native_key) {
590 continue; // a backend this node can run on serves it natively
591 }
592 // Promotion target = the output dtype ("compute dtype"), taken ONLY when
593 // every input can losslessly upcast to it — else decline.
594 let target = out_dtype;
595 if !inputs
596 .iter()
597 .all(|&i| lossless_upcast(graph.node(i).dtype, target))
598 {
599 continue;
600 }
601 // Uniform promoted key `[target, …, target, out]` (target == out).
602 let promoted_key: Vec<DType> = inputs
603 .iter()
604 .map(|_| target)
605 .chain(std::iter::once(out_dtype))
606 .collect();
607 if promoted_key == native_key {
608 continue; // inputs already == target; nothing to promote
609 }
610 if !servable(&promoted_key) {
611 continue; // the lossless promotion still isn't servable — genuine gap
612 }
613 for &input_id in &inputs {
614 if graph.node(input_id).dtype != target {
615 casts.push((id, input_id, target));
616 }
617 }
618 }
619
620 if casts.is_empty() {
621 return false;
622 }
623 // Visibility (C-6 "fuel never silently deoptimizes without saying so", applied
624 // to precision rather than fusion): a promoting cast is NOT numerically
625 // identical to a native mixed-precision kernel — it accumulates the upcast in
626 // higher precision, so the same graph can diverge by which arm ran (CPU upcast
627 // vs CUDA native mixed) — and it increases the promoted operand's resident
628 // bytes (e.g. BF16→F32 doubles a weight). A byte-exact-oracle or determinism
629 // consumer must be able to SEE it. Reported via `tracing`; forbidding it under
630 // a C-5 constraint + full C-4 cost accounting are tracked ROADMAP follow-ups.
631 tracing::warn!(
632 promoting_casts = casts.len(),
633 "dtype-reconciliation inserted {} promoting Cast(s): a node's per-operand \
634 dtype key had no native kernel on any backend, so input(s) were upcast to \
635 the output dtype. This CHANGES numerics vs a native mixed-precision kernel \
636 and increases resident bytes for the promoted operand(s).",
637 casts.len(),
638 );
639 fuel_graph::opt::insert_cast_fixups(graph, &casts);
640 true
641}
642
643/// Lossless dtype upcast predicate for [`insert_dtype_fixups`] — `true` ONLY for
644/// conversions that preserve every value exactly (identity + float widenings
645/// where the target's exponent AND mantissa cover the source's). Deliberately
646/// conservative: an unlisted pair returns `false`, so the pass declines rather
647/// than risk a lossy or semantics-changing promotion.
648fn lossless_upcast(from: DType, to: DType) -> bool {
649 use DType::*;
650 if from == to {
651 return true;
652 }
653 matches!(
654 (from, to),
655 (BF16, F32) | (BF16, F64) | (F16, F32) | (F16, F64) | (F32, F64)
656 )
657}
658
659/// Commit the plan's per-node winner backend to the graph's
660/// `target_backend` side-table — the optimizer writing its placement
661/// decision into the graph.
662///
663/// Per kernel-bearing node: stamp `winner.backend` if the plan has an
664/// `AlternativeSet` for it, else the pinned device's backend (structural
665/// ops the planner skips — `Op::Copy`/`Op::Move`/`Op::Alloc`/`Op::ZeroFill`
666/// — plus any op without an `OpKind` mapping). `Op::Const`/`Op::Release`/
667/// `Op::Contiguize`/view ops/`Op::Reshape` inherit or don't need a stamp
668/// and are skipped. Always overwrites, so re-optimizing after a
669/// `TopologyChanged` retry re-stamps consistently from the fresh plan.
670fn stamp_plan_backends(
671 graph: &mut Graph,
672 roots: &[NodeId],
673 plan: &ExecutionPlan,
674 pinned_loc: DeviceLocation,
675) {
676 let pinned_backend = pinned_loc.backend();
677 let order = topo_order_multi(graph, roots);
678 for &id in &order {
679 let node = graph.node(id);
680 if matches!(node.op, Op::Const | Op::Release | Op::Contiguize)
681 || node.op.is_view_op()
682 || matches!(node.op, Op::Reshape(_))
683 {
684 continue;
685 }
686 let stamp = plan
687 .alternatives(id)
688 .and_then(|set| set.winner())
689 .map(|c| c.backend)
690 .unwrap_or(pinned_backend);
691 graph.set_target_backend(id, stamp);
692 }
693}
694
695/// Cleanup Step B (residency): the optimizer-side cross-device copy pass —
696/// insert `Op::Copy { target }` on every edge whose producer's resident
697/// location doesn't share a storage substrate with the consumer's placement,
698/// then stamp each inserted copy's `target_backend` with the SOURCE backend
699/// (the pipelined executor's `Op::Copy` convention: the transfer kernel runs
700/// on the backend the bytes come FROM). Was the bridge's
701/// `insert_resident_input_copies`; moved here so the optimizer — not the
702/// realize-time bridge — owns the residency decision and writes it into the
703/// graph.
704///
705/// Placements come from graph-knowable facts only (no realize-time storage):
706/// residency-declaring ops, explicit `Graph::placement` (the bridge converts
707/// cache residency into placement stamps before optimize — cleanup Step B),
708/// the plan winner's device, the `target_backend` stamp (→ pinned), and view
709/// pass-through. Substrate sharing is queried via the process-global
710/// `SystemTopology` (available pre-realize once backends are registered).
711///
712/// Runs after `stamp_plan_backends` (it reads `target_backend`); the re-stamp
713/// sweep below restores the source-backend stamp on copies/moves that the
714/// stamping pass overwrote with the pinned backend.
715/// Returns the effective-placement map it resolved, so the optimizer can hand
716/// it out via [`OptimizedGraph::placement_of`]. The map is the pass's own input
717/// — surfacing it costs nothing and makes the placement decision observable
718/// instead of inferable.
719///
720/// Note the snapshot is taken BEFORE copy insertion (see the `placements`
721/// comment below), which is the right vantage for "where did this node land":
722/// it reports the placement of the original nodes, with the inserted copies
723/// being the consequence rather than part of the answer.
724pub(crate) fn insert_residency_copies(
725 graph: &mut Graph,
726 roots: &[NodeId],
727 plan: &ExecutionPlan,
728 pinned_loc: DeviceLocation,
729 input_residency: Option<&dyn Fn(NodeId) -> Option<DeviceLocation>>,
730) -> HashMap<NodeId, DeviceLocation> {
731 // Step E Phase C, PR C-0: walk the ARM-INCLUSIVE reachable set, not bare
732 // `roots`. A finalized `Op::Branch` is orphaned (its `reconverge_at` reads
733 // arm-0 directly, per the PR-A1 runnability invariant), so a plain
734 // `topo_order_multi(roots)` never reaches it — and therefore never reaches
735 // its non-arm-0 arms. The residency pass MUST stitch inbound cross-device
736 // copies for EVERY surviving arm so the executor can legally re-pick
737 // arm-1+ at runtime by live load (C2): whichever arm it picks, that arm's
738 // device-inputs are already resident. `effective_roots` (the same seeding
739 // the run extractor + route picker use) pulls every Branch's arms into the
740 // walk. On a branchless graph it returns exactly `roots` ⇒ byte-identical.
741 let eff_roots = fuel_graph::effective_roots(graph, roots);
742 let placements = effective_placements(graph, &eff_roots, plan, pinned_loc, input_residency);
743 let topology = SystemTopology::current();
744 // Identical locations short-circuit to `true` BEFORE the topology lookup
745 // (a location trivially shares bytes with itself; `shares_storage` returns
746 // `false` for unknown backends, so without this an unprobed topology would
747 // wrap every same-device edge in a copy).
748 let shares = |a: DeviceLocation, b: DeviceLocation| -> bool {
749 if a == b {
750 return true;
751 }
752 topology.shares_storage((a.backend(), a), (b.backend(), b))
753 };
754 // Hop-count oracle: an edge whose transfer path is `HostStaging` can't
755 // be done as a single `Op::Copy` (no direct device-to-device copy
756 // kernel between distinct GPU substrates — the cross-VENDOR CUDA↔Vulkan
757 // case), so the residency pass routes it through a CPU intermediate as
758 // TWO hops. `SystemTopology::transfer_path` already returns `HostStaging`
759 // for such pairs and `SameDevice` for `a == b`; CPU↔CUDA / CPU↔Vulkan
760 // resolve to a direct path (or the universal host-staging fallback only
761 // when CPU is NOT one of the endpoints), so any CPU-touching edge stays
762 // single-hop. We additionally guard on neither endpoint being CPU: a CPU
763 // intermediate for a CPU-touching edge would be nonsensical (and the
764 // single-hop CPU↔GPU Copy kernels exist and are byte-identical to
765 // today). Same-vendor GPU pairs that don't share storage (e.g. CUDA gpu0
766 // ↔ gpu1) fall back to `HostStaging` too — correctly two-hop, since
767 // there's no direct cross-gpu_id copy kernel today either.
768 let needs_host_staging = |a: DeviceLocation, b: DeviceLocation| -> bool {
769 if a == DeviceLocation::Cpu || b == DeviceLocation::Cpu {
770 return false;
771 }
772 matches!(
773 topology.transfer_path(a, b),
774 fuel_ir::backend::TransferPath::HostStaging
775 )
776 };
777 let inserted = insert_cross_device_copies(
778 graph,
779 &eff_roots,
780 |id| placements.get(&id).copied(),
781 shares,
782 needs_host_staging,
783 );
784 // Source-location resolver for stamping inserted copies. The
785 // `placements` snapshot was computed BEFORE insertion, so it does NOT
786 // contain the freshly-inserted CPU intermediate of a two-hop edge. That
787 // intermediate's placement was written into the graph by the pass
788 // (`set_placement(cpu_id, Cpu)`), so fall back to `graph.placement(src)`
789 // when the snapshot lacks the node — this is what stamps a two-hop's
790 // consumer-side hop with `Cpu` (its bytes come FROM the CPU intermediate,
791 // so its Copy kernel is the CPU `copy_from_cpu_wrapper`).
792 let src_location = |graph: &Graph, src: NodeId| -> Option<DeviceLocation> {
793 placements
794 .get(&src)
795 .copied()
796 .or_else(|| graph.placement(src))
797 };
798 // Stamp the new copies: target_backend = SOURCE backend. The pass only
799 // inserts a copy when the producer's placement resolved to Some.
800 for ©_id in &inserted {
801 if let Some(&src) = graph.node(copy_id).inputs.first()
802 && let Some(src_loc) = src_location(graph, src)
803 {
804 graph.set_target_backend(copy_id, src_loc.backend());
805 }
806 }
807 // Re-stamp ALL copies/moves with their SOURCE backend — graph rewrites are
808 // sticky and `stamp_plan_backends` just overwrote pre-existing ones (e.g.
809 // realize-root splices) with the pinned backend; the transfer kernel runs
810 // where the bytes come from. The freshly-inserted copies are visited too,
811 // but their input's placement resolves to the same source location, so the
812 // sweep re-applies the identical stamp (idempotent). Copies whose source
813 // placement is absent keep whatever stamp they already have. The two-hop
814 // CPU intermediate's source is the original GPU producer (stamped to that
815 // GPU); the consumer-side hop's source is the CPU intermediate (stamped
816 // Cpu via the `graph.placement` fallback in `src_location`).
817 // Arm-inclusive (C-0): re-walk from the arm-seeded roots so copies just
818 // inserted inside non-arm-0 arms are re-stamped too. The `eff_roots` seed
819 // set (Branch nodes are unchanged by insertion) reaches the fresh arm
820 // copies via the now-rewired arm-input edges.
821 let order = topo_order_multi(graph, &eff_roots);
822 for &id in &order {
823 if !matches!(graph.node(id).op, Op::Copy { .. } | Op::Move { .. }) {
824 continue;
825 }
826 let Some(&src) = graph.node(id).inputs.first() else {
827 continue;
828 };
829 let Some(src_loc) = src_location(graph, src) else {
830 continue;
831 };
832 graph.set_target_backend(id, src_loc.backend());
833 }
834
835 placements
836}
837
838/// Compute every reachable node's *effective placement* for the residency
839/// pass, mirroring the bridge's old `effective_placements`. Priority per node:
840///
841/// 1. **Residency-declaring ops** — `Op::Copy`/`Op::Move`/`Op::Alloc` carry
842/// their output location in the variant (definitional).
843/// 2. **Explicit `Graph::placement`** — set by inserted copies (and any
844/// caller-provided placement hints).
845/// 3. **Input residency** — where a persistent / const input already lives,
846/// supplied by the realize path via `PlanOptions::input_residency`. This is
847/// the only runtime fact, read through the provider closure — the optimizer
848/// never touches the storage itself.
849/// 4. **Plan winner** — a planned node runs on its winner's device.
850/// 5. **Backend stamp** — a node with `target_backend` but no plan entry
851/// (structural ops) follows the pinned device.
852/// 6. **View pass-throughs** — view ops / `Reshape` / `Contiguize` follow
853/// their data input (already resolved; `order` is topological).
854fn effective_placements(
855 g: &Graph,
856 roots: &[NodeId],
857 plan: &ExecutionPlan,
858 pinned_loc: DeviceLocation,
859 input_residency: Option<&dyn Fn(NodeId) -> Option<DeviceLocation>>,
860) -> HashMap<NodeId, DeviceLocation> {
861 let order = topo_order_multi(g, roots);
862 let mut map: HashMap<NodeId, DeviceLocation> = HashMap::with_capacity(order.len());
863 for &id in &order {
864 let node = g.node(id);
865 match node.op {
866 Op::Copy { target } | Op::Move { target } | Op::Alloc { target } => {
867 map.insert(id, target);
868 continue;
869 }
870 _ => {}
871 }
872 if let Some(loc) = g.placement(id) {
873 map.insert(id, loc);
874 continue;
875 }
876 if let Some(loc) = input_residency.and_then(|f| f(id)) {
877 map.insert(id, loc);
878 continue;
879 }
880 if let Some(winner) = plan.alternatives(id).and_then(|set| set.winner()) {
881 map.insert(id, winner.device);
882 continue;
883 }
884 if g.target_backend(id).is_some() {
885 map.insert(id, pinned_loc);
886 continue;
887 }
888 if (node.op.is_view_op() || matches!(node.op, Op::Reshape(_) | Op::Contiguize))
889 && let Some(&loc) = node.inputs.first().and_then(|i| map.get(i))
890 {
891 map.insert(id, loc);
892 }
893 }
894 map
895}
896
897/// The PR-A4 deliberate-fork pathfinder + the PR-B2 frontier
898/// convergence optimizer now live in [`crate::driver`] as registered
899/// [`crate::driver::Pathfinder`] / [`crate::driver::Optimizer`] impls
900/// ([`crate::driver::PlacementForkPathfinder`] /
901/// [`crate::driver::FrontierConvergenceOptimizer`]). PR-B3 replaced the
902/// hardcoded `seed_placement_fork_branches(...)` call in
903/// [`optimize_graph`] with a lock-step
904/// [`crate::driver::PassRegistry::run_lockstep`] drive over those
905/// registered passes (see the module docs). The pathfinder body is
906/// unchanged — it moved verbatim behind the trait.
907#[cfg(test)]
908mod tests {
909 use super::*;
910 use crate::fused::PrecisionGuarantee;
911 use crate::kernel::{KernelCaps, OpParams, unknown_cost};
912 use fuel_graph::opt::execution_plan;
913 use fuel_graph::{Node, Op};
914 use fuel_ir::dispatch::OpKind;
915 use fuel_ir::probe::BackendId;
916 use fuel_ir::{DType, DeviceLocation, Layout, Result as FuelResult, Shape};
917 use fuel_memory::Storage;
918 use std::sync::{Arc, RwLock};
919
920 fn noop_kernel(
921 _i: &[Arc<RwLock<Storage>>],
922 _o: &mut [Arc<RwLock<Storage>>],
923 _l: &[Layout],
924 _p: &OpParams,
925 ) -> FuelResult<()> {
926 Ok(())
927 }
928
929 fn register_elementwise(table: &mut KernelBindingTable, op: OpKind, n_in: usize) {
930 let mut dtypes = vec![DType::F32; n_in];
931 dtypes.push(DType::F32); // output dtype
932 table.register_full(
933 op,
934 &dtypes,
935 BackendId::Cpu,
936 noop_kernel,
937 KernelCaps::empty(),
938 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
939 unknown_cost,
940 );
941 }
942
943 fn f32_node(g: &mut Graph, op: Op, inputs: Vec<NodeId>) -> NodeId {
944 // No pre-stamp: post-Step-A `optimize_graph` writes `target_backend`
945 // itself, so pre-stamping here is redundant for the tests that run the
946 // optimizer — and it would falsify the `*_stamps_backends_*` tests'
947 // "unstamped before optimize" / "Const leaf not stamped" preconditions.
948 g.push(Node {
949 op,
950 inputs,
951 shape: Shape::from_dims(&[4]),
952 dtype: DType::F32,
953 })
954 }
955
956 /// A representative branchless CPU graph the optimizer can fully
957 /// place: a fan-in (`Add` over two unary chains) feeding a unary
958 /// tail. Every kernel-bearing op has a CPU binding registered. The
959 /// fan-in exercises the run extractor's multi-predecessor boundary,
960 /// so the equivalence holds across more than a single straight
961 /// chain.
962 fn build_branchless_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
963 register_elementwise(table, OpKind::ReluElementwise, 1);
964 register_elementwise(table, OpKind::SiluElementwise, 1);
965 register_elementwise(table, OpKind::AddElementwise, 2);
966 register_elementwise(table, OpKind::TanhElementwise, 1);
967
968 let mut g = Graph::new();
969 let a = f32_node(&mut g, Op::Const, vec![]);
970 let a1 = f32_node(&mut g, Op::Relu, vec![a]);
971 let b = f32_node(&mut g, Op::Const, vec![]);
972 let b1 = f32_node(&mut g, Op::Silu, vec![b]);
973 let sum = f32_node(&mut g, Op::Add, vec![a1, b1]);
974 let out = f32_node(&mut g, Op::Tanh, vec![sum]);
975 (g, out)
976 }
977
978 /// ROADMAP row 67 (I1): a graph whose analysed peak exceeds a small budget. `a` is read by `b` early and
979 /// by `c` late, so its longest inactive gap is evictable (the same shape the residency tests use).
980 fn build_over_budget_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
981 register_elementwise(table, OpKind::ReluElementwise, 1);
982 register_elementwise(table, OpKind::NegElementwise, 1);
983 register_elementwise(table, OpKind::MulElementwise, 2);
984 register_elementwise(table, OpKind::AddElementwise, 2);
985 let mut g = Graph::new();
986 let a = f32_node(&mut g, Op::Const, vec![]);
987 let b = f32_node(&mut g, Op::Relu, vec![a]);
988 let pad = f32_node(&mut g, Op::Neg, vec![b]);
989 let pad2 = f32_node(&mut g, Op::Neg, vec![pad]);
990 let c = f32_node(&mut g, Op::Mul, vec![pad2, a]);
991 let out = f32_node(&mut g, Op::Add, vec![b, c]);
992 (g, out)
993 }
994
995 fn count_ops(g: &Graph, pred: impl Fn(&Op) -> bool) -> usize {
996 (0..g.len())
997 .filter(|i| pred(&g.node(NodeId(*i)).op))
998 .count()
999 }
1000
1001 fn peak_bytes(g: &Graph, root: NodeId) -> usize {
1002 crate::residency::ResidencyPlanner::analyze(g, &[root]).peak_bytes
1003 }
1004
1005 #[test]
1006 fn a_device_budget_below_the_peak_inserts_evict_reload_chains() {
1007 let mut table = KernelBindingTable::new();
1008 let (mut g, root) = build_over_budget_graph(&mut table);
1009 let before = peak_bytes(&g, root);
1010 let opts = cpu_opts().with_device_budget_bytes(before - 1);
1011 let optimized =
1012 optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph under a budget");
1013 let outcome = optimized
1014 .eviction
1015 .as_ref()
1016 .expect("a budgeted run reports what the eviction pass did");
1017 assert!(
1018 !outcome.chains.is_empty(),
1019 "the outcome lists the inserted chains"
1020 );
1021 assert_eq!(outcome.budget_bytes, before - 1);
1022 assert!(
1023 count_ops(&g, |op| matches!(op, Op::Move { .. })) >= 1,
1024 "a budget below the peak must insert an Op::Move eviction"
1025 );
1026 assert!(
1027 count_ops(&g, |op| matches!(op, Op::Copy { .. })) >= 1,
1028 "and its reload Op::Copy"
1029 );
1030 // Not asserted here: a drop in the analysed peak. This graph is pinned to the CPU, and a
1031 // spill to the CPU cannot lower CPU residency; that property is pinned in
1032 // `residency::tests::today_the_reload_runs_eagerly_so_the_device_peak_does_not_drop`
1033 // (which documents that no round lowers the analysed peak until ROADMAP row 67 I3).
1034 }
1035
1036 #[test]
1037 fn the_plan_report_names_where_the_budget_came_from() {
1038 use crate::device_budget::{BudgetSource, ResolvedBudget};
1039 let run = |opts: PlanOptions<'_>| {
1040 let mut table = KernelBindingTable::new();
1041 let (mut g, root) = build_over_budget_graph(&mut table);
1042 optimize_graph(&mut g, &[root], &table, &opts)
1043 .expect("optimize_graph")
1044 .eviction
1045 .expect("a budgeted run reports an outcome")
1046 };
1047 let mut table = KernelBindingTable::new();
1048 let (g, root) = build_over_budget_graph(&mut table);
1049 let budget = peak_bytes(&g, root) - 1;
1050 let resolved = ResolvedBudget {
1051 bytes: budget,
1052 source: BudgetSource::Probed {
1053 available: (budget as u64) * 10 / 9,
1054 fraction: 0.9,
1055 },
1056 };
1057 let from_policy = run(cpu_opts().with_resolved_device_budget(resolved));
1058 assert_eq!(from_policy.budget_bytes, budget);
1059 assert_eq!(from_policy.budget_source, Some(resolved.source));
1060 // Control: a hand-set number carries no source, so the two paths are told apart.
1061 let by_hand = run(cpu_opts().with_device_budget_bytes(budget));
1062 assert_eq!(by_hand.budget_source, None);
1063 }
1064
1065 #[test]
1066 fn no_budget_a_roomy_budget_or_no_pinned_device_leave_the_graph_alone() {
1067 let nodes_of = |opts: &PlanOptions<'_>| {
1068 let mut table = KernelBindingTable::new();
1069 let (mut g, root) = build_over_budget_graph(&mut table);
1070 if opts.pinned_device.is_none() {
1071 // No pinned device: nodes need explicit placements to plan at all.
1072 for i in 0..g.len() {
1073 g.set_placement(NodeId(i), DeviceLocation::Cpu);
1074 }
1075 }
1076 let optimized = optimize_graph(&mut g, &[root], &table, opts).expect("optimize_graph");
1077 if opts.device_budget_bytes.is_none() {
1078 assert!(optimized.eviction.is_none(), "no budget: no outcome");
1079 }
1080 (g.len(), count_ops(&g, |op| matches!(op, Op::Move { .. })))
1081 };
1082 // Negative control: no budget at all.
1083 assert_eq!(nodes_of(&cpu_opts()).1, 0, "no budget: no eviction");
1084 // A budget the graph already fits.
1085 assert_eq!(
1086 nodes_of(&cpu_opts().with_device_budget_bytes(usize::MAX)).1,
1087 0,
1088 "roomy budget: no eviction"
1089 );
1090 // The pass is gated on a pinned device, like the residency pass it follows.
1091 let unpinned = PlanOptions::new()
1092 .without_cost_population()
1093 .with_device_budget_bytes(1);
1094 assert_eq!(nodes_of(&unpinned).1, 0, "no pinned device: no eviction");
1095 // Node counts match the no-budget run exactly.
1096 assert_eq!(
1097 nodes_of(&cpu_opts()).0,
1098 nodes_of(&cpu_opts().with_device_budget_bytes(usize::MAX)).0
1099 );
1100 }
1101
1102 /// A pure straight-line CPU graph — the simplest no-competing-route
1103 /// case (exactly one run by construction).
1104 fn build_straight_line_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
1105 register_elementwise(table, OpKind::ReluElementwise, 1);
1106 register_elementwise(table, OpKind::SiluElementwise, 1);
1107 register_elementwise(table, OpKind::TanhElementwise, 1);
1108
1109 let mut g = Graph::new();
1110 let a = f32_node(&mut g, Op::Const, vec![]);
1111 let b = f32_node(&mut g, Op::Relu, vec![a]);
1112 let c = f32_node(&mut g, Op::Silu, vec![b]);
1113 let d = f32_node(&mut g, Op::Tanh, vec![c]);
1114 (g, d)
1115 }
1116
1117 fn cpu_opts() -> PlanOptions<'static> {
1118 // No cost machinery: A3a only needs placement/validation, not
1119 // ranking. Pin the realize device so every node resolves.
1120 PlanOptions::new()
1121 .without_cost_population()
1122 .with_pinned_device(DeviceLocation::Cpu)
1123 }
1124
1125 /// Cleanup Step A: `optimize_graph` stamps each computational node's
1126 /// chosen backend onto the graph (the optimizer writes its placement
1127 /// decision INTO the graph). On a pinned-CPU straight-line graph every
1128 /// kernel-bearing node is stamped `Cpu`; the leaf `Op::Const` is
1129 /// skipped (it inherits / needs no stamp). When `pinned_device` is
1130 /// unset, no stamping occurs (the bare-graph test contract).
1131 #[test]
1132 fn optimize_graph_stamps_backends_onto_the_graph() {
1133 let mut table = KernelBindingTable::new();
1134 let (mut g, root) = build_straight_line_graph(&mut table);
1135 // a=Const(0), b=Relu(1), c=Silu(2), d=Tanh(3) by construction.
1136 let (a, b, c, d) = (NodeId(0), NodeId(1), NodeId(2), NodeId(3));
1137 assert!(g.target_backend(b).is_none(), "unstamped before optimize");
1138
1139 let _optimized = optimize_graph(&mut g, &[root], &table, &cpu_opts())
1140 .expect("optimize_graph on a straight-line CPU graph");
1141
1142 assert_eq!(
1143 g.target_backend(b),
1144 Some(BackendId::Cpu),
1145 "Relu stamped Cpu"
1146 );
1147 assert_eq!(
1148 g.target_backend(c),
1149 Some(BackendId::Cpu),
1150 "Silu stamped Cpu"
1151 );
1152 assert_eq!(
1153 g.target_backend(d),
1154 Some(BackendId::Cpu),
1155 "Tanh stamped Cpu"
1156 );
1157 assert!(
1158 g.target_backend(a).is_none(),
1159 "Op::Const leaf is not stamped"
1160 );
1161 }
1162
1163 /// `OptimizedGraph::placement_of` makes the placement DECISION observable,
1164 /// so a consumer can check where work landed instead of inferring it from
1165 /// timing (or from `Graph::placement`, which is only level 2 of the six-way
1166 /// resolution and returns `None` for exactly the compute nodes that matter).
1167 ///
1168 /// Two halves, and the second is the **positive control**: an accessor that
1169 /// silently returned `None` for everything would satisfy any test that only
1170 /// asserted `is_none()` on the unpinned path. So the pinned path asserts
1171 /// concrete `Some(Cpu)` values AND a non-empty map — if placement were never
1172 /// captured, that half fails loudly rather than passing vacuously.
1173 #[test]
1174 fn placement_of_observes_the_decision_and_marks_not_computed() {
1175 // --- pinned: the residency pass runs, placements are captured ---
1176 let mut table = KernelBindingTable::new();
1177 let (mut g, root) = build_straight_line_graph(&mut table);
1178 let (_a, b, c, d) = (NodeId(0), NodeId(1), NodeId(2), NodeId(3));
1179
1180 let optimized = optimize_graph(&mut g, &[root], &table, &cpu_opts())
1181 .expect("optimize_graph on a straight-line CPU graph");
1182
1183 assert!(
1184 optimized.has_placements(),
1185 "a pinned device runs the residency pass, so placements must be computed",
1186 );
1187 // POSITIVE CONTROL: concrete values, not merely "not None". An empty or
1188 // never-populated map would fail here instead of passing quietly.
1189 assert_eq!(
1190 optimized.placement_of(b),
1191 Some(DeviceLocation::Cpu),
1192 "Relu placed Cpu"
1193 );
1194 assert_eq!(
1195 optimized.placement_of(c),
1196 Some(DeviceLocation::Cpu),
1197 "Silu placed Cpu"
1198 );
1199 assert_eq!(
1200 optimized.placement_of(d),
1201 Some(DeviceLocation::Cpu),
1202 "Tanh placed Cpu"
1203 );
1204 assert!(
1205 optimized.placements().count() >= 3,
1206 "the map must actually be populated, got {} entries",
1207 optimized.placements().count(),
1208 );
1209
1210 // --- unpinned: the pass is skipped, and that is DISTINGUISHABLE ---
1211 // This is the property that keeps a `None` from being misread as
1212 // "placed nowhere" — the failure mode this accessor exists to prevent.
1213 //
1214 // Device context has to come from SOMEWHERE or `compile_plan` refuses
1215 // outright ("node has no device context — set PlanOptions::pinned_device,
1216 // a graph placement, or the node's target_backend"). So supply it via
1217 // per-node graph placement instead of a pin: the graph optimizes fine,
1218 // but `pinned_device` is unset so the residency pass never runs — which
1219 // is exactly the "optimized successfully, placement not computed" state
1220 // a caller must be able to tell apart from "placed nowhere".
1221 let mut table2 = KernelBindingTable::new();
1222 let (mut g2, root2) = build_straight_line_graph(&mut table2);
1223 for n in [NodeId(0), NodeId(1), NodeId(2), NodeId(3)] {
1224 g2.set_placement(n, DeviceLocation::Cpu);
1225 }
1226 let bare = PlanOptions::new().without_cost_population();
1227 let unpinned = optimize_graph(&mut g2, &[root2], &table2, &bare)
1228 .expect("optimize_graph with graph placements but no pinned device");
1229
1230 assert!(
1231 !unpinned.has_placements(),
1232 "no pinned device => residency pass skipped => placements NOT computed",
1233 );
1234 assert_eq!(
1235 unpinned.placement_of(b),
1236 None,
1237 "and every lookup is None — which `has_placements()` explains as \
1238 'not computed', never 'placed nowhere'",
1239 );
1240 }
1241
1242 /// Dtype-reconciliation declines on the REAL CPU table: the mixed-precision `[F32, BF16, F32]`
1243 /// and `[F32, F16, F32]` matmuls (f32 activation x half weight) are served natively by the CPU
1244 /// kernels `matmul_f32_bf16` / `matmul_f32_f16` (ROADMAP row 34), so `optimize_graph` plans them
1245 /// as they are and inserts no `Cast`: the weight stays half-width instead of being promoted to a
1246 /// resident f32 copy. Before row 34 this test asserted the opposite (a `Cast(F32)` on the
1247 /// weight, the fallback that the local-table tests below still pin for a backend WITHOUT the
1248 /// native key).
1249 #[test]
1250 fn optimize_graph_keeps_mixed_precision_matmul_native_on_cpu() {
1251 for weight in [DType::BF16, DType::F16] {
1252 let bindings = crate::dispatch::global_bindings(); // real populated CPU table
1253 let mut g = Graph::new();
1254 let lhs = g.push(Node {
1255 op: Op::Const,
1256 inputs: vec![],
1257 shape: Shape::from_dims(&[2, 3]),
1258 dtype: DType::F32,
1259 });
1260 let rhs = g.push(Node {
1261 op: Op::Const,
1262 inputs: vec![],
1263 shape: Shape::from_dims(&[3, 2]),
1264 dtype: weight,
1265 });
1266 let mm = g.push(Node {
1267 op: Op::MatMul,
1268 inputs: vec![lhs, rhs],
1269 shape: Shape::from_dims(&[2, 2]),
1270 dtype: DType::F32,
1271 });
1272
1273 optimize_graph(&mut g, &[mm], &bindings, &cpu_opts())
1274 .expect("mixed-precision matmul plans natively on CPU");
1275
1276 assert_eq!(
1277 g.node(mm).inputs,
1278 vec![lhs, rhs],
1279 "{weight:?}: no Cast, the CPU serves [F32, {weight:?}, F32] natively",
1280 );
1281 assert_eq!(g.node(rhs).dtype, weight, "the weight stays {weight:?}");
1282 }
1283 }
1284
1285 fn register_matmul(table: &mut KernelBindingTable, dtypes: &[DType], backend: BackendId) {
1286 table.register_full(
1287 OpKind::MatMul,
1288 dtypes,
1289 backend,
1290 noop_kernel,
1291 KernelCaps::empty(),
1292 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1293 unknown_cost,
1294 );
1295 }
1296
1297 /// The reconciling `Op::Cast` the pass inserts needs a binding of its own to
1298 /// plan. The production table has these (`(Cpu, Cast, [BF16, F32])`); a
1299 /// hand-built test table must register them explicitly.
1300 fn register_cast(table: &mut KernelBindingTable, from: DType, to: DType, backend: BackendId) {
1301 table.register_full(
1302 OpKind::Cast,
1303 &[from, to],
1304 backend,
1305 noop_kernel,
1306 KernelCaps::empty(),
1307 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1308 unknown_cost,
1309 );
1310 }
1311
1312 /// `[F32] @ [BF16] -> [F32]` on a graph pinned to `pinned`.
1313 fn mixed_matmul_graph() -> (Graph, NodeId, NodeId, NodeId) {
1314 let mut g = Graph::new();
1315 let lhs = g.push(Node {
1316 op: Op::Const,
1317 inputs: vec![],
1318 shape: Shape::from_dims(&[2, 3]),
1319 dtype: DType::F32,
1320 });
1321 let rhs = g.push(Node {
1322 op: Op::Const,
1323 inputs: vec![],
1324 shape: Shape::from_dims(&[3, 2]),
1325 dtype: DType::BF16,
1326 });
1327 let mm = g.push(Node {
1328 op: Op::MatMul,
1329 inputs: vec![lhs, rhs],
1330 shape: Shape::from_dims(&[2, 2]),
1331 dtype: DType::F32,
1332 });
1333 (g, lhs, rhs, mm)
1334 }
1335
1336 /// **Born-red regression guard: a backend must never break a graph that
1337 /// isn't running on it.**
1338 ///
1339 /// `insert_dtype_fixups` used to guard on `any_backend_supports` — a
1340 /// predicate over the WHOLE binding table that ignores the key's backend
1341 /// component. `compile_plan` enumerates over the node's *candidate
1342 /// placement set*. So when a non-candidate backend owned the only native
1343 /// mixed-dtype kernel, the pass saw "someone serves it", declined to
1344 /// reconcile, and the planner then dead-ended at `NoBackendForOp`.
1345 ///
1346 /// In-tree that surfaced as `--features vulkan` breaking CPU-pinned
1347 /// mixed-precision matmul, because Vulkan happens to be the only backend
1348 /// registering `MatMul[F32, BF16, F32]`. This test builds that situation
1349 /// from a LOCAL table so it reproduces in **every** build configuration —
1350 /// the feature-gated version is why the defect shipped unnoticed.
1351 #[test]
1352 fn dtype_reconciliation_ignores_kernels_on_non_candidate_backends() {
1353 let mut table = KernelBindingTable::new();
1354 // The pinned backend serves only the uniform key...
1355 register_matmul(
1356 &mut table,
1357 &[DType::F32, DType::F32, DType::F32],
1358 BackendId::Cpu,
1359 );
1360 // ...while a backend this graph will never run on owns the mixed key.
1361 register_matmul(
1362 &mut table,
1363 &[DType::F32, DType::BF16, DType::F32],
1364 BackendId::Vulkan,
1365 );
1366 register_cast(&mut table, DType::BF16, DType::F32, BackendId::Cpu);
1367
1368 let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
1369 optimize_graph(&mut g, &[mm], &table, &cpu_opts()).expect(
1370 "CPU-pinned mixed-precision matmul must reconcile via Cast even though \
1371 a NON-candidate backend owns the native mixed kernel",
1372 );
1373
1374 let mm_inputs = g.node(mm).inputs.clone();
1375 assert_eq!(mm_inputs[0], lhs, "lhs (already F32) untouched");
1376 let cast_id = mm_inputs[1];
1377 assert_ne!(cast_id, rhs, "rhs was rewired to a Cast");
1378 assert!(
1379 matches!(g.node(cast_id).op, Op::Cast(DType::F32)),
1380 "rhs cast to F32"
1381 );
1382 assert_eq!(
1383 g.node(cast_id).inputs,
1384 vec![rhs],
1385 "cast reads the original BF16 weight"
1386 );
1387 }
1388
1389 /// The converse guard — the fix must not over-cast. When the node's own
1390 /// candidate backend serves the mixed key natively, reconciliation must
1391 /// decline, so the native mixed-precision kernel is preserved (casting
1392 /// would change numerics and double the promoted operand's bytes).
1393 #[test]
1394 fn dtype_reconciliation_declines_when_the_candidate_backend_serves_it_natively() {
1395 let mut table = KernelBindingTable::new();
1396 register_matmul(
1397 &mut table,
1398 &[DType::F32, DType::BF16, DType::F32],
1399 BackendId::Cpu,
1400 );
1401
1402 let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
1403 optimize_graph(&mut g, &[mm], &table, &cpu_opts()).expect("native mixed kernel plans");
1404
1405 assert_eq!(
1406 g.node(mm).inputs,
1407 vec![lhs, rhs],
1408 "no Cast: the candidate backend has the native mixed kernel",
1409 );
1410 }
1411
1412 /// Multi-device behavior must be PRESERVED, not sacrificed to fix the bug
1413 /// above. When an off-device fallback is admitted, the foreign backend IS
1414 /// a candidate for this node — so its native mixed kernel is reachable and
1415 /// reconciliation must still decline. This is why the fix mirrors the
1416 /// planner's candidate set rather than narrowing to the pinned device.
1417 #[test]
1418 fn dtype_reconciliation_counts_admitted_off_device_fallback_as_a_candidate() {
1419 let mut table = KernelBindingTable::new();
1420 register_matmul(
1421 &mut table,
1422 &[DType::F32, DType::F32, DType::F32],
1423 BackendId::Cpu,
1424 );
1425 register_matmul(
1426 &mut table,
1427 &[DType::F32, DType::BF16, DType::F32],
1428 BackendId::Vulkan,
1429 );
1430
1431 let fallback = |_from: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
1432 vec![(BackendId::Vulkan, DeviceLocation::Vulkan { gpu_id: 0 })]
1433 };
1434 let opts = PlanOptions::new()
1435 .without_cost_population()
1436 .with_pinned_device(DeviceLocation::Cpu)
1437 .with_fallback_placements_for(&fallback);
1438
1439 let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
1440 optimize_graph(&mut g, &[mm], &table, &opts).expect("off-device native mixed kernel plans");
1441
1442 assert_eq!(
1443 g.node(mm).inputs,
1444 vec![lhs, rhs],
1445 "no Cast: the admitted off-device fallback backend serves the mixed key natively",
1446 );
1447 }
1448
1449 /// The stamping is guarded on a pinned device — an `optimize_graph`
1450 /// with no `pinned_device` leaves the graph unstamped (so the bare
1451 /// optimize.rs test callers below are unaffected by Step A).
1452 #[test]
1453 fn optimize_graph_without_pinned_device_does_not_stamp() {
1454 let mut table = KernelBindingTable::new();
1455 let (mut g, root) = build_straight_line_graph(&mut table);
1456 // Give each node a device context via a graph PLACEMENT (a distinct
1457 // side-table from `target_backend`), so `compile_plan` resolves without
1458 // a pinned device — then assert `optimize_graph` performs no
1459 // `target_backend` stamping (the stamping arm is guarded on
1460 // `pinned_device`, so without a pin nothing is stamped).
1461 for id in [NodeId(0), NodeId(1), NodeId(2), NodeId(3)] {
1462 g.set_placement(id, DeviceLocation::Cpu);
1463 }
1464 let opts = PlanOptions::new().without_cost_population(); // no pinned device
1465 let _ = optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph");
1466 assert!(
1467 g.target_backend(NodeId(1)).is_none(),
1468 "no pinned device ⇒ no target_backend stamping",
1469 );
1470 }
1471
1472 /// Cleanup Step B (layout): `optimize_graph` inserts an `Op::Contiguize`
1473 /// before a kernel whose chosen winner rejects strided inputs
1474 /// (`caps.strided_input == false`, e.g. the `KernelCaps::empty()`
1475 /// elementwise bindings) and whose input layout is non-contiguous — the
1476 /// layout-fixup pass moved from the realize-time bridge into the optimizer.
1477 /// The pass itself is exhaustively tested in `fuel-graph::opt`; this guards
1478 /// the optimizer-side wiring (callback reads the plan winner's caps, runs
1479 /// inside the pinned guard).
1480 #[test]
1481 fn optimize_graph_inserts_layout_fixup_for_strided_input() {
1482 let mut table = KernelBindingTable::new();
1483 register_elementwise(&mut table, OpKind::ReluElementwise, 1); // empty caps ⇒ rejects strided
1484 let mut g = Graph::new();
1485 let a = f32_node(&mut g, Op::Const, vec![]);
1486 let r = f32_node(&mut g, Op::Relu, vec![a]);
1487 // Make `a`'s effective layout non-contiguous (non-zero start_offset),
1488 // so the strided-rejecting Relu needs a Contiguize on its input.
1489 g.set_layout(a, Layout::contiguous_with_offset(Shape::from_dims(&[4]), 1));
1490
1491 let _optimized = optimize_graph(&mut g, &[r], &table, &cpu_opts())
1492 .expect("optimize_graph with a strided input");
1493
1494 // Relu's input was `a`; after the fixup it must read through an inserted
1495 // Op::Contiguize wrapping `a`.
1496 let relu_input = g.node(r).inputs[0];
1497 assert!(
1498 matches!(g.node(relu_input).op, Op::Contiguize),
1499 "strided input to a strided-rejecting kernel must be fixed up via \
1500 Op::Contiguize, got {:?}",
1501 g.node(relu_input).op,
1502 );
1503 assert_eq!(
1504 g.node(relu_input).inputs,
1505 vec![a],
1506 "the inserted Op::Contiguize wraps the original strided input",
1507 );
1508 }
1509
1510 // ---- Cleanup Step B (residency) — insert_residency_copies tests ----
1511 // (migrated from the bridge's insert_resident_input_copies unit tests;
1512 // cache residency is supplied via an `input_residency` closure instead of a
1513 // live StorageCache. Placement metadata only — no GPU needed; the unprobed
1514 // test `SystemTopology` reports Cpu/Cuda as non-sharing, so a crossing is
1515 // detected and a copy inserted.)
1516
1517 /// Co-located graph ⇒ `insert_residency_copies` is a no-op (no crossings).
1518 #[test]
1519 fn residency_noop_when_colocated() {
1520 let mut g = Graph::new();
1521 let c1 = f32_node(&mut g, Op::Const, vec![]);
1522 let c2 = f32_node(&mut g, Op::Const, vec![]);
1523 let add = f32_node(&mut g, Op::Add, vec![c1, c2]);
1524 g.set_target_backend(add, BackendId::Cpu);
1525 let residency = |id: NodeId| (id == c1 || id == c2).then_some(DeviceLocation::Cpu);
1526 let pre = g.len();
1527 insert_residency_copies(
1528 &mut g,
1529 &[add],
1530 &ExecutionPlan::empty(),
1531 DeviceLocation::Cpu,
1532 Some(&residency),
1533 );
1534 assert_eq!(g.len(), pre, "co-located graph must be a no-op");
1535 assert_eq!(g.node(add).inputs, vec![c1, c2], "edges untouched");
1536 }
1537
1538 /// A CPU-resident input feeding two CUDA-pinned consumers ⇒ exactly ONE
1539 /// `Op::Copy` bridges the crossing (CSE-deduped), targeting the consumer
1540 /// device, stamped `target_backend = SOURCE` (Cpu, the H2D wrapper) with
1541 /// its output placed on the consumer device.
1542 #[test]
1543 fn residency_one_copy_per_crossing_deduped() {
1544 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
1545 let mut g = Graph::new();
1546 let c1 = f32_node(&mut g, Op::Const, vec![]);
1547 let neg = f32_node(&mut g, Op::Neg, vec![c1]);
1548 let sqr = f32_node(&mut g, Op::Sqr, vec![c1]);
1549 g.set_target_backend(neg, BackendId::Cuda);
1550 g.set_target_backend(sqr, BackendId::Cuda);
1551 let residency = |id: NodeId| (id == c1).then_some(DeviceLocation::Cpu);
1552
1553 let pre = g.len();
1554 insert_residency_copies(
1555 &mut g,
1556 &[neg, sqr],
1557 &ExecutionPlan::empty(),
1558 cuda0,
1559 Some(&residency),
1560 );
1561
1562 assert_eq!(g.len(), pre + 1, "one crossing → one copy, CSE-deduped");
1563 let neg_in = g.node(neg).inputs[0];
1564 let sqr_in = g.node(sqr).inputs[0];
1565 assert_eq!(neg_in, sqr_in, "both consumers share the one copy");
1566 assert_ne!(neg_in, c1, "consumers rewired off the raw input");
1567 let copy = g.node(neg_in);
1568 assert!(
1569 matches!(copy.op, Op::Copy { target } if target == cuda0),
1570 "copy targets the consumer device; got {:?}",
1571 copy.op,
1572 );
1573 assert_eq!(copy.inputs, vec![c1], "copy reads the resident slot");
1574 assert_eq!(
1575 g.target_backend(neg_in),
1576 Some(BackendId::Cpu),
1577 "stamped with the SOURCE backend (H2D runs on the CPU wrapper)",
1578 );
1579 assert_eq!(
1580 g.placement(neg_in),
1581 Some(cuda0),
1582 "copy output placed on the consumer device",
1583 );
1584 }
1585
1586 /// Idempotence + re-stamp: a second pass on the rewritten graph inserts
1587 /// nothing and restores the source-backend stamp even after a clobber
1588 /// (mimicking `stamp_plan_backends` overwriting it with the pinned backend).
1589 #[test]
1590 fn residency_idempotent_and_restamped_on_second_call() {
1591 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
1592 let mut g = Graph::new();
1593 let c1 = f32_node(&mut g, Op::Const, vec![]);
1594 let neg = f32_node(&mut g, Op::Neg, vec![c1]);
1595 g.set_target_backend(neg, BackendId::Cuda);
1596 let residency = |id: NodeId| (id == c1).then_some(DeviceLocation::Cpu);
1597
1598 insert_residency_copies(
1599 &mut g,
1600 &[neg],
1601 &ExecutionPlan::empty(),
1602 cuda0,
1603 Some(&residency),
1604 );
1605 let copy_id = g.node(neg).inputs[0];
1606 // Simulate stamp_plan_backends clobbering the copy with the pinned backend.
1607 g.set_target_backend(copy_id, BackendId::Cuda);
1608
1609 let pre = g.len();
1610 insert_residency_copies(
1611 &mut g,
1612 &[neg],
1613 &ExecutionPlan::empty(),
1614 cuda0,
1615 Some(&residency),
1616 );
1617 assert_eq!(g.len(), pre, "re-run inserts nothing");
1618 assert_eq!(
1619 g.target_backend(copy_id),
1620 Some(BackendId::Cpu),
1621 "re-stamp sweep restores the source-backend stamp",
1622 );
1623 }
1624
1625 // ---- Step E Phase C, PR C-0: arm residency-copy audit ----
1626 //
1627 // C2 lets the executor re-pick an `Op::Branch` arm at runtime by live
1628 // device load — it may choose arm-1+ instead of the static arm-0 winner.
1629 // That is only legal if the optimizer's residency pass has ALREADY
1630 // stitched the inbound cross-device `Op::Copy` for EVERY surviving arm,
1631 // so whichever arm the executor picks, that arm's device-inputs are
1632 // resident on its device. This test builds a 2-arm diamond whose two arms
1633 // live on DIFFERENT devices (arm-0 CPU, arm-1 CUDA) sharing one CPU
1634 // producer, runs the residency pass, and asserts BOTH arms' cross-device
1635 // inputs got their copy — not just arm-0's.
1636 //
1637 // The finalized `Op::Branch` is orphaned (its `reconverge_at` reads arm-0
1638 // directly, per the PR-A1 runnability invariant), so arm-1 is reachable
1639 // ONLY through the Branch node. `insert_residency_copies` walks
1640 // `topo_order_multi(roots)` directly (NOT `effective_roots`), so it never
1641 // reaches an orphaned Branch — and therefore never reaches arm-1. The
1642 // run/route machinery (`extract_runs_multi`, `branches_in_topo_order`)
1643 // does use `effective_roots`; the residency pass does not. This is the
1644 // C-0 prerequisite gap.
1645
1646 /// Build a 2-arm diamond: a CPU producer `diverge` fans into arm-0 (CPU)
1647 /// and arm-1 (`arm1_loc`); `reconverge` reads arm-0 (the runnability
1648 /// invariant); the Branch merges {arm0, arm1} at `reconverge`. Returns
1649 /// `(graph, branch, diverge, arm0, arm1, post)`. Placements are set via
1650 /// `set_placement` so the residency pass reads them with no plan/winner.
1651 fn residency_diamond(
1652 arm1_loc: DeviceLocation,
1653 ) -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId) {
1654 let mut g = Graph::new();
1655 let pre = f32_node(&mut g, Op::Const, vec![]);
1656 let diverge = f32_node(&mut g, Op::Relu, vec![pre]);
1657 let arm0 = f32_node(&mut g, Op::Silu, vec![diverge]);
1658 let arm1 = f32_node(&mut g, Op::GeluTanh, vec![diverge]);
1659 let reconverge = f32_node(&mut g, Op::Relu, vec![arm0]);
1660 let mut b = g.open_branch(diverge);
1661 b.add_arm(arm0);
1662 b.add_arm(arm1);
1663 let branch = b
1664 .finalize_branches(&mut g, reconverge)
1665 .expect("well-formed 2-arm branch")
1666 .expect("2 arms survive");
1667 let post = f32_node(&mut g, Op::Tanh, vec![reconverge]);
1668 // Producer + arm-0 + the post-merge region on CPU; arm-1 elsewhere.
1669 g.set_placement(pre, DeviceLocation::Cpu);
1670 g.set_placement(diverge, DeviceLocation::Cpu);
1671 g.set_placement(arm0, DeviceLocation::Cpu);
1672 g.set_placement(reconverge, DeviceLocation::Cpu);
1673 g.set_placement(post, DeviceLocation::Cpu);
1674 g.set_placement(arm1, arm1_loc);
1675 (g, branch, diverge, arm0, arm1, post)
1676 }
1677
1678 /// C-0 PREREQUISITE: the residency pass must insert the inbound
1679 /// cross-device `Op::Copy` for BOTH arms of a 2-device branch — arm-0
1680 /// (CPU, same device as the producer ⇒ no copy needed) AND arm-1 (CUDA,
1681 /// crosses ⇒ MUST get a copy). If only arm-0 were stitched, re-picking
1682 /// arm-1 at runtime (C2) would dispatch a CUDA kernel whose input was
1683 /// never copied to the GPU → the un-bridged-mixed-edge error / a UAF.
1684 #[test]
1685 fn residency_stitches_every_branch_arm_not_just_arm0() {
1686 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
1687 let (mut g, _branch, diverge, arm0, arm1, post) = residency_diamond(cuda0);
1688
1689 insert_residency_copies(
1690 &mut g,
1691 &[post],
1692 &ExecutionPlan::empty(),
1693 DeviceLocation::Cpu,
1694 None,
1695 );
1696
1697 // arm-0 is CPU, same substrate as the CPU producer ⇒ its input edge
1698 // does NOT cross ⇒ no copy (and must stay reading `diverge`).
1699 assert_eq!(
1700 g.node(arm0).inputs,
1701 vec![diverge],
1702 "arm-0 is co-located with its producer ⇒ no copy, edge untouched",
1703 );
1704
1705 // arm-1 is CUDA, its producer `diverge` is CPU ⇒ the edge crosses ⇒
1706 // the residency pass MUST have inserted an Op::Copy targeting CUDA on
1707 // arm-1's input. THIS is the C-0 invariant: every surviving arm's
1708 // device-inputs are made resident, not just arm-0's.
1709 let arm1_in = g.node(arm1).inputs[0];
1710 assert_ne!(
1711 arm1_in, diverge,
1712 "arm-1 (CUDA) reads the CPU producer directly — its inbound \
1713 cross-device Op::Copy was NEVER inserted. Re-picking arm-1 at \
1714 runtime (C2) would dispatch a CUDA kernel over un-copied CPU \
1715 bytes. The residency pass stitched only arm-0's route.",
1716 );
1717 let copy = g.node(arm1_in);
1718 assert!(
1719 matches!(copy.op, Op::Copy { target } if target == cuda0),
1720 "arm-1's inbound copy must target CUDA; got {:?}",
1721 copy.op,
1722 );
1723 assert_eq!(
1724 copy.inputs,
1725 vec![diverge],
1726 "arm-1's copy reads the shared CPU producer",
1727 );
1728 }
1729
1730 // ---- PR-A4 deliberate-fork-seed test substrate ----
1731
1732 fn noop_kernel_b(
1733 _i: &[Arc<RwLock<Storage>>],
1734 _o: &mut [Arc<RwLock<Storage>>],
1735 _l: &[Layout],
1736 _p: &OpParams,
1737 ) -> FuelResult<()> {
1738 Ok(())
1739 }
1740
1741 /// Register a CPU AND a (synthetic) CUDA binding for `op` so a node
1742 /// enumerated against both placements gets two viable
1743 /// `(backend, device)` candidates — the genuine placement fork the
1744 /// A4 pathfinder seeds a branch from.
1745 fn register_two_backend(table: &mut KernelBindingTable, op: OpKind, n_in: usize) {
1746 let mut dtypes = vec![DType::F32; n_in];
1747 dtypes.push(DType::F32);
1748 table.register_full(
1749 op,
1750 &dtypes,
1751 BackendId::Cpu,
1752 noop_kernel,
1753 KernelCaps::empty(),
1754 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1755 unknown_cost,
1756 );
1757 table.register_full(
1758 op,
1759 &dtypes,
1760 BackendId::Cuda,
1761 noop_kernel_b,
1762 KernelCaps::empty(),
1763 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1764 unknown_cost,
1765 );
1766 }
1767
1768 fn two_backend_placements(dev: DeviceLocation) -> Vec<BackendId> {
1769 if dev == DeviceLocation::Cpu {
1770 vec![BackendId::Cpu, BackendId::Cuda]
1771 } else {
1772 vec![]
1773 }
1774 }
1775
1776 /// Two backends co-located at the realize device, so every
1777 /// kernel-bearing node enumerates ≥2 placements — the multi-backend
1778 /// build the A4 pathfinder forks on. CPU-only builds (one placement
1779 /// per node) never hit this; the equivalence/idempotence gates above
1780 /// cover that.
1781 fn two_backend_opts() -> PlanOptions<'static> {
1782 PlanOptions::new()
1783 .without_cost_population()
1784 .with_pinned_device(DeviceLocation::Cpu)
1785 .with_placements_for_device(&two_backend_placements)
1786 }
1787
1788 /// A graph with a single kernel-bearing node that has a genuine
1789 /// ≥2-placement choice AND exactly one consumer (so it is a
1790 /// deliberate fork, not plain fan-out). Only `fork`'s op (`Silu`) is
1791 /// registered on two backends, so it is the ONLY node with a real
1792 /// ≥2-placement choice — exactly the "most ops are CPU-only, the
1793 /// matmul has cuBLAS too" shape.
1794 ///
1795 /// A long CPU-only `Relu` body surrounds the fork so the single
1796 /// deliberate branch sits far below the fewness threshold (a tiny
1797 /// graph would be all-branch by node count): `c -> body* -> prod ->
1798 /// fork -> tail -> body*`. `prod` is the diverge; `tail` is the
1799 /// reconverge (it reads `fork`).
1800 fn build_single_fork_graph(
1801 table: &mut KernelBindingTable,
1802 ) -> (Graph, NodeId, NodeId, NodeId, NodeId) {
1803 register_elementwise(table, OpKind::ReluElementwise, 1);
1804 register_two_backend(table, OpKind::SiluElementwise, 1); // the fork
1805 register_elementwise(table, OpKind::TanhElementwise, 1);
1806
1807 let mut g = Graph::new();
1808 let mut prev = f32_node(&mut g, Op::Const, vec![]);
1809 // Straight-line CPU body before the fork.
1810 for _ in 0..20 {
1811 prev = f32_node(&mut g, Op::Relu, vec![prev]);
1812 }
1813 let prod = prev; // the diverge (fork's producer)
1814 let fork = f32_node(&mut g, Op::Silu, vec![prod]);
1815 let tail = f32_node(&mut g, Op::Tanh, vec![fork]); // reconverge
1816 // Straight-line CPU body after the reconverge — the realize root
1817 // is the body's tail, so the whole graph is reachable and the
1818 // single fork sits far below the fewness threshold.
1819 let mut prev = tail;
1820 for _ in 0..20 {
1821 prev = f32_node(&mut g, Op::Relu, vec![prev]);
1822 }
1823 let root = prev;
1824 (g, prod, fork, tail, root)
1825 }
1826
1827 /// THE A4 DELIBERATE-FORK GATE (born-red until the pathfinder
1828 /// emits a Branch).
1829 ///
1830 /// (a) A node with two viable `(backend, device)` placements and a
1831 /// single consumer ⇒ `optimize_graph` emits exactly ONE 2-arm
1832 /// `Op::Branch` whose arm-0 is the DP winner, and the result passes
1833 /// the fewness gate.
1834 #[test]
1835 fn deliberate_fork_emits_one_two_arm_branch() {
1836 use fuel_graph::{branch_density, passes_fewness_gate};
1837 let mut table = KernelBindingTable::new();
1838 let (mut g, _prod, fork, _tail, root) = build_single_fork_graph(&mut table);
1839 let opts = two_backend_opts();
1840
1841 let nodes_before = g.len();
1842 let optimized = optimize_graph(&mut g, &[root], &table, &opts)
1843 .expect("optimize_graph succeeds on a 2-placement graph");
1844
1845 // Exactly one Op::Branch in the arena.
1846 assert_eq!(
1847 optimized.branch_count(&g),
1848 1,
1849 "a single genuine placement fork emits exactly one Op::Branch",
1850 );
1851
1852 // It is a 2-arm branch (arm-0 = the winner = `fork`).
1853 let branch_id = (nodes_before..g.len())
1854 .map(NodeId)
1855 .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
1856 .expect("a Branch node was appended");
1857 let branch = g.node(branch_id);
1858 assert_eq!(branch.inputs.len(), 2, "the branch has exactly two arms");
1859 assert_eq!(
1860 branch.inputs[0], fork,
1861 "arm-0 is the DP winner node (the route realize uses today)",
1862 );
1863 assert_ne!(
1864 branch.inputs[1], fork,
1865 "arm-1 is a distinct (runner-up placement) node",
1866 );
1867
1868 // The fewness gate holds — one branch among many nodes.
1869 assert!(
1870 passes_fewness_gate(&g, root),
1871 "a single deliberate fork passes the fewness gate; density={}",
1872 branch_density(&g, root),
1873 );
1874 }
1875
1876 /// (b) An ordinary DAG fan-out (one result, two distinct consumers)
1877 /// with the SAME 2-placement freedom is NOT flagged as a branch —
1878 /// fan-out is not a decision point.
1879 #[test]
1880 fn plain_fan_out_is_not_a_branch() {
1881 let mut table = KernelBindingTable::new();
1882 // Only the fan-out node's op (`Relu`) is dual-backend, so it is
1883 // the sole ≥2-placement candidate — and it is excluded purely
1884 // because it fans out (two consumers), not because it lacks a
1885 // placement choice. The consumers are CPU-only.
1886 register_two_backend(&mut table, OpKind::ReluElementwise, 1);
1887 register_elementwise(&mut table, OpKind::SiluElementwise, 1);
1888 register_elementwise(&mut table, OpKind::TanhElementwise, 1);
1889 register_elementwise(&mut table, OpKind::AddElementwise, 2);
1890
1891 // `shared` has two distinct consumers (c0, c1) that join at
1892 // `out` — plain fan-out, not a fork — even though it has a real
1893 // 2-placement choice.
1894 let mut g = Graph::new();
1895 let c = f32_node(&mut g, Op::Const, vec![]);
1896 let shared = f32_node(&mut g, Op::Relu, vec![c]);
1897 let c0 = f32_node(&mut g, Op::Silu, vec![shared]);
1898 let c1 = f32_node(&mut g, Op::Tanh, vec![shared]);
1899 let out = f32_node(&mut g, Op::Add, vec![c0, c1]);
1900 let opts = two_backend_opts();
1901
1902 let optimized =
1903 optimize_graph(&mut g, &[out], &table, &opts).expect("optimize_graph succeeds");
1904 assert_eq!(
1905 optimized.branch_count(&g),
1906 0,
1907 "plain fan-out (multiple consumers) is not a deliberate fork",
1908 );
1909 let _ = shared;
1910 }
1911
1912 /// (c) A branched graph realizes correctly via arm-0: the dispatch
1913 /// order follows {pre, arm-0, post} and SKIPS arm-1's run.
1914 #[test]
1915 fn branched_graph_realizes_via_arm0() {
1916 let mut table = KernelBindingTable::new();
1917 let (mut g, prod, fork, tail, root) = build_single_fork_graph(&mut table);
1918 let opts = two_backend_opts();
1919
1920 // Capture the single-route order BEFORE the branch is emitted —
1921 // this is the order realize must reproduce on arm-0.
1922 let pre_order = execution_plan(&g, &[root]);
1923
1924 let optimized =
1925 optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
1926 assert_eq!(optimized.branch_count(&g), 1, "exactly one branch");
1927
1928 // The arm-1 node is the branch's second input — it must NOT
1929 // appear in the arm-0 dispatch order.
1930 let branch_id = (0..g.len())
1931 .map(NodeId)
1932 .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
1933 .expect("a Branch node exists");
1934 let arm1 = g.node(branch_id).inputs[1];
1935
1936 let order = optimized.dispatch_order(&g);
1937 assert!(
1938 !order.contains(&arm1),
1939 "arm-0 lowering must skip arm-1's run; order={order:?} arm1={arm1:?}",
1940 );
1941 // arm-0 (fork) and the pre/post nodes ARE executed.
1942 assert!(order.contains(&prod), "pre-run (diverge producer) executes");
1943 assert!(order.contains(&fork), "arm-0 (the winner) executes");
1944 assert!(order.contains(&tail), "post-run (reconverge) executes");
1945 assert!(order.contains(&root), "the realize root executes");
1946
1947 // Behavior preserving: arm-0 lowering reproduces exactly the
1948 // pre-branch single-route order (arm-0 = the DP winner = the
1949 // graph realize used before the branch was recorded).
1950 assert_eq!(
1951 order, pre_order,
1952 "arm-0 dispatch order equals the pre-branch single-route order",
1953 );
1954 }
1955
1956 /// Return type of [`cached_env_test_fixture`] — named purely to dodge
1957 /// `clippy::type_complexity`, not because any caller needs the alias.
1958 type CachedEnvTestFixture = (
1959 Arc<RwLock<Graph>>,
1960 crate::pipelined::StorageCache,
1961 OptimizedGraph,
1962 std::sync::OnceLock<Vec<NodeId>>,
1963 Arc<dyn crate::ranker::RuntimeSelector>,
1964 NodeId,
1965 );
1966
1967 /// Shared setup for the two `cached_env_*` tests below: a single-fork
1968 /// graph, a two-backend `OptimizedGraph`, a seeded `StorageCache`, a
1969 /// fresh `order_cache`, and a real (non-stub) `WinnerSelector`.
1970 /// Factored out purely to keep each test under Codacy's method-length
1971 /// bound — no behavior lives here that either test's own body needs to
1972 /// see inline.
1973 fn cached_env_test_fixture() -> CachedEnvTestFixture {
1974 use crate::pipelined::StorageCache;
1975 use crate::ranker::runtime_selector::WinnerSelector;
1976
1977 let mut table = KernelBindingTable::new();
1978 let (mut g, _prod, _fork, _tail, root) = build_single_fork_graph(&mut table);
1979 let opts = two_backend_opts();
1980 let optimized =
1981 optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
1982 assert_eq!(optimized.branch_count(&g), 1, "exactly one branch");
1983
1984 let graph = Arc::new(RwLock::new(g));
1985 let mut cache = StorageCache::new();
1986 cache.insert(
1987 NodeId(0), // the leaf Const build_single_fork_graph pushes first.
1988 Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
1989 1.0_f32, 2.0, 3.0, 4.0,
1990 ]))),
1991 );
1992 let order_cache: std::sync::OnceLock<Vec<NodeId>> = std::sync::OnceLock::new();
1993 let selector: Arc<dyn crate::ranker::RuntimeSelector> = Arc::new(WinnerSelector);
1994 (graph, cache, optimized, order_cache, selector, root)
1995 }
1996
1997 /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
1998 /// §5), answering the PM's review question directly: on a graph with a
1999 /// REAL `Op::Branch` and a REAL selector (so the executor's picking
2000 /// entry point resolves a genuine pick, not just "no branches to
2001 /// pick"), `realize_with_optimized_picking_cached_env` must route
2002 /// through `OrderSource::Streaming`, NEVER through `OrderSource::Cached`
2003 /// — proven here by checking `order_cache` stays EMPTY across two
2004 /// separate picking realizes, not merely by reading the routing code.
2005 /// This is the stronger property PR review asked for: the fix doesn't
2006 /// need a cache key that "covers the pick" because picked graphs never
2007 /// reach the cache in the first place — `realize_with_optimized_picking_env`'s
2008 /// OWN routing (`streaming_pick_for` returning `Some` whenever a
2009 /// selector is given over a branched graph) already excludes them, and
2010 /// this test is what proves that exclusion actually holds for the
2011 /// cached sibling too, not just the uncached original.
2012 ///
2013 /// `result`/`result2` tolerate `Error::TopologyChanged` as a passing
2014 /// outcome, not just `Ok`: `optimized.generation` is stamped once, from
2015 /// the process-wide `topology_generation()` counter, at `optimize_graph`
2016 /// time above — and that counter is shared by every test in this binary
2017 /// (`register_runtime_kernel`/`extend_global_bindings`'s own doc admits
2018 /// this; see `register_runtime_kernel_into`'s test-only escape hatch).
2019 /// A sibling test registering a runtime-fused kernel between here and
2020 /// either realize call bumps it, and `realize_inner`'s chunk-boundary
2021 /// check (pipelined.rs) deliberately does NOT retry at this layer —
2022 /// only `pipelined_bridge`'s wrapper does (by design, so a low-level
2023 /// `PipelinedExecutor` caller sees the typed error, not a silent stall).
2024 /// A real retry would need a fresh `optimize_graph` call, which would
2025 /// defeat this test's actual subject (whether the same `OptimizedGraph`
2026 /// and `order_cache` stay consistent across repeat calls), so instead
2027 /// of retrying we just don't fail on the one outcome this test was
2028 /// never about. The `order_cache`-emptiness assertions stay
2029 /// unconditional: the `Streaming` path never touches `order_cache`
2030 /// regardless of whether the realize that invoked it succeeded or hit
2031 /// this race.
2032 #[test]
2033 fn cached_env_never_caches_a_branched_graph_with_a_real_selector() {
2034 use crate::PipelinedExecutor;
2035 use fuel_ir::{Error, SymEnv};
2036
2037 let (graph, cache, optimized, order_cache, selector, root) = cached_env_test_fixture();
2038
2039 let result = PipelinedExecutor::realize_with_optimized_picking_cached_env(
2040 graph.clone(),
2041 root,
2042 cache.clone(),
2043 &optimized,
2044 &order_cache,
2045 Some(selector.clone()),
2046 None,
2047 SymEnv::default(),
2048 );
2049 assert!(
2050 result.is_ok()
2051 || matches!(
2052 result.as_ref().map_err(Error::root_cause),
2053 Err(Error::TopologyChanged { .. })
2054 ),
2055 "a picked realize over a branched graph must either succeed or hit the \
2056 (unrelated, expected-under-concurrency) TopologyChanged race: {:?}",
2057 result.err()
2058 );
2059 assert!(
2060 order_cache.get().is_none(),
2061 "a branched graph with a real selector pick must NEVER populate order_cache — \
2062 it must route through OrderSource::Streaming, not OrderSource::Cached",
2063 );
2064
2065 // A second call, same cache slot: still must not populate it.
2066 let result2 = PipelinedExecutor::realize_with_optimized_picking_cached_env(
2067 graph,
2068 root,
2069 cache,
2070 &optimized,
2071 &order_cache,
2072 Some(selector),
2073 None,
2074 SymEnv::default(),
2075 );
2076 assert!(
2077 result2.is_ok()
2078 || matches!(
2079 result2.as_ref().map_err(Error::root_cause),
2080 Err(Error::TopologyChanged { .. })
2081 ),
2082 "second picked realize must either succeed or hit the same expected-under- \
2083 concurrency TopologyChanged race: {:?}",
2084 result2.err()
2085 );
2086 assert!(
2087 order_cache.get().is_none(),
2088 "order_cache must still be empty after a second picked realize",
2089 );
2090 }
2091
2092 /// Deterministic sibling of the test above: forces the EXACT race
2093 /// `Error::TopologyChanged` tolerance was added for, instead of relying
2094 /// on another test in the binary to collide by chance. Proves two
2095 /// things the flaky-under-`-j4` observation alone couldn't: (1) that a
2096 /// stale `optimized.generation` is SUFFICIENT to reproduce the exact
2097 /// failure this test's sibling hit (confirming the root cause, not
2098 /// just a plausible story), and (2) that `order_cache` stays empty
2099 /// even on the `Err` branch (the property this test file is actually
2100 /// about, independent of the race).
2101 ///
2102 /// Deliberately does NOT call the real, process-wide
2103 /// `bump_topology_generation()` to force this — that would inflict the
2104 /// exact `-j4` cross-test hazard this test documents onto every OTHER
2105 /// concurrently-running test in the binary that assumes a stable
2106 /// generation (an earlier draft of this test did exactly that, and
2107 /// broke `realize_with_optimized_picking_cached_env_matches_arm0_cold_and_warm`
2108 /// under `-j4`). `OptimizedGraph::generation` is `pub`, so mutating
2109 /// this test's own LOCAL copy to a value that can't match the live
2110 /// counter reproduces the identical code path with zero blast radius.
2111 #[test]
2112 fn cached_env_tolerates_a_concurrent_topology_generation_bump() {
2113 use crate::PipelinedExecutor;
2114 use fuel_ir::{Error, SymEnv};
2115
2116 let (graph, cache, mut optimized, order_cache, selector, root) = cached_env_test_fixture();
2117
2118 // Simulate a sibling test's legitimate `register_runtime_kernel`/
2119 // `extend_global_bindings` call landing between `optimize_graph`
2120 // (which stamped `optimized.generation` above) and this realize —
2121 // exactly the collision `cached_env_never_caches_a_branched_graph_with_a_real_selector`
2122 // hit under `-j4` — by staling THIS test's own copy of the stamp,
2123 // not the shared live counter every other test also reads.
2124 optimized.generation = optimized.generation.wrapping_add(1);
2125
2126 let result = PipelinedExecutor::realize_with_optimized_picking_cached_env(
2127 graph,
2128 root,
2129 cache,
2130 &optimized,
2131 &order_cache,
2132 Some(selector),
2133 None,
2134 SymEnv::default(),
2135 );
2136 assert!(
2137 matches!(
2138 result.as_ref().map_err(Error::root_cause),
2139 Err(Error::TopologyChanged { .. })
2140 ),
2141 "a forced generation bump before realize must surface as TopologyChanged, \
2142 not silently succeed or fail some other way: {:?}",
2143 result
2144 );
2145 assert!(
2146 order_cache.get().is_none(),
2147 "order_cache must stay empty even when the realize that would have \
2148 populated it (if it were ever going to) failed with TopologyChanged",
2149 );
2150 }
2151
2152 /// (d) No `DEFAULT_MAX_N` truncation: the fork records the winner +
2153 /// a runner-up without a fixed top-N cap stranding placements. Both
2154 /// arms survive; the per-device frontier — not a fixed N — bounds
2155 /// the arms.
2156 #[test]
2157 fn no_default_max_n_truncation() {
2158 let mut table = KernelBindingTable::new();
2159 let (mut g, _prod, fork, _tail, root) = build_single_fork_graph(&mut table);
2160 let opts = two_backend_opts();
2161
2162 let optimized =
2163 optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
2164 assert_eq!(optimized.branch_count(&g), 1);
2165 let branch_id = (0..g.len())
2166 .map(NodeId)
2167 .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
2168 .expect("a Branch node exists");
2169 // Two distinct placements ⇒ two arms survive; the runner-up was
2170 // not dropped by any top-N cap.
2171 assert_eq!(g.node(branch_id).inputs.len(), 2);
2172 assert_eq!(g.node(branch_id).inputs[0], fork);
2173 }
2174
2175 /// THE EQUIVALENCE GATE (born-red until `optimize_graph` exists and
2176 /// its lowered order matches `compile_plan`).
2177 ///
2178 /// On representative no-competing-route graphs, assert:
2179 /// (a) `optimize_graph` leaves ZERO `Op::Branch` nodes, and
2180 /// (b) the concatenated `extract_runs`/`lower_run` dispatch order
2181 /// EQUALS today's `compile_plan(...).order` exactly (same
2182 /// NodeIds, same order).
2183 #[test]
2184 fn equivalence_gate_branchless_order_matches_compile_plan() {
2185 for build in [
2186 build_straight_line_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2187 build_branchless_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2188 ] {
2189 let mut table = KernelBindingTable::new();
2190 let (mut g, root) = build(&mut table);
2191 let opts = cpu_opts();
2192
2193 // Today's path: the exact order the executor walks.
2194 let order = execution_plan(&g, &[root]);
2195 let plan = compile_plan(&g, &order, &table, &opts)
2196 .expect("today's compile_plan succeeds on a placeable graph");
2197
2198 // New path.
2199 let optimized = optimize_graph(&mut g, &[root], &table, &opts)
2200 .expect("optimize_graph succeeds on the same graph");
2201
2202 // (a) zero competing routes => zero Branch nodes.
2203 assert_eq!(
2204 optimized.branch_count(&g),
2205 0,
2206 "a no-competing-route graph optimizes to zero Op::Branch nodes",
2207 );
2208
2209 // (b) EXACT order equality against compile_plan(...).order.
2210 let lowered = optimized.dispatch_order(&g);
2211 assert_eq!(
2212 lowered, plan.order,
2213 "the extract_runs/lower_run dispatch order must equal \
2214 compile_plan(...).order exactly (same NodeIds, same order)",
2215 );
2216 // And it covers every reachable node — the executor walks
2217 // the whole graph, runs partition it with no gaps/dupes.
2218 assert_eq!(
2219 lowered.len(),
2220 order.len(),
2221 "the lowered order covers every node compile_plan ordered",
2222 );
2223 }
2224 }
2225
2226 /// `optimize_graph` on a branchless graph is idempotent and adds no
2227 /// nodes: the node count is unchanged across repeated calls, the
2228 /// branch count stays zero, and the lowered order is stable.
2229 #[test]
2230 fn optimize_graph_branchless_is_idempotent_and_adds_no_nodes() {
2231 let mut table = KernelBindingTable::new();
2232 let (mut g, root) = build_branchless_graph(&mut table);
2233 let opts = cpu_opts();
2234
2235 let nodes_before = g.len();
2236 let first =
2237 optimize_graph(&mut g, &[root], &table, &opts).expect("first optimize succeeds");
2238 let order_first = first.dispatch_order(&g);
2239 let nodes_after_first = g.len();
2240
2241 let second =
2242 optimize_graph(&mut g, &[root], &table, &opts).expect("second optimize succeeds");
2243 let order_second = second.dispatch_order(&g);
2244 let nodes_after_second = g.len();
2245
2246 assert_eq!(
2247 nodes_before, nodes_after_first,
2248 "optimize_graph adds no nodes (A3a is single-route-only)",
2249 );
2250 assert_eq!(
2251 nodes_after_first, nodes_after_second,
2252 "a second optimize_graph adds no further nodes — idempotent",
2253 );
2254 assert_eq!(first.branch_count(&g), 0, "no branches after first");
2255 assert_eq!(second.branch_count(&g), 0, "no branches after second");
2256 assert_eq!(
2257 order_first, order_second,
2258 "the lowered dispatch order is stable across repeated optimize",
2259 );
2260 }
2261
2262 /// Identity proof for `docs/design/incremental-consumer-index.md` §5's
2263 /// `order_for` fix track: that fix proposes memoizing `dispatch_order`'s
2264 /// output WHOLESALE once per plan-once session, instead of recomputing
2265 /// it (via `extract_runs_multi` + `non_chosen_arm_nodes`, measured
2266 /// ~56ms/step, the single largest named sub-cost in a live decode step)
2267 /// on every `realize_inner` call. That's only valid if calling
2268 /// `dispatch_order` repeatedly on the SAME `OptimizedGraph` view with NO
2269 /// intervening graph mutation — exactly the plan-once decode shape,
2270 /// where only leaf values are rebound between tokens, never the graph's
2271 /// structure — yields a byte-identical `Vec<NodeId>` every time. Proven
2272 /// here, not assumed: five repeated calls, two structurally different
2273 /// branchless graphs (a fan-in boundary and a plain chain), zero
2274 /// mutation between calls (deliberately — this is NOT the existing
2275 /// `optimize_graph_branchless_is_idempotent_and_adds_no_nodes` test
2276 /// above, which re-runs `optimize_graph` itself between its two
2277 /// `dispatch_order` calls; this one proves `dispatch_order` is pure on
2278 /// its own, independent of re-optimizing).
2279 #[test]
2280 fn dispatch_order_is_stable_across_repeated_calls_with_no_mutation() {
2281 for build in [
2282 build_branchless_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2283 build_straight_line_graph,
2284 ] {
2285 let mut table = KernelBindingTable::new();
2286 let (mut g, root) = build(&mut table);
2287 let opts = cpu_opts();
2288 let optimized = optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph");
2289
2290 let orders: Vec<Vec<NodeId>> = (0..5).map(|_| optimized.dispatch_order(&g)).collect();
2291 for (i, order) in orders.iter().enumerate().skip(1) {
2292 assert_eq!(
2293 &orders[0], order,
2294 "dispatch_order call {i} diverged from call 0 with no intervening \
2295 mutation — the order_for memoization fix would be UNSAFE if this failed",
2296 );
2297 }
2298 }
2299 }
2300
2301 /// Build-time validation: optimize_graph fails fast (Result, never
2302 /// panic) when a kernel-bearing node has no registered binding —
2303 /// reusing compile_plan's missing-binding diagnostic.
2304 #[test]
2305 fn optimize_graph_fails_fast_on_missing_binding() {
2306 let table = KernelBindingTable::new(); // empty — no bindings.
2307 let mut g = Graph::new();
2308 let a = f32_node(&mut g, Op::Const, vec![]);
2309 let relu = f32_node(&mut g, Op::Relu, vec![a]);
2310 let opts = cpu_opts();
2311
2312 let err = optimize_graph(&mut g, &[relu], &table, &opts)
2313 .map(|_| ())
2314 .unwrap_err();
2315 match err {
2316 fuel_ir::Error::NoBackendForOp { op, .. } => {
2317 assert_eq!(op, OpKind::ReluElementwise);
2318 }
2319 other => panic!("expected NoBackendForOp, got {other:?}"),
2320 }
2321 }
2322
2323 // ===== Phase B PR-B3: the lock-step pathfinder/ranker/optimizer
2324 // driver. =====
2325
2326 use crate::driver::{
2327 FrontierConvergenceOptimizer, OptimizationContext, Optimizer, PassRegistry, Pathfinder,
2328 PlacementForkPathfinder,
2329 };
2330 use std::collections::HashSet;
2331
2332 /// Snapshot of a graph's `Op::Branch` decision points, keyed by
2333 /// arena order: `(branch_id, reconverge_at, arm NodeIds)`. Two
2334 /// optimization paths that produce the same snapshot produced the
2335 /// same multi-path graph (behavior-preservation).
2336 fn branch_snapshot(g: &Graph) -> Vec<(NodeId, NodeId, Vec<NodeId>)> {
2337 (0..g.len())
2338 .map(NodeId)
2339 .filter_map(|id| match g.node(id).op {
2340 Op::Branch { reconverge_at } => {
2341 Some((id, reconverge_at, g.node(id).inputs.clone()))
2342 }
2343 _ => None,
2344 })
2345 .collect()
2346 }
2347
2348 /// THE LOAD-BEARING BEHAVIOR-PRESERVATION GATE (born-red until
2349 /// `optimize_graph` routes through the lock-step driver).
2350 ///
2351 /// On a representative multi-placement graph, the driver
2352 /// (`PassRegistry::default_passes().run_lockstep`) produces the
2353 /// **identical** multi-path graph as the old hardcoded sequence
2354 /// (pathfinder then optimizer, in that order): same branch count,
2355 /// same arm-0 winner, same arms, same reconverge points, and the
2356 /// same arm-0 dispatch order. B3 is a structural refactor — the
2357 /// optimized result must not change.
2358 #[test]
2359 fn driver_matches_legacy_sequence() {
2360 // (A) The reference: drive the registered passes BY HAND in the
2361 // legacy order (propose, then prune) onto a freshly compiled
2362 // plan — exactly what the pre-B3 hardcoded sequence did.
2363 let mut ref_table = KernelBindingTable::new();
2364 let (mut ref_g, _prod, ref_fork, _tail, ref_root) = build_single_fork_graph(&mut ref_table);
2365 let opts = two_backend_opts();
2366 let ref_order = execution_plan(&ref_g, &[ref_root]);
2367 let ref_plan = compile_plan(&ref_g, &ref_order, &ref_table, &opts)
2368 .expect("reference compile_plan succeeds");
2369 {
2370 let guard: HashSet<NodeId> = HashSet::new();
2371 let ctx = OptimizationContext {
2372 order: &ref_order,
2373 plan: &ref_plan,
2374 cycle_guard: &guard,
2375 bindings: &ref_table,
2376 };
2377 // Legacy order: the pathfinder ADDs, then the optimizer
2378 // prunes — the same two operations the hardcoded sequence ran.
2379 PlacementForkPathfinder
2380 .propose(&mut ref_g, &ctx)
2381 .expect("pathfinder proposes");
2382 FrontierConvergenceOptimizer
2383 .prune(&mut ref_g, &ctx)
2384 .expect("optimizer prunes");
2385 }
2386 let ref_snapshot = branch_snapshot(&ref_g);
2387 let ref_dispatch = fuel_graph::lower_runs_arm0(&ref_g, &[ref_root]);
2388
2389 // (B) The driver path: optimize_graph routes through
2390 // PassRegistry::default_passes().run_lockstep.
2391 let mut table = KernelBindingTable::new();
2392 let (mut g, _p, fork, _t, root) = build_single_fork_graph(&mut table);
2393 let optimized =
2394 optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
2395 let got_snapshot = branch_snapshot(&g);
2396 let got_dispatch = optimized.dispatch_order(&g);
2397
2398 // Identical multi-path graph: same branches, arms, reconverge.
2399 assert_eq!(
2400 got_snapshot, ref_snapshot,
2401 "driver produces the identical Op::Branch structure as the legacy \
2402 pathfinder→optimizer sequence",
2403 );
2404 assert_eq!(
2405 got_snapshot.len(),
2406 1,
2407 "the representative multi-placement graph produces exactly one branch",
2408 );
2409 assert_eq!(
2410 got_snapshot[0].2[0], fork,
2411 "arm-0 is the DP winner (the route realize uses)",
2412 );
2413 // Identical dispatch order (arm-0 single-route lowering).
2414 assert_eq!(
2415 got_dispatch, ref_dispatch,
2416 "driver yields the identical arm-0 dispatch order as the legacy sequence",
2417 );
2418 let _ = ref_fork;
2419 }
2420
2421 /// A no-op registry (no registered pathfinders) leaves a branchless
2422 /// graph unchanged: no nodes added, zero branches, identical
2423 /// dispatch order. Proves the driver itself introduces no structure.
2424 #[test]
2425 fn noop_registry_leaves_branchless_graph_unchanged() {
2426 let mut table = KernelBindingTable::new();
2427 let (mut g, root) = build_branchless_graph(&mut table);
2428 let opts = cpu_opts();
2429
2430 let order = execution_plan(&g, &[root]);
2431 let plan = compile_plan(&g, &order, &table, &opts).expect("compile_plan succeeds");
2432
2433 let dispatch_before = fuel_graph::lower_runs_arm0(&g, &[root]);
2434 let nodes_before = g.len();
2435
2436 let registry = PassRegistry::new(); // empty — no passes.
2437 assert_eq!(registry.pathfinder_count(), 0);
2438 assert_eq!(registry.optimizer_count(), 0);
2439
2440 let guard: HashSet<NodeId> = HashSet::new();
2441 let ctx = OptimizationContext {
2442 order: &order,
2443 plan: &plan,
2444 cycle_guard: &guard,
2445 bindings: &table,
2446 };
2447 registry
2448 .run_lockstep(&mut g, &ctx)
2449 .expect("empty registry runs cleanly");
2450
2451 assert_eq!(g.len(), nodes_before, "no-op registry adds no nodes");
2452 let branches = (0..g.len())
2453 .map(NodeId)
2454 .filter(|&id| matches!(g.node(id).op, Op::Branch { .. }))
2455 .count();
2456 assert_eq!(branches, 0, "no-op registry adds no branches");
2457 let dispatch_after = fuel_graph::lower_runs_arm0(&g, &[root]);
2458 assert_eq!(
2459 dispatch_before, dispatch_after,
2460 "no-op registry leaves the dispatch order unchanged",
2461 );
2462 }
2463
2464 /// Lock-step ordering: a pathfinder ADDs before its dependent
2465 /// optimizer PRUNEs. We register a recording pathfinder and a
2466 /// recording optimizer that each stamp a shared log when invoked;
2467 /// `run_lockstep` must invoke the pathfinder strictly before the
2468 /// optimizer (prune-as-you-go, never optimizer-first).
2469 #[test]
2470 fn lockstep_runs_pathfinder_before_dependent_optimizer() {
2471 use std::sync::{Arc, Mutex};
2472
2473 #[derive(Clone)]
2474 struct RecordPathfinder(Arc<Mutex<Vec<&'static str>>>);
2475 impl Pathfinder for RecordPathfinder {
2476 fn name(&self) -> &'static str {
2477 "RecordPathfinder"
2478 }
2479 fn propose(
2480 &self,
2481 _g: &mut Graph,
2482 _ctx: &OptimizationContext<'_>,
2483 ) -> fuel_ir::Result<()> {
2484 self.0.lock().unwrap().push("propose");
2485 Ok(())
2486 }
2487 }
2488 #[derive(Clone)]
2489 struct RecordOptimizer(Arc<Mutex<Vec<&'static str>>>);
2490 impl Optimizer for RecordOptimizer {
2491 fn name(&self) -> &'static str {
2492 "RecordOptimizer"
2493 }
2494 fn prune(&self, _g: &mut Graph, _ctx: &OptimizationContext<'_>) -> fuel_ir::Result<()> {
2495 self.0.lock().unwrap().push("prune");
2496 Ok(())
2497 }
2498 }
2499
2500 let log = Arc::new(Mutex::new(Vec::new()));
2501 let registry = PassRegistry::new()
2502 .with_pathfinder(Box::new(RecordPathfinder(log.clone())))
2503 .with_optimizer(Box::new(RecordOptimizer(log.clone())));
2504
2505 let mut g = Graph::new();
2506 let _a = f32_node(&mut g, Op::Const, vec![]);
2507 let plan = ExecutionPlan::empty();
2508 let order: Vec<NodeId> = Vec::new();
2509 let guard: HashSet<NodeId> = HashSet::new();
2510 let table = KernelBindingTable::new();
2511 let ctx = OptimizationContext {
2512 order: &order,
2513 plan: &plan,
2514 cycle_guard: &guard,
2515 bindings: &table,
2516 };
2517 registry.run_lockstep(&mut g, &ctx).expect("drive runs");
2518
2519 let seq = log.lock().unwrap().clone();
2520 assert_eq!(
2521 seq,
2522 vec!["propose", "prune"],
2523 "lock-step drive runs the pathfinder ADD strictly before its \
2524 dependent optimizer PRUNE (prune-as-you-go)",
2525 );
2526 }
2527
2528 // ---- GAP-380 (a1): lower a fused op with no kernel on the pinned device -------------------
2529
2530 /// `[q, k_cache, v_cache, block_table, context_lens]` consts, a fused PAGED_ATTN, and a
2531 /// `Contiguize` consumer. Returns `(graph, consumer)`.
2532 fn paged_attn_graph() -> (Graph, NodeId) {
2533 use fuel_graph::registry::{FusedOpParams, FusedOps};
2534 let mut g = Graph::new();
2535 let mut leaf = |dims: &[usize], dtype: DType| {
2536 g.push(Node {
2537 op: Op::Const,
2538 inputs: vec![],
2539 shape: Shape::from_dims(dims),
2540 dtype,
2541 })
2542 };
2543 let q = leaf(&[1, 2, 1, 4], DType::F32);
2544 let kc = leaf(&[3, 2, 2, 4], DType::F32);
2545 let vc = leaf(&[3, 2, 2, 4], DType::F32);
2546 let bt = leaf(&[1, 2], DType::U32);
2547 let cl = leaf(&[1], DType::U32);
2548 let fused = g.push(Node {
2549 op: Op::Fused(
2550 FusedOps::PAGED_ATTN,
2551 FusedOpParams::PagedAttn {
2552 softmax_scale: 0.5,
2553 block_size: 2,
2554 softcap: None,
2555 },
2556 ),
2557 inputs: vec![q, kc, vc, bt, cl],
2558 shape: Shape::from_dims(&[1, 2, 1, 4]),
2559 dtype: DType::F32,
2560 });
2561 let consumer = g.push(Node {
2562 op: Op::Contiguize,
2563 inputs: vec![fused],
2564 shape: Shape::from_dims(&[1, 2, 1, 4]),
2565 dtype: DType::F32,
2566 });
2567 (g, consumer)
2568 }
2569
2570 fn paged_attn_nodes(g: &Graph, root: NodeId) -> usize {
2571 topo_order_multi(g, &[root])
2572 .into_iter()
2573 .filter(|&n| {
2574 matches!(
2575 g.node(n).op,
2576 Op::Fused(fuel_graph::registry::FusedOps::PAGED_ATTN, _)
2577 )
2578 })
2579 .count()
2580 }
2581
2582 #[test]
2583 fn a_cuda_pin_with_no_cuda_paged_attn_kernel_lowers_the_fused_node() {
2584 let (mut g, root) = paged_attn_graph();
2585 let opts = PlanOptions::new().with_pinned_device(DeviceLocation::Cuda { gpu_id: 0 });
2586 assert_eq!(
2587 paged_attn_nodes(&g, root),
2588 1,
2589 "PRECONDITION: one fused node"
2590 );
2591 let n = lower_fused_unbound_on_pinned_device(&mut g, &[root], &opts, &|_, _| false);
2592 assert_eq!(n, 1);
2593 assert_eq!(
2594 paged_attn_nodes(&g, root),
2595 0,
2596 "no fused PAGED_ATTN stays reachable"
2597 );
2598 }
2599
2600 /// Sabotage siblings: each condition of the gate, taken away alone, leaves the node fused.
2601 #[test]
2602 fn the_gate_needs_a_cuda_pin_no_bound_kernel_and_a_listed_op() {
2603 // A bound CUDA kernel: keep the fused node (the fast path wins when it exists).
2604 let (mut g, root) = paged_attn_graph();
2605 let cuda = PlanOptions::new().with_pinned_device(DeviceLocation::Cuda { gpu_id: 0 });
2606 assert_eq!(
2607 lower_fused_unbound_on_pinned_device(&mut g, &[root], &cuda, &|_, _| true),
2608 0
2609 );
2610 assert_eq!(paged_attn_nodes(&g, root), 1);
2611 // A CPU pin: the host kernel IS the right place, so nothing lowers.
2612 let (mut g, root) = paged_attn_graph();
2613 let cpu = PlanOptions::new().with_pinned_device(DeviceLocation::Cpu);
2614 assert_eq!(
2615 lower_fused_unbound_on_pinned_device(&mut g, &[root], &cpu, &|_, _| false),
2616 0
2617 );
2618 assert_eq!(paged_attn_nodes(&g, root), 1);
2619 // No pin at all (bare-graph callers): untouched.
2620 let (mut g, root) = paged_attn_graph();
2621 let bare = PlanOptions::new();
2622 assert_eq!(
2623 lower_fused_unbound_on_pinned_device(&mut g, &[root], &bare, &|_, _| false),
2624 0
2625 );
2626 assert_eq!(paged_attn_nodes(&g, root), 1);
2627 }
2628
2629 /// The production predicate is the real registry: CUDA has no PAGED_ATTN kernel today, CPU does.
2630 /// Red the day a CUDA kernel is bound (then the recipe is the slower path and this list must be
2631 /// revisited, which is the point).
2632 #[test]
2633 fn the_registry_has_a_cpu_paged_attn_kernel_and_no_cuda_one() {
2634 let impls = crate::fused::default_kernel_registry()
2635 .impls_for(fuel_graph::registry::FusedOps::PAGED_ATTN);
2636 assert!(
2637 impls
2638 .iter()
2639 .any(|(b, _)| *b == fuel_ir::probe::BackendId::Cpu),
2640 "CONTROL: the registry lookup sees the CPU PAGED_ATTN kernels"
2641 );
2642 assert!(
2643 !impls
2644 .iter()
2645 .any(|(b, _)| *b == fuel_ir::probe::BackendId::Cuda),
2646 "a CUDA PAGED_ATTN kernel is bound: revisit LOWER_WHEN_NO_DEVICE_KERNEL (the fused kernel may now beat the recipe)"
2647 );
2648 }
2649 /// Helper for the row-157 region tests: every kernel op registered on two placements.
2650 fn two_placement_table() -> KernelBindingTable {
2651 let mut table = KernelBindingTable::new();
2652 register_two_backend(&mut table, OpKind::ReluElementwise, 1);
2653 register_two_backend(&mut table, OpKind::SiluElementwise, 1);
2654 register_two_backend(&mut table, OpKind::TanhElementwise, 1);
2655 register_two_backend(&mut table, OpKind::AddElementwise, 2);
2656 table
2657 }
2658
2659 /// `(branch_id, arm-0 exit, reconverge)` of every `Op::Branch` added after `from`.
2660 fn branches_after(g: &Graph, from: usize) -> Vec<(NodeId, NodeId, NodeId)> {
2661 (from..g.len())
2662 .map(NodeId)
2663 .filter_map(|id| match g.node(id).op {
2664 Op::Branch { reconverge_at } => Some((id, g.node(id).inputs[0], reconverge_at)),
2665 _ => None,
2666 })
2667 .collect()
2668 }
2669
2670 /// ROW 157 / GAP-385, RESIDUAL JOIN AND FAN-OUT (born red against the one-node fork, which made
2671 /// 8 one-node forks here and none at `n1` or `res`).
2672 ///
2673 /// A transformer-block-shaped graph, every op on two placements: a residual block whose body fans
2674 /// out (`n1` feeds q, k and v which rejoin through `a` and `b`), then a second residual block.
2675 /// Expect one multi-node region per residual block: block 1 has diverge `x`, a seven-node arm
2676 /// (`n1 q k v a b o`) and reconverge `res`, which reads `x` directly (the residual edge); block 2
2677 /// has diverge `res`, a two-node arm (`n2 m`) and reconverge `res2`.
2678 #[test]
2679 fn transformer_shaped_graph_forks_residual_blocks_as_multi_node_regions() {
2680 let table = two_placement_table();
2681 let mut g = Graph::new();
2682 let x = f32_node(&mut g, Op::Const, vec![]);
2683 let n1 = f32_node(&mut g, Op::Relu, vec![x]); // fan-out: q, k, v
2684 let q = f32_node(&mut g, Op::Silu, vec![n1]);
2685 let k = f32_node(&mut g, Op::Tanh, vec![n1]);
2686 let v = f32_node(&mut g, Op::Relu, vec![n1]);
2687 let a = f32_node(&mut g, Op::Add, vec![q, k]);
2688 let b = f32_node(&mut g, Op::Add, vec![a, v]);
2689 let o = f32_node(&mut g, Op::Silu, vec![b]);
2690 let res = f32_node(&mut g, Op::Add, vec![x, o]); // residual join
2691 let n2 = f32_node(&mut g, Op::Relu, vec![res]);
2692 let m = f32_node(&mut g, Op::Silu, vec![n2]);
2693 let res2 = f32_node(&mut g, Op::Add, vec![res, m]);
2694
2695 let before = g.len();
2696 let optimized = optimize_graph(&mut g, &[res2], &table, &two_backend_opts())
2697 .expect("optimize_graph succeeds on a transformer-shaped two-placement graph");
2698
2699 let mut branches = branches_after(&g, before);
2700 branches.sort_by_key(|(_, exit, _)| exit.0);
2701 assert_eq!(
2702 optimized.branch_count(&g),
2703 2,
2704 "one region per residual block"
2705 );
2706 assert_eq!(
2707 branches.iter().map(|&(_, e, r)| (e, r)).collect::<Vec<_>>(),
2708 vec![(o, res), (m, res2)],
2709 "arm-0 exits and reconverge nodes: (o, res) and (m, res2)"
2710 );
2711 // Arm 1 clones the whole stretch: 7 + 2 clone nodes beside the 2 branch nodes.
2712 assert_eq!(
2713 g.len() - before,
2714 7 + 2 + 2,
2715 "clones of both stretches plus two branch nodes"
2716 );
2717 // Block 1's arm-1 head reads the shared diverge node x (not a clone), and res reads x directly.
2718 assert!(
2719 g.node(res).inputs.contains(&x),
2720 "the residual edge x -> res is untouched"
2721 );
2722 }
2723
2724 /// ROW 158: a region's arm 1 on ANOTHER device must read every value from outside its arm through an
2725 /// `Op::Copy`, and hand its result back to arm 0's device through one. The first run of arm 1 on a GPU
2726 /// (a CPU arm in a Vulkan realize) failed with `cpu kernel wrapper called with non-CPU input` on a clone
2727 /// `Add` reading two Vulkan `Mul` nodes directly: the pathfinder's clones carried a `target_backend`
2728 /// but no placement, so the residency pass placed them on the pinned device and saw no crossing.
2729 ///
2730 /// The stretch `a, t` has TWO external inputs (the diverge `d` and the earlier `e`) and its exit feeds
2731 /// a reconverge on the host. The alternative runs on `Cuda { gpu_id: 0 }`. Built through
2732 /// `try_record_branch` with explicit devices because the synthetic two-backend fixture of
2733 /// `optimize_graph` puts its "Cuda" placement at the CPU location and so cannot show a crossing.
2734 #[test]
2735 fn a_cross_device_arm_one_gets_inbound_copies_for_every_external_input_and_an_exit_copy() {
2736 use crate::region_pathfinder::try_record_branch;
2737 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2738 let mut g = Graph::new();
2739 let x = f32_node(&mut g, Op::Const, vec![]);
2740 let e = f32_node(&mut g, Op::Relu, vec![x]);
2741 let d = f32_node(&mut g, Op::Silu, vec![e]); // the diverge
2742 let a = f32_node(&mut g, Op::Add, vec![d, e]); // entry: reads d AND e, both outside the stretch
2743 let t = f32_node(&mut g, Op::Tanh, vec![a]);
2744 let res = f32_node(&mut g, Op::Add, vec![d, t]); // reconverge: reads the exit t (and d)
2745 for n in [x, e, d, a, t, res] {
2746 g.set_placement(n, DeviceLocation::Cpu);
2747 if n != x {
2748 g.set_target_backend(n, BackendId::Cpu);
2749 }
2750 }
2751 let branch = try_record_branch(
2752 &mut g,
2753 d,
2754 res,
2755 &[a, t],
2756 t,
2757 BackendId::Cuda,
2758 cuda0,
2759 DeviceLocation::Cpu,
2760 )
2761 .expect("well-formed branch")
2762 .expect("two arms");
2763 insert_residency_copies(
2764 &mut g,
2765 &[res],
2766 &ExecutionPlan::empty(),
2767 DeviceLocation::Cpu,
2768 None,
2769 );
2770
2771 let arm1_exit = g.node(branch).inputs[1];
2772 // The arm's result comes back to the host through a copy, so both exits live on one device.
2773 assert!(
2774 matches!(g.node(arm1_exit).op, Op::Copy { target } if target == DeviceLocation::Cpu),
2775 "arm 1's exit must be a copy back to the host; got {:?}",
2776 g.node(arm1_exit).op
2777 );
2778 let clone_t = g.node(arm1_exit).inputs[0];
2779 let clone_a = g.node(clone_t).inputs[0];
2780 assert_eq!(g.node(clone_a).op, Op::Add, "the clone of the entry node");
2781 // Both external inputs of the clone entry node go through a copy onto the alternative device.
2782 assert_eq!(g.node(clone_a).inputs.len(), 2);
2783 for &input in &g.node(clone_a).inputs {
2784 assert!(
2785 matches!(g.node(input).op, Op::Copy { target } if target == cuda0),
2786 "clone entry node reads {:?} ({:?}) from outside its arm with no copy onto {cuda0:?}",
2787 input,
2788 g.node(input).op,
2789 );
2790 }
2791 // The copies read the original host values (the shared diverge and the earlier node).
2792 let sources: Vec<NodeId> = g
2793 .node(clone_a)
2794 .inputs
2795 .iter()
2796 .map(|&c| g.node(c).inputs[0])
2797 .collect();
2798 assert_eq!(sources, vec![d, e]);
2799 // Arm 0 is untouched: still host to host, no copies.
2800 assert_eq!(g.node(a).inputs, vec![d, e]);
2801 }
2802
2803 /// ROW 157 / GAP-385, PURE FAN-OUT (no residual edge): `x -> n1 -> {q, k} -> a -> t`. The region is
2804 /// the fan-out and everything up to its join: diverge `x`, a four-node arm (`n1 q k a`), reconverge
2805 /// `t`. Born red: the one-node fork never forked `n1` (two consumers) and made one-node forks of
2806 /// `q`, `k` (sole consumer `a`) and `a`.
2807 #[test]
2808 fn fan_out_that_rejoins_is_one_multi_node_region() {
2809 let table = two_placement_table();
2810 let mut g = Graph::new();
2811 let x = f32_node(&mut g, Op::Const, vec![]);
2812 let n1 = f32_node(&mut g, Op::Relu, vec![x]);
2813 let q = f32_node(&mut g, Op::Silu, vec![n1]);
2814 let k = f32_node(&mut g, Op::Tanh, vec![n1]);
2815 let a = f32_node(&mut g, Op::Add, vec![q, k]);
2816 let t = f32_node(&mut g, Op::Relu, vec![a]);
2817
2818 let before = g.len();
2819 optimize_graph(&mut g, &[t], &table, &two_backend_opts()).expect("optimize_graph");
2820 let branches = branches_after(&g, before);
2821 assert_eq!(
2822 branches.iter().map(|&(_, e, r)| (e, r)).collect::<Vec<_>>(),
2823 vec![(a, t)],
2824 "one region: arm-0 exit a, reconverge t"
2825 );
2826 assert_eq!(
2827 g.len() - before,
2828 4 + 1,
2829 "four cloned nodes (n1 q k a) plus the branch node"
2830 );
2831 }
2832 /// Cross-device, production-shaped options: the realize device is a GPU (`Cuda { gpu_id: 0 }`), CPU is
2833 /// the always-feasible fallback device, and a transfer estimator is present, so the placement DP
2834 /// runs and prunes every node's alternative set to its committed device (the single-device-set
2835 /// invariant). This is the shape `build_optimized_graph` builds on a Vulkan/CUDA realize; the
2836 /// co-located `two_backend_opts` above never opens a DP row and so never reaches this pruning.
2837 struct FlatTransfer;
2838 impl crate::ranker::cost::TransferEstimator for FlatTransfer {
2839 fn estimate_transfer_ns(
2840 &self,
2841 src: DeviceLocation,
2842 dst: DeviceLocation,
2843 _bytes: u64,
2844 ) -> u64 {
2845 if src == dst { 0 } else { 1_000 }
2846 }
2847 }
2848 /// A kernel cost of 10_000 flops (10 us at the caps' 1 flop/ns) on every node: a transfer of 1_000 ns
2849 /// is then a small fraction of a node, as on a real model, rather than infinitely worse than a
2850 /// zero-cost kernel (which `unknown_cost` would give).
2851 fn ten_us_cost(
2852 _: &[Shape],
2853 _: &[DType],
2854 _: &crate::kernel::OpParams,
2855 _: &fuel_ir::backend::BackendCapabilities,
2856 ) -> crate::fused::CostEstimate {
2857 crate::fused::CostEstimate {
2858 flops: 10_000,
2859 bytes_moved: 0,
2860 kernel_overhead_ns: 0,
2861 }
2862 }
2863 /// The same node on the GPU prior (`default_backend_rates`: 30 flops/ns) at 300_000 flops, i.e. also
2864 /// 10 us: the CPU arm is then within the competitive factor. Without this the CPU arm would be ~30x
2865 /// slower and correctly NOT competitive, which is itself what a real GPU model looks like.
2866 fn ten_us_cost_gpu(
2867 _: &[Shape],
2868 _: &[DType],
2869 _: &crate::kernel::OpParams,
2870 _: &fuel_ir::backend::BackendCapabilities,
2871 ) -> crate::fused::CostEstimate {
2872 crate::fused::CostEstimate {
2873 flops: 300_000,
2874 bytes_moved: 0,
2875 kernel_overhead_ns: 0,
2876 }
2877 }
2878 fn costed_two_placement_table() -> KernelBindingTable {
2879 let mut table = KernelBindingTable::new();
2880 for (op, n_in) in [
2881 (OpKind::ReluElementwise, 1),
2882 (OpKind::SiluElementwise, 1),
2883 (OpKind::TanhElementwise, 1),
2884 (OpKind::AddElementwise, 2),
2885 ] {
2886 let mut dtypes = vec![DType::F32; n_in];
2887 dtypes.push(DType::F32);
2888 for (backend, kernel, cost) in [
2889 (
2890 BackendId::Cpu,
2891 noop_kernel as crate::kernel::KernelRef,
2892 ten_us_cost as crate::kernel::CostFn,
2893 ),
2894 (
2895 BackendId::Cuda,
2896 noop_kernel_b as crate::kernel::KernelRef,
2897 ten_us_cost_gpu as crate::kernel::CostFn,
2898 ),
2899 ] {
2900 table.register_full(
2901 op,
2902 &dtypes,
2903 backend,
2904 kernel,
2905 KernelCaps::empty(),
2906 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2907 cost,
2908 );
2909 }
2910 }
2911 table
2912 }
2913 fn gpu_placements(dev: DeviceLocation) -> Vec<BackendId> {
2914 match dev {
2915 DeviceLocation::Cuda { .. } => vec![BackendId::Cuda],
2916 DeviceLocation::Cpu => vec![BackendId::Cpu],
2917 _ => vec![],
2918 }
2919 }
2920 fn cpu_fallback(dev: DeviceLocation) -> Vec<(BackendId, DeviceLocation)> {
2921 if dev == DeviceLocation::Cpu {
2922 vec![]
2923 } else {
2924 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
2925 }
2926 }
2927
2928 /// ROW 157 / GAP-385, PRODUCTION ENTRY (born red). Live run, Vulkan tiny-Llama, ref `db0c1f7a2`: every
2929 /// optimize reported 0 live `Op::Branch`; the pathfinder saw 0 nodes with two placements because
2930 /// `compile_plan` pruned each set to the DP-committed device. Here the same options shape
2931 /// (GPU realize device + CPU fallback + transfer estimator) over a residual block must still yield
2932 /// one multi-node region.
2933 #[test]
2934 fn cross_device_residual_block_forks_through_the_production_options_shape() {
2935 let table = costed_two_placement_table();
2936 let mut g = Graph::new();
2937 let x = f32_node(&mut g, Op::Const, vec![]);
2938 let n1 = f32_node(&mut g, Op::Relu, vec![x]);
2939 let q = f32_node(&mut g, Op::Silu, vec![n1]);
2940 let o = f32_node(&mut g, Op::Tanh, vec![q]);
2941 let res = f32_node(&mut g, Op::Add, vec![x, o]);
2942
2943 let est = FlatTransfer;
2944 let gpu = DeviceLocation::Cuda { gpu_id: 0 };
2945 let caps = fuel_ir::backend::BackendCapabilities {
2946 backend_id: BackendId::Cuda,
2947 device_location: gpu,
2948 op_dtype_support: std::collections::HashSet::new(),
2949 required_alignment: 64,
2950 access_granularity_bits: 8,
2951 transfer_paths: vec![(gpu, fuel_ir::backend::TransferPath::SameDevice)],
2952 storage_substrate: fuel_ir::backend::SubstrateClass::HostBytes,
2953 compute_throughput_flops_per_ns: 1.0,
2954 mem_bandwidth_bytes_per_ns: 4.0,
2955 };
2956 let caps_for = |_: BackendId| Some(&caps);
2957 let residency = |_: NodeId| Some(gpu);
2958 // Cost population stays ON (the default): `relaxed` merged enumeration, and with it the
2959 // placement DP, only runs when pricing is active, exactly as `build_optimized_graph` sets it.
2960 let opts = PlanOptions::new()
2961 .with_pinned_device(gpu)
2962 .with_placements_for_device(&gpu_placements)
2963 .with_fallback_placements_for(&cpu_fallback)
2964 .with_capabilities_for(&caps_for)
2965 .with_transfer_estimator(&est)
2966 .with_input_residency(&residency);
2967 let before = g.len();
2968 let optimized = optimize_graph(&mut g, &[res], &table, &opts).expect("optimize_graph");
2969 assert!(
2970 optimized.branch_count(&g) >= 1,
2971 "a GPU realize with a CPU fallback must expose a cross-device region; branches={:?}",
2972 branches_after(&g, before)
2973 );
2974 }
2975
2976 /// SIBLING of the test above: the same cross-device shape, but the GPU kernel is 30x cheaper than the
2977 /// CPU one (both at 10_000 flops, GPU prior 30 flops/ns). The CPU arm is not within the competitive
2978 /// factor, so NO region is recorded. This is what a real GPU model looks like; the test keeps the
2979 /// first one from passing by recording a region unconditionally.
2980 #[test]
2981 fn cross_device_cpu_arm_far_slower_than_the_gpu_is_not_competitive() {
2982 let mut table = KernelBindingTable::new();
2983 for (op, n_in) in [
2984 (OpKind::ReluElementwise, 1),
2985 (OpKind::SiluElementwise, 1),
2986 (OpKind::TanhElementwise, 1),
2987 (OpKind::AddElementwise, 2),
2988 ] {
2989 let mut dtypes = vec![DType::F32; n_in];
2990 dtypes.push(DType::F32);
2991 for (backend, kernel) in [
2992 (BackendId::Cpu, noop_kernel as crate::kernel::KernelRef),
2993 (BackendId::Cuda, noop_kernel_b as crate::kernel::KernelRef),
2994 ] {
2995 table.register_full(
2996 op,
2997 &dtypes,
2998 backend,
2999 kernel,
3000 KernelCaps::empty(),
3001 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3002 ten_us_cost,
3003 );
3004 }
3005 }
3006 let mut g = Graph::new();
3007 let x = f32_node(&mut g, Op::Const, vec![]);
3008 let n1 = f32_node(&mut g, Op::Relu, vec![x]);
3009 let q = f32_node(&mut g, Op::Silu, vec![n1]);
3010 let o = f32_node(&mut g, Op::Tanh, vec![q]);
3011 let res = f32_node(&mut g, Op::Add, vec![x, o]);
3012 let est = FlatTransfer;
3013 let gpu = DeviceLocation::Cuda { gpu_id: 0 };
3014 let caps = fuel_ir::backend::BackendCapabilities {
3015 backend_id: BackendId::Cuda,
3016 device_location: gpu,
3017 op_dtype_support: std::collections::HashSet::new(),
3018 required_alignment: 64,
3019 access_granularity_bits: 8,
3020 transfer_paths: vec![(gpu, fuel_ir::backend::TransferPath::SameDevice)],
3021 storage_substrate: fuel_ir::backend::SubstrateClass::HostBytes,
3022 compute_throughput_flops_per_ns: 1.0,
3023 mem_bandwidth_bytes_per_ns: 4.0,
3024 };
3025 let caps_for = |_: BackendId| Some(&caps);
3026 let residency = |_: NodeId| Some(gpu);
3027 let opts = PlanOptions::new()
3028 .with_pinned_device(gpu)
3029 .with_placements_for_device(&gpu_placements)
3030 .with_fallback_placements_for(&cpu_fallback)
3031 .with_capabilities_for(&caps_for)
3032 .with_transfer_estimator(&est)
3033 .with_input_residency(&residency);
3034 let optimized = optimize_graph(&mut g, &[res], &table, &opts).expect("optimize_graph");
3035 assert_eq!(
3036 optimized.branch_count(&g),
3037 0,
3038 "a CPU arm ~30x slower than the GPU is not competitive within the factor of 2"
3039 );
3040 }
3041
3042 /// SABOTAGE SIBLING (row 157): a node read from outside the stretch must not sit inside a region.
3043 /// `n1` is read by `m` and by a second realize root `side`, so no region may contain it; `m` alone
3044 /// (diverge `n1`, reconverge `t`) is still a valid one-node region.
3045 #[test]
3046 fn a_node_read_from_outside_the_stretch_is_not_inside_a_region() {
3047 let table = two_placement_table();
3048 let mut g = Graph::new();
3049 let x = f32_node(&mut g, Op::Const, vec![]);
3050 let n1 = f32_node(&mut g, Op::Relu, vec![x]);
3051 let m = f32_node(&mut g, Op::Silu, vec![n1]);
3052 let t = f32_node(&mut g, Op::Relu, vec![m]);
3053 let side = f32_node(&mut g, Op::Tanh, vec![n1]);
3054 let before = g.len();
3055 optimize_graph(&mut g, &[t, side], &table, &two_backend_opts()).expect("optimize_graph");
3056 let exits: Vec<NodeId> = branches_after(&g, before).iter().map(|b| b.1).collect();
3057 assert!(
3058 !exits.contains(&n1),
3059 "n1 is read by a second root and cannot be an arm exit"
3060 );
3061 }
3062
3063 /// SABOTAGE SIBLING (row 157): a stretch is only as long as the nodes that have the alternative.
3064 /// `s` is CPU-only, so no region may span it; the two Relu nodes each fork alone.
3065 #[test]
3066 fn a_node_without_the_alternative_kernel_splits_the_region() {
3067 let mut table = KernelBindingTable::new();
3068 register_two_backend(&mut table, OpKind::ReluElementwise, 1);
3069 register_elementwise(&mut table, OpKind::SiluElementwise, 1); // CPU only
3070 let mut g = Graph::new();
3071 let x = f32_node(&mut g, Op::Const, vec![]);
3072 let r1 = f32_node(&mut g, Op::Relu, vec![x]);
3073 let s = f32_node(&mut g, Op::Silu, vec![r1]);
3074 let r2 = f32_node(&mut g, Op::Relu, vec![s]);
3075 let t = f32_node(&mut g, Op::Relu, vec![r2]);
3076 let before = g.len();
3077 optimize_graph(&mut g, &[t], &table, &two_backend_opts()).expect("optimize_graph");
3078 let mut exits: Vec<NodeId> = branches_after(&g, before).iter().map(|b| b.1).collect();
3079 exits.sort_by_key(|n| n.0);
3080 assert!(
3081 !exits.contains(&s),
3082 "the CPU-only node is never an arm exit"
3083 );
3084 // r2 and t form one two-node stretch? t is the root, so only r1 and r2 can be interior.
3085 assert_eq!(
3086 exits,
3087 vec![r1, r2],
3088 "r1 forks alone, r2 forks alone, nothing spans s"
3089 );
3090 }
3091
3092 /// SABOTAGE SIBLING (row 157): one placement per node means no region at all.
3093 #[test]
3094 fn a_single_placement_graph_gets_no_regions() {
3095 let mut table = KernelBindingTable::new();
3096 register_elementwise(&mut table, OpKind::ReluElementwise, 1);
3097 register_elementwise(&mut table, OpKind::SiluElementwise, 1);
3098 let mut g = Graph::new();
3099 let x = f32_node(&mut g, Op::Const, vec![]);
3100 let a = f32_node(&mut g, Op::Relu, vec![x]);
3101 let b = f32_node(&mut g, Op::Silu, vec![a]);
3102 let c = f32_node(&mut g, Op::Relu, vec![b]);
3103 let before = g.len();
3104 let optimized = optimize_graph(&mut g, &[c], &table, &cpu_opts()).expect("optimize_graph");
3105 assert_eq!(optimized.branch_count(&g), 0);
3106 assert_eq!(g.len(), before, "no clones are left behind");
3107 }
3108
3109 // ===== Load-aware arm pick through the PRODUCTION realize entry
3110 // (row 158 slice 2: estimated-completion, not queue-depth) =====
3111
3112 /// Records the backend of every candidate the wrapped selector picks, so
3113 /// a test can read WHICH arm the production picking entry chose.
3114 #[derive(Debug)]
3115 struct RecordingSelector {
3116 inner: crate::ranker::ChainedSelector,
3117 picked: std::sync::Mutex<Vec<BackendId>>,
3118 }
3119
3120 impl crate::ranker::RuntimeSelector for RecordingSelector {
3121 fn select<'a>(
3122 &self,
3123 set: &'a crate::ranker::AlternativeSet,
3124 ) -> Option<&'a crate::ranker::Candidate> {
3125 let picked = self.inner.select(set);
3126 if let Some(c) = picked {
3127 self.picked.lock().unwrap().push(c.backend);
3128 }
3129 picked
3130 }
3131 }
3132
3133 /// Judge answering per BACKEND only. The pick enumerates candidates from
3134 /// the process-wide binding table (real `portable-cpu` kernel with a
3135 /// revision hash; a synthetic CUDA stand-in), so a cell-keyed judge would
3136 /// couple the test to those tags.
3137 struct BackendJudge {
3138 cuda_ns: u64,
3139 cpu_ns: u64,
3140 }
3141
3142 impl crate::ranker::JudgeOracle for BackendJudge {
3143 fn measured_latency_ns(
3144 &self,
3145 _op: OpKind,
3146 _dtype: DType,
3147 _size_class: fuel_ir::dispatch::SizeClass,
3148 backend: BackendId,
3149 _kernel_source: &str,
3150 _kernel_revision_hash: u64,
3151 ) -> Option<u64> {
3152 match backend {
3153 BackendId::Cuda => Some(self.cuda_ns),
3154 BackendId::Cpu => Some(self.cpu_ns),
3155 _ => None,
3156 }
3157 }
3158 }
3159
3160 /// Realize the single-fork graph through
3161 /// `PipelinedExecutor::realize_with_optimized_picking_env` (the entry the
3162 /// bridge calls) with a `ChainedSelector` over `lookup` and a Judge that
3163 /// measures the fork op at `cuda_ns` on CUDA and `cpu_ns` on CPU. Returns
3164 /// the backends the streaming pick chose for the (one) branch.
3165 ///
3166 /// Also returns the realize result (`"Ok"` or `Err(..)` as text), so a
3167 /// run with no pick names its cause instead of reading as "no pick".
3168 ///
3169 /// Holds `TOPOLOGY_TEST_GATE` for writing from before `optimize_graph`
3170 /// until the realize returns: the executor returns the typed
3171 /// `Error::TopologyChanged` when another test in this binary bumps the
3172 /// process-wide topology generation in between, and then the streaming
3173 /// walk never reaches the branch (ROADMAP row 165). The gate stops a
3174 /// sibling's bump from landing in that window; there is no retry.
3175 fn picked_backends_through_realize(
3176 lookup: crate::ranker::BackendRuntimeLookup,
3177 cuda_ns: u64,
3178 cpu_ns: u64,
3179 ) -> (Vec<BackendId>, String) {
3180 use crate::PipelinedExecutor;
3181 use crate::pipelined::StorageCache;
3182 use crate::ranker::ChainedSelector;
3183 use fuel_ir::SymEnv;
3184
3185 // Build the lazily initialised process-wide tables BEFORE taking the
3186 // gate: their initialisation bumps the generation, and a bump under
3187 // our own write guard would wait on ourselves.
3188 drop(crate::dispatch::global_bindings());
3189 let _crate_gate = crate::dispatch::TOPOLOGY_TEST_GATE
3190 .write()
3191 .unwrap_or_else(|poisoned| poisoned.into_inner());
3192
3193 let mut table = KernelBindingTable::new();
3194 let (mut g, _prod, _fork, _tail, root) = build_single_fork_graph(&mut table);
3195 let optimized = optimize_graph(&mut g, &[root], &table, &two_backend_opts())
3196 .expect("optimize_graph succeeds");
3197 assert_eq!(optimized.branch_count(&g), 1, "exactly one branch");
3198
3199 let selector = Arc::new(RecordingSelector {
3200 inner: ChainedSelector::with_default_estimator(
3201 Some(Arc::new(BackendJudge { cuda_ns, cpu_ns })),
3202 Some(lookup.clone()),
3203 ),
3204 picked: std::sync::Mutex::new(Vec::new()),
3205 });
3206
3207 let graph = Arc::new(RwLock::new(g));
3208 let mut cache = StorageCache::new();
3209 cache.insert(
3210 NodeId(0),
3211 Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
3212 1.0_f32, 2.0, 3.0, 4.0,
3213 ]))),
3214 );
3215 // The CUDA arm has no device behind it in a CPU test, so a realize
3216 // that picked CUDA ends in a device error at the reconverge node; a
3217 // realize that picked CPU runs end to end. The result is returned, not
3218 // ignored, so the caller pins which.
3219 let result = PipelinedExecutor::realize_with_optimized_picking_env(
3220 graph,
3221 root,
3222 cache,
3223 &optimized,
3224 Some(selector.clone() as Arc<dyn crate::ranker::RuntimeSelector>),
3225 Some(lookup),
3226 SymEnv::default(),
3227 );
3228 let outcome = match result {
3229 Ok(_) => "Ok".to_string(),
3230 Err(e) => format!("Err({e:?})"),
3231 };
3232 let picks = selector.picked.lock().unwrap().clone();
3233 (picks, outcome)
3234 }
3235
3236 /// Row 158 slice 2. CUDA measures 100 ns on the fork op, CPU 100 us.
3237 /// The device load must be read as estimated BACKLOG TIME, not as a
3238 /// queue-depth bucket:
3239 /// - idle CUDA -> CUDA arm;
3240 /// - CUDA with ONE op queued (the count bucket says "saturated") but
3241 /// only 1 us of estimated backlog -> STILL the CUDA arm (1.1 us beats
3242 /// CPU's 100 us); the count tier wrongly sends this to CPU;
3243 /// - CUDA with a 1 hour backlog -> the CPU arm.
3244 ///
3245 /// SHOWS: the streaming pick, reached through the production picking
3246 /// realize entry, ranks arms by backlog + measured latency.
3247 /// DOES NOT SHOW: that the executor's submit sites feed the backlog
3248 /// (the lookup here injects it), nor that kernels ran on either arm.
3249 #[test]
3250 fn load_aware_pick_ranks_by_estimated_completion_through_realize() {
3251 use crate::ranker::mock_backlog_lookup;
3252 const HOUR_NS: u64 = 3_600_000_000_000;
3253
3254 let (idle, idle_r) = picked_backends_through_realize(
3255 mock_backlog_lookup(vec![(BackendId::Cuda, 0, 0)]),
3256 100,
3257 100_000,
3258 );
3259 assert_eq!(
3260 idle,
3261 vec![BackendId::Cuda],
3262 "idle GPU -> GPU arm; realize={idle_r}"
3263 );
3264
3265 let (one_op, one_op_r) = picked_backends_through_realize(
3266 mock_backlog_lookup(vec![(BackendId::Cuda, 1, 1_000)]),
3267 100,
3268 100_000,
3269 );
3270 assert_eq!(
3271 one_op,
3272 vec![BackendId::Cuda],
3273 "1 op / 1 us backlog: GPU still finishes first (1.1 us vs 100 us); realize={one_op_r}",
3274 );
3275
3276 let (hour, hour_r) = picked_backends_through_realize(
3277 mock_backlog_lookup(vec![(BackendId::Cuda, 1, HOUR_NS)]),
3278 100,
3279 100_000,
3280 );
3281 assert_eq!(
3282 hour,
3283 vec![BackendId::Cpu],
3284 "1 h GPU backlog -> CPU arm; realize={hour_r}"
3285 );
3286 assert_eq!(hour_r, "Ok", "the CPU arm realizes end to end");
3287 }
3288}