fuel_graph/run.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Run extraction + the transient `lower_run` view + the fewness gate.
3//!
4//! Phase A PR-A2 of the "plan IS the graph" rebuild.
5//!
6//! A **run** is the maximal straight-line op-sequence between two
7//! *decision points* — the future dispatch / CUDA-graph-capture unit
8//! (see [`../docs/architecture/06-runtime.md`](../../docs/architecture/06-runtime.md)
9//! §"Dispatch: runs, not single ops"). This module *derives* runs from
10//! the graph structure; it does **not** execute them (Phase C) and does
11//! **not** add an optimizer (Phase A3+). A run is a single-device
12//! contiguous chain with one `entry` and one `exit`; its members are
13//! [`NodeId`]s in topological order.
14//!
15//! Run boundaries (a new run starts at a node when *any* hold):
16//! - **(a) graph entry** — a node with no predecessor inside the
17//! reachable set (a source / root input of the walk).
18//! - **(b) reconverge** — a node named as some [`Op::Branch`]'s
19//! `reconverge_at` (the post-merge region is a fresh run).
20//! - **(c) arm entry** — a node whose sole predecessor is a Branch's
21//! *diverge* point (the first node of each candidate route).
22//! - **(d) residency seam** — the node's [`Graph::target_backend`]
23//! differs from its sole predecessor's, **or** the node is an
24//! [`Op::Copy`] / [`Op::Move`] device-transfer.
25//! - **(e) fan-in** — a node with more than one predecessor inside the
26//! reachable set.
27//!
28//! Consequently a run never spans a `Branch` boundary or a device
29//! change. A graph with **zero** `Op::Branch` nodes and a single
30//! residency extracts to exactly **one** run covering all reachable
31//! nodes — exactly today's single-route graph.
32
33use crate::{Graph, NodeId, Op, topo_order_multi};
34use fuel_ir::probe::BackendId;
35use std::collections::{HashMap, HashSet};
36
37/// A resolved route through the multi-path graph: for each `Op::Branch`
38/// decision point (keyed by the Branch node's [`NodeId`]) the **arm
39/// index** the runtime route picker (Picker 2) chose. Arm `i` is the
40/// branch's `inputs[i]` (arm-0 = `inputs[0]` = the cost-vector winner).
41///
42/// A branch **absent** from the map defaults to **arm 0** — so the empty
43/// route is exactly the arm-0-everywhere lowering ([`lower_runs_arm0`]),
44/// which keeps the no-pressure / no-telemetry behavior identical to
45/// Phase B. The picker in `fuel-dispatch` produces one of these by
46/// walking the branches in topological order and consulting a runtime
47/// selector over each branch's arms; `fuel-graph` only *consumes* it to
48/// lower the chosen route (it has no selector / telemetry knowledge).
49pub type PickedRoute = HashMap<NodeId, usize>;
50
51/// A maximal straight-line, single-device op-sequence between two
52/// decision points — the dispatch / command-buffer-capture unit.
53///
54/// `members` are in topological order; `entry == members[0]` and
55/// `exit == *members.last()`. `device` is the resolved
56/// [`BackendId`] shared by every member (via
57/// [`Graph::target_backend`]); `None` means "inherit the executor
58/// default" (no member carries an explicit backend) — a run is
59/// single-device, so every member agrees on this value by construction
60/// (a residency change is itself a run boundary).
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct Run {
63 /// First node of the run (a decision-point boundary).
64 pub entry: NodeId,
65 /// Last node of the run (the node the next decision point reads,
66 /// or a root output).
67 pub exit: NodeId,
68 /// Every node of the run, in topological order, `entry` first.
69 pub members: Vec<NodeId>,
70 /// The single resolved backend shared by all members, or `None`
71 /// when no member carries an explicit `target_backend` (executor
72 /// default).
73 pub device: Option<BackendId>,
74}
75
76/// Extract the runs of the graph reachable from `root`, in
77/// topological order of their entries.
78///
79/// Walks the single existing [`topo_order_multi`] order once and cuts
80/// a new run at every boundary (see the module docs). Each emitted run
81/// is single-entry / single-exit and single-device.
82pub fn extract_runs(graph: &Graph, root: NodeId) -> Vec<Run> {
83 extract_runs_multi(graph, &[root])
84}
85
86/// Multi-root variant of [`extract_runs`] — the reachable set is the
87/// union over `roots` (mirrors [`topo_order_multi`]) **plus the arms of
88/// every reachable [`Op::Branch`]**. A Branch's non-arm-0 arms are read
89/// only by the Branch node itself (arm 0 is the runnability fallback the
90/// `reconverge_at` node reads directly, per PR-A1), so seeding the walk
91/// from the Branch nodes pulls every candidate route into the reachable
92/// set.
93pub fn extract_runs_multi(graph: &Graph, roots: &[NodeId]) -> Vec<Run> {
94 let eff_roots = effective_roots(graph, roots);
95 let order = topo_order_multi(graph, &eff_roots);
96 let reachable: HashSet<NodeId> = order.iter().copied().collect();
97
98 // Nodes named as some Branch's `reconverge_at` (the post-merge region
99 // opens a fresh run).
100 let reconverge_points: HashSet<NodeId> = order
101 .iter()
102 .filter_map(|&id| match graph.node(id).op {
103 Op::Branch { reconverge_at } => Some(reconverge_at),
104 _ => None,
105 })
106 .collect();
107
108 // Arm-entry nodes: the first node of each candidate route, departing
109 // from the shared diverge point. A run never spans into an arm.
110 let arm_entries = compute_arm_entries(graph, &order, &reachable);
111
112 // Predecessors inside the reachable set, per node (for fan-in + the
113 // residency-seam sole-predecessor test).
114 let mut pred_inside: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
115 for &id in &order {
116 let preds: Vec<NodeId> = graph
117 .node(id)
118 .inputs
119 .iter()
120 .copied()
121 .filter(|p| reachable.contains(p))
122 .collect();
123 pred_inside.insert(id, preds);
124 }
125
126 let mut runs: Vec<Run> = Vec::new();
127 let mut current: Vec<NodeId> = Vec::new();
128 let mut current_device: Option<BackendId> = None;
129
130 for &id in &order {
131 // The `Op::Branch` (phi/merge) node is structural bookkeeping —
132 // the decision point *between* runs, not executable work. It is
133 // never a run member; once a route is picked it is invisible to
134 // the hot path. Skipping it also means a consumer that reads a
135 // Branch (rather than the `reconverge_at` node) finds its
136 // predecessor absent from the open run and so opens a fresh run.
137 if matches!(graph.node(id).op, Op::Branch { .. }) {
138 continue;
139 }
140 let preds = &pred_inside[&id];
141 let device = graph.target_backend(id);
142
143 let starts_new = {
144 // (a) graph entry — no predecessor in the reachable set.
145 let is_entry = preds.is_empty();
146 // (b) reconverge point.
147 let is_reconverge = reconverge_points.contains(&id);
148 // (c) arm entry.
149 let is_arm = arm_entries.contains(&id);
150 // (e) fan-in — more than one reachable predecessor.
151 let is_fan_in = preds.len() > 1;
152 // (d) residency seam: a device-transfer op, or a backend that
153 // differs from the sole predecessor's backend.
154 let is_transfer = matches!(graph.node(id).op, Op::Copy { .. } | Op::Move { .. });
155 let is_seam = preds.len() == 1 && graph.target_backend(preds[0]) != device;
156 // Contiguity: a run is a straight-line chain, so a node only
157 // *extends* the current run when its sole predecessor IS the
158 // current run's last member. Otherwise it begins a new run
159 // even if no other rule fired (guards against topo interleave
160 // and the Branch node itself, whose inputs are the arm exits).
161 let breaks_chain = match current.last() {
162 None => true,
163 Some(&last) => !(preds.len() == 1 && preds[0] == last),
164 };
165 // A node whose backend differs from the open run's device
166 // cannot extend it (single-device runs).
167 let device_mismatch = !current.is_empty() && device != current_device;
168 is_entry
169 || is_reconverge
170 || is_arm
171 || is_fan_in
172 || is_transfer
173 || is_seam
174 || breaks_chain
175 || device_mismatch
176 };
177
178 if starts_new && !current.is_empty() {
179 runs.push(finish_run(¤t, current_device));
180 current = Vec::new();
181 }
182 if current.is_empty() {
183 current_device = device;
184 }
185 current.push(id);
186 }
187 if !current.is_empty() {
188 runs.push(finish_run(¤t, current_device));
189 }
190 runs
191}
192
193/// The effective root set for a run/density walk: the caller's `roots`
194/// plus every [`Op::Branch`] node *participating in* the reachable
195/// computation. A finalized `Op::Branch` is typically **orphaned** —
196/// nothing downstream reads it (the `reconverge_at` node reads arm 0
197/// directly, per PR-A1's runnability invariant), so it would never be
198/// found by a plain forward walk. We therefore scan the whole arena and
199/// seed any Branch whose `reconverge_at` (or any arm exit) is already
200/// reachable; seeding it pulls its candidate arms into the walk. Run to
201/// a fixpoint so a Branch reached only through another Branch's arm is
202/// also covered.
203///
204/// Public so the optimizer's residency pass (`fuel-dispatch`) can stitch
205/// inbound cross-device copies for EVERY surviving arm — a plain
206/// `topo_order_multi(roots)` walk misses orphaned Branch nodes (and thus
207/// their non-arm-0 arms), which would leave a re-pickable arm's device-
208/// inputs un-bridged (Step E Phase C, PR C-0).
209pub fn effective_roots(graph: &Graph, roots: &[NodeId]) -> Vec<NodeId> {
210 let mut seeds: Vec<NodeId> = roots.to_vec();
211 let mut seen: HashSet<NodeId> = seeds.iter().copied().collect();
212 loop {
213 let reachable: HashSet<NodeId> = topo_order_multi(graph, &seeds).into_iter().collect();
214 let mut added = false;
215 for idx in 0..graph.len() {
216 let id = NodeId(idx);
217 if seen.contains(&id) {
218 continue;
219 }
220 let Op::Branch { reconverge_at } = graph.node(id).op else {
221 continue;
222 };
223 // The branch participates if its merge target or any arm exit
224 // is already part of the reachable computation.
225 let participates = reachable.contains(&reconverge_at)
226 || graph.node(id).inputs.iter().any(|a| reachable.contains(a));
227 if participates {
228 seen.insert(id);
229 seeds.push(id);
230 added = true;
231 }
232 }
233 if !added {
234 break;
235 }
236 }
237 seeds
238}
239
240/// The reachable [`Op::Branch`] decision points over `roots`, in
241/// **topological order** of their `reconverge_at` merge points — the
242/// order the runtime route picker (Picker 2) resolves them in, so that
243/// coupled upstream decisions are committed before a downstream branch
244/// is reached (06-runtime §"Resolution order matters when decisions are
245/// coupled").
246///
247/// A finalized `Op::Branch` is typically orphaned (the `reconverge_at`
248/// node reads arm 0 directly, per PR-A1), so a plain forward walk would
249/// miss it; we therefore order by each branch's `reconverge_at` position
250/// in the [`effective_roots`] walk — the merge point is downstream of the
251/// arms, so its topo position is a faithful "where this decision sits"
252/// key. Branches whose merge point is unreachable are dropped.
253pub fn branches_in_topo_order(graph: &Graph, roots: &[NodeId]) -> Vec<NodeId> {
254 let eff_roots = effective_roots(graph, roots);
255 let order = topo_order_multi(graph, &eff_roots);
256 let position: HashMap<NodeId, usize> =
257 order.iter().enumerate().map(|(i, &id)| (id, i)).collect();
258
259 let mut branches: Vec<(usize, NodeId)> = Vec::new();
260 for idx in 0..graph.len() {
261 let id = NodeId(idx);
262 let Op::Branch { reconverge_at } = graph.node(id).op else {
263 continue;
264 };
265 // Only branches whose merge point participates in this realize.
266 if let Some(&pos) = position.get(&reconverge_at) {
267 branches.push((pos, id));
268 }
269 }
270 branches.sort_by_key(|&(pos, _)| pos);
271 branches.into_iter().map(|(_, id)| id).collect()
272}
273
274fn finish_run(members: &[NodeId], device: Option<BackendId>) -> Run {
275 Run {
276 entry: members[0],
277 exit: *members.last().expect("a run has at least one member"),
278 members: members.to_vec(),
279 device,
280 }
281}
282
283/// For every [`Op::Branch`] reachable in `order`, find the arm-entry
284/// nodes: the first node on each candidate route after the shared
285/// diverge point. These are run boundaries (rule (c)).
286///
287/// The op carries `reconverge_at` but not the diverge, so we recover the
288/// branch's shared prefix structurally: intersect the backward cones of
289/// all arm exits. Every node in that intersection is shared (the diverge
290/// point and its ancestors); the per-arm interior is everything else in
291/// the cone. An interior node is an *arm entry* when one of its
292/// predecessors lies in the shared prefix — i.e. it is the point where
293/// the route departs from the diverge region.
294fn compute_arm_entries(
295 graph: &Graph,
296 order: &[NodeId],
297 reachable: &HashSet<NodeId>,
298) -> HashSet<NodeId> {
299 let mut arm_entries: HashSet<NodeId> = HashSet::new();
300 for &id in order {
301 let Op::Branch { .. } = graph.node(id).op else {
302 continue;
303 };
304 let arm_exits: Vec<NodeId> = graph.node(id).inputs.clone();
305 if arm_exits.len() < 2 {
306 continue;
307 }
308 // Backward cone of each arm exit, bounded to the reachable set.
309 let cones: Vec<HashSet<NodeId>> = arm_exits
310 .iter()
311 .map(|&e| backward_cone(graph, e, reachable))
312 .collect();
313 // The diverge point is shared by every arm — it lies in the
314 // intersection of all cones. The arm interiors are the
315 // per-cone nodes NOT in that shared prefix. The arm entry is the
316 // interior node whose sole predecessor lies in the shared prefix.
317 let mut shared: HashSet<NodeId> = cones[0].clone();
318 for c in &cones[1..] {
319 shared = shared.intersection(c).copied().collect();
320 }
321 for cone in &cones {
322 for &n in cone {
323 if shared.contains(&n) {
324 continue;
325 }
326 // Arm-interior node. It is an arm *entry* if any of its
327 // predecessors is in the shared prefix (it departs from
328 // the diverge region).
329 let departs = graph.node(n).inputs.iter().any(|p| shared.contains(p));
330 if departs {
331 arm_entries.insert(n);
332 }
333 }
334 }
335 }
336 arm_entries
337}
338
339/// Backward-reachable cone of `from` (the node and all transitive
340/// inputs), bounded to `reachable`.
341fn backward_cone(graph: &Graph, from: NodeId, reachable: &HashSet<NodeId>) -> HashSet<NodeId> {
342 let mut seen: HashSet<NodeId> = HashSet::new();
343 let mut stack = vec![from];
344 while let Some(n) = stack.pop() {
345 if !reachable.contains(&n) || !seen.insert(n) {
346 continue;
347 }
348 for &inp in &graph.node(n).inputs {
349 if !seen.contains(&inp) {
350 stack.push(inp);
351 }
352 }
353 }
354 seen
355}
356
357/// The transient executable view of a single run: its ordered member
358/// [`NodeId`]s, ready to be recorded into a command buffer (Phase C).
359///
360/// A **borrow / transient** view — it is NOT stored on the graph. This
361/// is the shape Phase C records; PR-A2 only derives it.
362pub fn lower_run(run: &Run) -> &[NodeId] {
363 &run.members
364}
365
366/// The **arm-0 single-route lowering** (Phase A PR-A4, architect-
367/// approved temporary fix). The flat executable dispatch order that
368/// **follows arm 0 through every [`Op::Branch`]** — the pre-run, arm 0's
369/// run, then the post-run — and **skips every non-arm-0 arm's run**.
370///
371/// Why this is needed: [`extract_runs_multi`] partitions *every* arm
372/// into its own run (so the future runtime picker can choose among
373/// them). A naive concatenation of all runs would execute every arm.
374/// Until the Phase-C route picker lands, realize must default to arm 0
375/// — the route a finalized-but-unpicked graph runs on (the A1 arm-0
376/// runnability invariant). This walk drops the runs that lie entirely
377/// inside a non-arm-0 arm and keeps the rest (pre / arm-0 / post), so a
378/// branched graph realizes to the same result as its arm-0 route.
379///
380/// A graph with **zero `Op::Branch` nodes** has no arm to skip, so this
381/// is byte-identical to concatenating [`lower_run`] over
382/// [`extract_runs_multi`] — today's single-route order.
383pub fn lower_runs_arm0(graph: &Graph, roots: &[NodeId]) -> Vec<NodeId> {
384 // Arm-0 everywhere is the empty-route special case of the general
385 // route-aware lowering (an unmentioned branch defaults to arm 0).
386 lower_picked_route(graph, roots, &PickedRoute::new())
387}
388
389/// **Route-aware lowering** (Phase C PR-C1) — the generalization of
390/// [`lower_runs_arm0`]. The flat executable dispatch order that follows
391/// the **chosen arm at each [`Op::Branch`]** (per `picked`, defaulting to
392/// arm 0 for any branch the picker did not resolve) and **skips every
393/// non-chosen arm's run**.
394///
395/// This is exactly [`lower_runs_arm0`] generalized from "arm 0 always"
396/// to "the picked arm per branch": it reuses the same run partition
397/// ([`extract_runs_multi`]) and the same single-contiguous-region
398/// property of a run (extract never spans a branch boundary, so a run is
399/// either wholly inside a non-chosen arm or wholly outside). The skip set
400/// is `non_chosen_arm_nodes` — `non_arm0_arm_nodes` generalized to "any
401/// arm but the chosen one."
402///
403/// Value-preserving contract: every arm is a valid kernel for the same
404/// op (cast-to-uniform at `reconverge_at` per PR-A1), so following any
405/// arm yields the same result within tolerance. With `picked` empty
406/// (no-pressure / no-telemetry route) this is byte-identical to
407/// [`lower_runs_arm0`], and a graph with **zero `Op::Branch` nodes** has
408/// no arm to skip, so it equals concatenating [`lower_run`] over
409/// [`extract_runs_multi`] — today's single-route order.
410pub fn lower_picked_route(graph: &Graph, roots: &[NodeId], picked: &PickedRoute) -> Vec<NodeId> {
411 let runs = extract_runs_multi(graph, roots);
412 let skip = non_chosen_arm_nodes(graph, roots, picked);
413 // The KEPT runs (chosen arms + pre/post/independent regions), in topo
414 // order — the runs the un-reordered lowering would concatenate — with
415 // each chosen arm `k >= 1` placed where arm 0's run would have been
416 // (see `relocate_chosen_arm_runs`: the base order puts a non-zero arm's
417 // run AFTER the main chain, which is after the reconverge that reads it).
418 let metas = branch_arm_meta(graph, roots);
419 let (kept, aliases) = relocate_chosen_arm_runs(&runs, &metas, &skip, |b| {
420 picked.get(&b).copied().unwrap_or(0)
421 });
422 // PR-C3: device-alternating reorder of the kept runs (auto-overlap).
423 // Single-device ⇒ identity ⇒ byte-identical to the prior concatenation.
424 // Multi-device ⇒ a valid topological reordering that interleaves
425 // devices so independent device sub-DAGs dispatch adjacently (the A4b
426 // overlap topology, for an arbitrary graph). The reorder is a hint: the
427 // emitted NodeIds are identical, only their order across independent
428 // runs changes.
429 let perm = device_alternating_order_with_aliases(graph, &kept, &aliases);
430 let mut order = Vec::new();
431 for &ri in &perm {
432 order.extend_from_slice(lower_run(&kept[ri]));
433 }
434 order
435}
436
437/// The kept runs of a route in dispatch order, with every chosen arm `k >= 1` whose runs sit AFTER the
438/// reconverge in the base order moved to just before the reconverge's run, plus the arm-exit aliases
439/// (`arm 0 exit -> chosen exit`).
440///
441/// [`extract_runs_multi`] cuts runs from a topological order whose orphaned-Branch seeds pull a non-zero
442/// arm's clone run in AFTER the main chain, while the reconverge node reads ARM 0's exit directly. With
443/// arm 0 skipped nothing orders the chosen arm's run before that reconverge, so a single branch came out
444/// right by luck and chained branches (a region's reconverge is the next region's diverge) came out
445/// invalid. The place for a late chosen-arm run is just before the reconverge's run, NOT the first arm slot:
446/// a chosen-arm run reads values (the diverge, and inbound copies of other nodes) that arm 0's own runs read
447/// first, so by the time the reconverge's run is reached every input is emitted; an earlier slot can precede
448/// a node the run reads (an inbound `Copy` of a later main-chain node, found on a GPU run: ROADMAP row 158).
449/// A chosen-arm run already before the reconverge in the base order stays where it is.
450fn relocate_chosen_arm_runs<F>(
451 runs: &[Run],
452 metas: &[BranchArmMeta],
453 skip: &HashSet<NodeId>,
454 mut chosen_of: F,
455) -> (Vec<Run>, HashMap<NodeId, NodeId>)
456where
457 F: FnMut(NodeId) -> usize,
458{
459 let mut entry_to_branches: HashMap<NodeId, Vec<usize>> = HashMap::new();
460 for (mi, meta) in metas.iter().enumerate() {
461 for &(entry, _arm) in &meta.arm_entries {
462 entry_to_branches.entry(entry).or_default().push(mi);
463 }
464 }
465 let run_of_entry: HashMap<NodeId, usize> =
466 runs.iter().enumerate().map(|(i, r)| (r.entry, i)).collect();
467 let mut resolved: HashSet<usize> = HashSet::new();
468 let mut relocated: HashSet<usize> = HashSet::new();
469 // Run index of a reconverge run -> the chosen arm's runs to emit just before it.
470 let mut before: HashMap<usize, Vec<usize>> = HashMap::new();
471 let mut aliases: HashMap<NodeId, NodeId> = HashMap::new();
472 let mut kept: Vec<Run> = Vec::new();
473 for (ri, run) in runs.iter().enumerate() {
474 if relocated.contains(&ri) {
475 continue;
476 }
477 if let Some(pending) = before.remove(&ri) {
478 for rj in pending {
479 kept.push(runs[rj].clone());
480 }
481 }
482 if let Some(branches) = entry_to_branches.get(&run.entry) {
483 for &mi in branches {
484 if !resolved.insert(mi) {
485 continue;
486 }
487 let meta = &metas[mi];
488 let chosen = clamp_arm(meta, chosen_of(meta.branch));
489 if chosen != 0 {
490 note_alias(meta, chosen, &mut aliases);
491 if let Some(&rr) = run_of_entry.get(&meta.reconverge) {
492 for rj in arm_run_indices(runs, meta, chosen) {
493 if rj > rr && relocated.insert(rj) {
494 before.entry(rr).or_default().push(rj);
495 }
496 }
497 }
498 }
499 }
500 }
501 if skip.contains(&run.entry) {
502 continue;
503 }
504 kept.push(run.clone());
505 }
506 (kept, aliases)
507}
508
509/// A stale or out-of-range arm index clamps to arm 0 (never panic), as `add_non_chosen_skip` does.
510fn clamp_arm(meta: &BranchArmMeta, chosen: usize) -> usize {
511 if chosen < meta.cones.len() { chosen } else { 0 }
512}
513
514/// Record `arm 0 exit -> chosen arm exit` for a branch whose chosen arm is not arm 0.
515fn note_alias(meta: &BranchArmMeta, chosen: usize, aliases: &mut HashMap<NodeId, NodeId>) {
516 if chosen != 0
517 && let (Some(&arm0), Some(&armk)) = (meta.exits.first(), meta.exits.get(chosen))
518 {
519 aliases.insert(arm0, armk);
520 }
521}
522
523/// Indices (ascending) of the runs wholly inside arm `arm` of `meta`: those whose entry lies in the arm's
524/// cone but not in the shared diverge prefix.
525fn arm_run_indices(runs: &[Run], meta: &BranchArmMeta, arm: usize) -> Vec<usize> {
526 let cone = &meta.cones[arm];
527 runs.iter()
528 .enumerate()
529 .filter(|(_, r)| cone.contains(&r.entry) && !meta.shared.contains(&r.entry))
530 .map(|(i, _)| i)
531 .collect()
532}
533
534/// **Device-overlap topological reorder** of a run list (Step E Phase C,
535/// PR C3 — the *auto-overlap* pass). Returns a permutation of
536/// `0..runs.len()` (indices into `runs`) that is a **valid topological
537/// reordering** — every run still appears after all the runs it depends
538/// on — chosen so independent cross-device sub-DAGs DISPATCH so they
539/// overlap: the longest compute chunk of each device is enqueued/recorded
540/// BEFORE the host-blocking cross-device drain that feeds the join.
541///
542/// # Why (the A4b caveat this removes)
543///
544/// [`extract_runs_multi`] emits runs in [`topo_order_multi`]'s fixed-DFS
545/// order. For two INDEPENDENT reconverging sub-DAGs — one on CUDA, one on
546/// Vulkan — that DFS emits one sub-DAG *fully* (including the cross-device
547/// `Op::Copy` that feeds the join) before the other is even recorded. The
548/// executor then blocks the host on that copy's producer (a D2H wait)
549/// while the OTHER device sits idle — the two devices serialize. A4b built
550/// the cross-device concurrency MECHANISM (eager Vulkan submit + in-flight
551/// CUDA handles) but it only overlaps when the auto-submitting device's
552/// chunk (CUDA, A3 stream-ordered) is enqueued — and thus running — BEFORE
553/// the host blocks on the deferred device's (Vulkan) drain. The A4b overlap
554/// benchmark gets that order by HAND (a specific reconverge input order +
555/// CPU-primary pinning so the DFS happens to pop the heavy CUDA chunk
556/// first). This pass produces that order for an ARBITRARY graph.
557///
558/// # The heuristic — longest-downstream-compute (critical-path) list scheduling
559///
560/// A Kahn pump that, among the runs whose producers are all emitted, picks
561/// the run with the **largest compute chunk reachable downstream**
562/// (including itself) — a classic critical-path / HLFET list-scheduling
563/// priority. Concretely, each run is weighted by `max over its downstream
564/// cone of compute_size(run)`, where a compute run's size is its node count
565/// and a cross-device **transfer** (`Op::Copy`/`Op::Move`) has size 0. The
566/// effect:
567///
568/// - The path to the **heaviest compute chunk** (e.g. the long CUDA chain)
569/// is emitted FIRST — so on the auto-submitting device it is enqueued and
570/// running earliest, maximizing the window the other device's work
571/// overlaps. (Empirically: enqueuing the heavy CUDA chunk first is what
572/// makes the eager-submit overlap; the inverse order serializes.)
573/// - The next-heaviest device chunk is emitted next (its device's chunk is
574/// recorded while the first device runs).
575/// - A cross-device **drain** (the D2H `Op::Copy` feeding the join) has
576/// near-zero downstream compute weight, so it sorts AFTER both device
577/// chunks — exactly the A4b overlap topology (record/enqueue both chunks,
578/// THEN the drain whose fence-wait the other device's in-flight work
579/// hides). Among equal-weight ready runs, ties break toward a device
580/// DIFFERENT from the last emitted (interleave), then the smallest
581/// original index (determinism).
582///
583/// # The invariant — a HINT, never a correctness lever
584///
585/// Reordering INDEPENDENT runs changes only *when* work dispatches, never
586/// the result: the emitted order is always a valid topological order (a
587/// run after its producers), every op is bit-deterministic, and every
588/// cross-device wait/copy keys on a node's *inputs*, not on dispatch
589/// position — so no reorder can drop a wait or change a value. The output
590/// is byte-identical regardless of the reorder (proved by the
591/// reorder-invariance tests).
592///
593/// # The multi-device gate (single-device = identity)
594///
595/// If every run shares a single resolved device (≤ 1 distinct
596/// [`Run::device`] across the list), there is nothing to overlap, so this
597/// returns the identity permutation `0..runs.len()` and the lowering is
598/// **byte-identical to today's** topo-DFS order. The pass only diverges
599/// from the input order when the run list genuinely spans two or more
600/// devices.
601///
602/// # Determinism
603///
604/// Deterministic for a given run list: the priority key is
605/// `(−downstream_weight, not_different_device, original_index)`, fully
606/// ordered, so the reorder is reproducible and a degenerate input (one
607/// device) reproduces the input order exactly.
608///
609/// `runs` must be the partition [`extract_runs_multi`] produced for the
610/// same `graph` (the node→run mapping is rebuilt from `runs`), and the
611/// dependency edges are derived from each member's graph inputs.
612pub fn device_alternating_order(graph: &Graph, runs: &[Run]) -> Vec<usize> {
613 device_alternating_order_with_aliases(graph, runs, &HashMap::new())
614}
615
616/// [`device_alternating_order`] with ARM-EXIT ALIASES: `aliases[arm0_exit] = chosen_arm_exit` for every
617/// branch whose chosen arm is not arm 0. A reconverge node reads ARM 0's exit directly (the runnability
618/// invariant) and the executor aliases the chosen exit onto it, so when arm `k >= 1` is chosen and arm 0's
619/// run is skipped, the reconverge's run depends on the run holding arm `k`'s exit. Without the alias the
620/// dependency analysis sees no producer for that input and may emit the reconverge BEFORE the chosen arm
621/// (ROADMAP row 158: `input NodeId(6) of NodeId(7) not realized`). With an empty map this is exactly
622/// [`device_alternating_order`].
623pub fn device_alternating_order_with_aliases(
624 graph: &Graph,
625 runs: &[Run],
626 aliases: &HashMap<NodeId, NodeId>,
627) -> Vec<usize> {
628 let n = runs.len();
629 if n <= 1 {
630 return (0..n).collect();
631 }
632
633 // The multi-device gate: count distinct resolved devices. `None`
634 // (executor-default, no explicit backend) is its own bucket — a list
635 // that is all-`None` or all-one-backend has nothing to interleave.
636 let mut distinct: Vec<Option<BackendId>> = Vec::new();
637 for r in runs {
638 if !distinct.contains(&r.device) {
639 distinct.push(r.device);
640 }
641 }
642 if distinct.len() <= 1 {
643 // Single-device (or single executor-default) — identity. This is
644 // the byte-identical-to-today path (the headline single-device
645 // regression gate).
646 return (0..n).collect();
647 }
648
649 // node -> the index of the run that contains it (every reachable node
650 // is in exactly one run; the Branch node is not a member of any run,
651 // so a cross-run input that is a Branch node simply finds no producer
652 // run, which is correct — arms feed the reconverge, not the Branch).
653 let mut run_of: HashMap<NodeId, usize> = HashMap::new();
654 for (ri, r) in runs.iter().enumerate() {
655 for &m in &r.members {
656 run_of.insert(m, ri);
657 }
658 }
659
660 // Run-level dependency edges. Run `r` depends on run `s` (s != r) when
661 // some member of `r` reads a node that is a member of `s` (a cross-run
662 // input). `preds[r]` = the set of producer runs; `succs[s]` = the runs
663 // that read `s`; `indeg[r]` = count of not-yet-emitted producers.
664 let mut preds: Vec<HashSet<usize>> = vec![HashSet::new(); n];
665 let mut succs: Vec<Vec<usize>> = vec![Vec::new(); n];
666 for (ri, r) in runs.iter().enumerate() {
667 for &m in &r.members {
668 for &inp in &graph.node(m).inputs {
669 // A read of an arm-0 exit whose branch chose another arm is a read of the chosen exit.
670 let inp = aliases.get(&inp).copied().unwrap_or(inp);
671 if let Some(&pi) = run_of.get(&inp)
672 && pi != ri
673 && preds[ri].insert(pi)
674 {
675 succs[pi].push(ri);
676 }
677 }
678 }
679 }
680 let mut indeg: Vec<usize> = preds.iter().map(|p| p.len()).collect();
681
682 // Per-run COMPUTE size: node count for a real compute chunk, 0 for a
683 // pure cross-device TRANSFER (`Op::Copy`/`Op::Move` — always its own
684 // single-member run, the residency-seam boundary). A transfer is the
685 // run that FORCES a cross-device wait at dispatch (the executor drains
686 // the source / eager-submits + fences the in-flight batch when it hits a
687 // cross-device copy); it does no compute, so it weighs 0 and a drain is
688 // never the heaviest-downstream pick — it sorts after the compute chunks.
689 let compute_size = |ri: usize| -> u64 {
690 if matches!(
691 graph.node(runs[ri].entry).op,
692 Op::Copy { .. } | Op::Move { .. }
693 ) {
694 0
695 } else {
696 runs[ri].members.len() as u64
697 }
698 };
699
700 // `down_weight[r]` = the LARGEST compute chunk reachable from `r`
701 // downstream, including `r` itself — the critical-path priority. A
702 // memoized DFS over `succs` (the run-DAG is acyclic, so the recursion
703 // terminates; memoization makes it linear). Computed with an explicit
704 // stack (never-panic on deep graphs — no recursion).
705 let mut down_weight: Vec<u64> = vec![u64::MAX; n]; // MAX = not yet computed
706 for start in 0..n {
707 if down_weight[start] != u64::MAX {
708 continue;
709 }
710 // Post-order: push (node, children_done?).
711 let mut stack: Vec<(usize, bool)> = vec![(start, false)];
712 while let Some((r, done)) = stack.pop() {
713 if done {
714 let mut w = compute_size(r);
715 for &s in &succs[r] {
716 w = w.max(down_weight[s]);
717 }
718 down_weight[r] = w;
719 continue;
720 }
721 if down_weight[r] != u64::MAX {
722 continue;
723 }
724 // Tentatively mark in-progress so a (DAG-impossible) revisit
725 // doesn't loop; finalized on the `done` pass.
726 stack.push((r, true));
727 for &s in &succs[r] {
728 if down_weight[s] == u64::MAX {
729 stack.push((s, false));
730 }
731 }
732 }
733 }
734
735 // Kahn pump with critical-path priority. `ready` is every run whose
736 // producers are all emitted. Among the ready runs we pick the one whose
737 // priority key is smallest:
738 //
739 // ( -down_weight , not_different_device , original_index )
740 //
741 // i.e. (1) the LARGEST downstream compute chunk first — emit the path to
742 // the heaviest device chunk earliest so the auto-submitting device
743 // (CUDA) is enqueued + running before the deferred device's (Vulkan)
744 // host-blocking drain, which is what the eager-submit mechanism turns
745 // into overlap (and a drain weighs 0, so it sorts after both chunks);
746 // (2) among equal-weight ready runs, a device DIFFERENT from the last
747 // emitted (interleave); (3) the SMALLEST original index (determinism +
748 // topo stability — the degenerate single-device case already returned
749 // identity above). `ready` is a plain Vec scanned each step; run counts
750 // are tiny (a run is a whole straight-line chunk; the fewness gate keeps
751 // decision points sparse), so the O(ready) scan is cheap. This is a
752 // HINT: every emitted order is a valid topological order regardless of
753 // the priority (Kahn guarantees producers-first), so the result is
754 // byte-identical — only the dispatch timing changes.
755 let mut emitted: Vec<bool> = vec![false; n];
756 let mut ready: Vec<usize> = (0..n).filter(|&i| indeg[i] == 0).collect();
757 let mut order: Vec<usize> = Vec::with_capacity(n);
758 let mut last_device: Option<Option<BackendId>> = None;
759
760 while !ready.is_empty() {
761 // Priority key (smaller wins): heaviest downstream compute first,
762 // then a different device than last (interleave), then smallest idx.
763 let key_of = |ri: usize| -> (std::cmp::Reverse<u64>, bool, usize) {
764 let same_device = last_device.is_some_and(|ld| runs[ri].device == ld);
765 (std::cmp::Reverse(down_weight[ri]), same_device, ri)
766 };
767 let mut best_pos = 0usize;
768 let mut best_key = key_of(ready[0]);
769 for (pos, &ri) in ready.iter().enumerate().skip(1) {
770 let key = key_of(ri);
771 if key < best_key {
772 best_key = key;
773 best_pos = pos;
774 }
775 }
776 let ri = ready.swap_remove(best_pos);
777 emitted[ri] = true;
778 order.push(ri);
779 last_device = Some(runs[ri].device);
780
781 for &si in &succs[ri] {
782 if emitted[si] {
783 continue;
784 }
785 indeg[si] -= 1;
786 if indeg[si] == 0 {
787 ready.push(si);
788 }
789 }
790 }
791
792 // A cyclic run graph is impossible (the node graph is a DAG and runs
793 // partition it), so the pump emits every run. Defend never-panic: if
794 // somehow a run was not emitted (a structural surprise), fall back to
795 // the input order for the remainder so the lowering stays total rather
796 // than dropping work.
797 if order.len() != n {
798 #[expect(
799 clippy::needless_range_loop,
800 reason = "the bound `n` is the node count checked above (order.len() != n), not `emitted.len()`; enumerate could change the iteration count -- a wrong-number bug"
801 )]
802 for i in 0..n {
803 if !emitted[i] {
804 order.push(i);
805 }
806 }
807 }
808 order
809}
810
811/// **Streaming route-aware lowering** (Step E Phase C, PR C1) — the
812/// incremental form of [`lower_picked_route`]. Instead of taking a
813/// fully-resolved [`PickedRoute`] up front, it walks the run partition in
814/// topological order and **resolves each branch lazily, the first time the
815/// walk reaches one of its arm-entry runs**, by calling `resolve(branch)`.
816/// It emits only the chosen arm's runs (skipping the non-chosen arms),
817/// exactly like [`lower_picked_route`] — but the arm decision happens *at
818/// the frontier*, not before the walk.
819///
820/// This is the substrate that lets the runtime picker re-pick a branch's
821/// arm **by the live device load at the moment the frontier reaches it**
822/// (C2): the compiler thread drives this walk while the executor drains
823/// the previous runs, so `resolve` sees the load current to that decision
824/// point. `resolve` returns the chosen arm index for a branch (a stale /
825/// out-of-range index is clamped to arm 0 by the same skip logic, so it
826/// never panics — never-panic on a production path).
827///
828/// **Byte-identity with the one-shot lowering (the C1 gate).** Because
829/// `resolve` is the same per-branch decision the eager picker makes (the
830/// production VRAM-pressure chain reads only free-memory state, not walk
831/// progress), the route this walk accumulates equals
832/// `fuel_graph::PickedRoute` the eager `pick_route` produces, and the
833/// emitted order therefore equals `lower_picked_route(graph, roots,
834/// pick_route(..))` on every input. C1 changes *when* a branch resolves,
835/// never *which* arm — and a branchless graph never enters this walk at
836/// all (the caller's branchless fast path returns before streaming).
837/// `resolve` is invoked **at most once per branch** (memoized in the
838/// accumulated route), so a coupled downstream branch that reads upstream
839/// picks still resolves upstream-first (arm-entries of an upstream branch
840/// precede a downstream branch's in run-topo order).
841pub fn lower_picked_route_streaming<F>(
842 graph: &Graph,
843 roots: &[NodeId],
844 mut resolve: F,
845) -> Vec<NodeId>
846where
847 F: FnMut(NodeId) -> usize,
848{
849 let mut order = Vec::new();
850 walk_picked_route_streaming(graph, roots, &mut resolve, |members| {
851 order.extend_from_slice(members);
852 });
853 order
854}
855
856/// The callback core of the streaming lowering — the form the compiler
857/// thread drives so resolution and emission genuinely interleave (the
858/// thread compiles + dispatches each chosen run as the walk reaches it,
859/// rather than first materializing a flat order). `resolve(branch)` yields
860/// the chosen arm index at the frontier; `emit(&[NodeId])` receives each
861/// kept run's members in topological order. [`lower_picked_route_streaming`]
862/// is the `Vec`-collecting wrapper over this (used by the byte-identity
863/// test); the executor's compiler thread passes an `emit` that
864/// `compile_one`'s + sends each node.
865///
866/// Walks the run partition once, in topological order of run entries
867/// (identical to [`extract_runs_multi`]); at the first run that opens an
868/// arm of a not-yet-resolved branch it calls `resolve`, folds that
869/// branch's non-chosen arms into the skip set, then emits the run iff its
870/// entry is not skipped. See [`lower_picked_route_streaming`] for the
871/// byte-identity argument.
872pub fn walk_picked_route_streaming<R, E>(
873 graph: &Graph,
874 roots: &[NodeId],
875 mut resolve: R,
876 mut emit: E,
877) where
878 R: FnMut(NodeId) -> usize,
879 E: FnMut(&[NodeId]),
880{
881 let runs = extract_runs_multi(graph, roots);
882
883 // Per-branch lowering metadata, precomputed once from the reachable
884 // structure (cones + the diverge/shared prefix + each arm's entry
885 // node). The *decision* — which arm — is still deferred to `resolve`
886 // at the frontier; only the structure is precomputed.
887 let branch_meta = branch_arm_meta(graph, roots);
888
889 // arm-entry node -> the branches it opens an arm of. A node can be the
890 // arm-entry of more than one branch only in degenerate shared-prefix
891 // overlaps; resolving every such branch on first encounter is correct
892 // (each resolves independently) and keeps the walk single-pass.
893 let mut entry_to_branches: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
894 for meta in &branch_meta {
895 for &(entry, _arm) in &meta.arm_entries {
896 entry_to_branches
897 .entry(entry)
898 .or_default()
899 .push(meta.branch);
900 }
901 }
902 let meta_of: HashMap<NodeId, &BranchArmMeta> =
903 branch_meta.iter().map(|m| (m.branch, m)).collect();
904
905 let mut skip: HashSet<NodeId> = HashSet::new();
906 let mut resolved: HashSet<NodeId> = HashSet::new();
907
908 // PR-C3 composition: the device-alternating reorder (auto-overlap) runs
909 // over the kept runs, but it must NOT reorder across an unresolved
910 // branch decision (a downstream run's keep/skip depends on the arm
911 // picked upstream, and the picker reads live load AT the frontier, so
912 // moving a run past an unresolved branch would change what is even
913 // resolvable). So we reorder within **branch-free segments**: buffer
914 // kept runs; when the frontier reaches a run that resolves a NEW branch,
915 // FLUSH the buffered segment (device-alternation-reordered) BEFORE
916 // resolving, then start a fresh segment. The flush is the only place a
917 // reorder happens, and it never crosses a `resolve` call — so arm
918 // resolution stays strictly upstream-first and the reorder is confined
919 // to runs already committed to their devices. Branchless graphs (the
920 // auto-overlap benchmark + every existing multi-device live suite) have
921 // exactly one segment = the whole run list, so this is identical to the
922 // one-shot `lower_picked_route` reorder.
923 let mut segment: Vec<&Run> = Vec::new();
924 // `arm 0 exit -> chosen exit` for every resolved branch whose chosen arm is not arm 0.
925 let mut aliases: HashMap<NodeId, NodeId> = HashMap::new();
926 // Runs of a chosen non-zero arm that sit after the reconverge in `runs` and are emitted just before the
927 // reconverge's run instead (see `relocate_chosen_arm_runs`).
928 let mut relocated: HashSet<usize> = HashSet::new();
929 // Run index of a reconverge run -> the chosen arm's runs to emit just before it.
930 let mut before: HashMap<usize, Vec<usize>> = HashMap::new();
931 let run_of_entry: HashMap<NodeId, usize> =
932 runs.iter().enumerate().map(|(i, r)| (r.entry, i)).collect();
933 let flush = |segment: &mut Vec<&Run>, aliases: &HashMap<NodeId, NodeId>, emit: &mut E| {
934 if segment.is_empty() {
935 return;
936 }
937 // `device_alternating_order` wants `&[Run]`; collect the segment's
938 // runs (cheap — members are NodeId Vecs, but a segment is small).
939 let owned: Vec<Run> = segment.iter().map(|r| (*r).clone()).collect();
940 let perm = device_alternating_order_with_aliases(graph, &owned, aliases);
941 for &ri in &perm {
942 emit(lower_run(&owned[ri]));
943 }
944 segment.clear();
945 };
946
947 for (ri, run) in runs.iter().enumerate() {
948 if relocated.contains(&ri) {
949 continue; // emitted just before its branch's reconverge run
950 }
951 if let Some(pending) = before.remove(&ri) {
952 for rj in pending {
953 segment.push(&runs[rj]);
954 }
955 }
956 // Frontier reached this run's entry. If it opens an arm of one or
957 // more not-yet-resolved branches, the route past this point is about
958 // to be decided — flush the branch-free segment accumulated so far
959 // (reordered) BEFORE resolving, so no reorder crosses the decision.
960 if let Some(branches) = entry_to_branches.get(&run.entry) {
961 let opens_new = branches.iter().any(|b| !resolved.contains(b));
962 if opens_new {
963 flush(&mut segment, &aliases, &mut emit);
964 }
965 let mut newly_resolved = false;
966 for &branch in branches {
967 if !resolved.insert(branch) {
968 continue;
969 }
970 let meta = meta_of[&branch];
971 // Resolve NOW (reading live load via `resolve` once C2 lands); the skip set is
972 // recomputed from liveness below, before we decide whether to keep this run.
973 let chosen = clamp_arm(meta, resolve(branch));
974 note_alias(meta, chosen, &mut aliases);
975 newly_resolved = true;
976 // A chosen arm k >= 1 has runs late in `runs` (after the reconverge that reads them):
977 // emit those just before the reconverge's run, and skip them at their natural place.
978 if chosen != 0
979 && let Some(&rr) = run_of_entry.get(&meta.reconverge)
980 {
981 for rj in arm_run_indices(&runs, meta, chosen) {
982 if rj > rr && relocated.insert(rj) {
983 before.entry(rr).or_default().push(rj);
984 }
985 }
986 }
987 }
988 if newly_resolved {
989 // Branches resolved so far choose the route; unresolved ones default to arm 0.
990 skip = skipped_arm_nodes(graph, roots, &branch_meta, &aliases);
991 }
992 }
993 // A run is a single contiguous arm/region (extract never spans a
994 // branch boundary), so it is either wholly inside a non-chosen arm
995 // or wholly outside. Skip iff its entry is a skipped node; otherwise
996 // buffer it into the current branch-free segment (emitted at the
997 // next flush, device-alternation-reordered).
998 if skip.contains(&run.entry) {
999 continue;
1000 }
1001 segment.push(run);
1002 }
1003 // Flush the final branch-free segment (the post-region + any tail).
1004 flush(&mut segment, &aliases, &mut emit);
1005}
1006
1007/// Per-branch structural metadata for the streaming lowering: the branch
1008/// node, its arms' `(arm-entry node, arm index)` pairs, the per-arm
1009/// backward cones, and the shared diverge prefix. The arm *decision* is
1010/// not here — only the structure the skip-set computation needs once an
1011/// arm is chosen.
1012struct BranchArmMeta {
1013 branch: NodeId,
1014 /// The arm exits (`inputs` of the Branch node), arm 0 first.
1015 exits: Vec<NodeId>,
1016 /// The merge node (`Op::Branch { reconverge_at }`): the first run after the arms opens here.
1017 reconverge: NodeId,
1018 /// `(arm-entry node, arm index)` for each arm — the run entry that
1019 /// opens that arm. Used to detect, while walking runs, which branch a
1020 /// run opens an arm of.
1021 arm_entries: Vec<(NodeId, usize)>,
1022 /// Backward cone of each arm exit (`inputs[i]`), bounded to reachable.
1023 cones: Vec<HashSet<NodeId>>,
1024 /// Shared diverge prefix = intersection of every arm's cone.
1025 shared: HashSet<NodeId>,
1026}
1027
1028/// Precompute [`BranchArmMeta`] for every reachable ≥2-arm [`Op::Branch`].
1029/// Mirrors `non_chosen_arm_nodes`'s cone/shared-prefix derivation and
1030/// `compute_arm_entries`'s arm-entry recovery (the op carries only
1031/// `reconverge_at`, so the diverge prefix is recovered as the cone
1032/// intersection), so the streaming skip set is byte-identical to the
1033/// one-shot `non_chosen_arm_nodes` for the same picks.
1034fn branch_arm_meta(graph: &Graph, roots: &[NodeId]) -> Vec<BranchArmMeta> {
1035 let eff_roots = effective_roots(graph, roots);
1036 let order = topo_order_multi(graph, &eff_roots);
1037 let reachable: HashSet<NodeId> = order.iter().copied().collect();
1038
1039 let mut metas = Vec::new();
1040 for &id in &order {
1041 let Op::Branch { reconverge_at } = graph.node(id).op else {
1042 continue;
1043 };
1044 let arm_exits = graph.node(id).inputs.clone();
1045 if arm_exits.len() < 2 {
1046 continue;
1047 }
1048 let cones: Vec<HashSet<NodeId>> = arm_exits
1049 .iter()
1050 .map(|&e| backward_cone(graph, e, &reachable))
1051 .collect();
1052 let mut shared: HashSet<NodeId> = cones[0].clone();
1053 for c in &cones[1..] {
1054 shared = shared.intersection(c).copied().collect();
1055 }
1056 // Each arm's entry: the interior node (cone minus shared) whose
1057 // sole/any predecessor lies in the shared prefix — where the arm
1058 // departs from the diverge region (mirrors `compute_arm_entries`).
1059 let mut arm_entries: Vec<(NodeId, usize)> = Vec::new();
1060 for (arm_idx, cone) in cones.iter().enumerate() {
1061 for &n in cone {
1062 if shared.contains(&n) {
1063 continue;
1064 }
1065 let departs = graph.node(n).inputs.iter().any(|p| shared.contains(p));
1066 if departs {
1067 arm_entries.push((n, arm_idx));
1068 }
1069 }
1070 }
1071 metas.push(BranchArmMeta {
1072 branch: id,
1073 exits: arm_exits.clone(),
1074 reconverge: reconverge_at,
1075 arm_entries,
1076 cones,
1077 shared,
1078 });
1079 }
1080 metas
1081}
1082
1083/// The set of nodes that belong to a **non-chosen arm** of some reachable
1084/// [`Op::Branch`] — the nodes the route-aware lowering skips. The arm-0
1085/// generalization: when `picked` is empty (or a branch is absent from
1086/// it), the chosen arm defaults to arm 0, so this reduces to the former
1087/// `non_arm0_arm_nodes`.
1088///
1089/// For each reachable branch, the chosen arm is `inputs[chosen]`
1090/// (`chosen = picked[branch]`, default 0) and the non-chosen arms are
1091/// every other input. The shared prefix (the diverge region) is the
1092/// intersection of every arm exit's backward cone (PR-A2's
1093/// `compute_arm_entries` recovers the diverge the same way — the op
1094/// carries `reconverge_at`, not the diverge). A node is skipped when it
1095/// lies in a non-chosen arm's cone but is neither shared nor part of the
1096/// chosen arm's cone — i.e. it is interior to a route the picker did not
1097/// take. Arms are internally disjoint by the PR-A1 build-time
1098/// validation, so these sets don't overlap the chosen arm.
1099fn non_chosen_arm_nodes(graph: &Graph, roots: &[NodeId], picked: &PickedRoute) -> HashSet<NodeId> {
1100 let metas = branch_arm_meta(graph, roots);
1101 // The chosen arm per branch defaults to arm 0 (the winner) for any branch the picker did not
1102 // resolve, and a stale or out-of-range pick clamps to arm 0 (never panic on a production path).
1103 let mut aliases: HashMap<NodeId, NodeId> = HashMap::new();
1104 for meta in &metas {
1105 let chosen = clamp_arm(meta, picked.get(&meta.branch).copied().unwrap_or(0));
1106 note_alias(meta, chosen, &mut aliases);
1107 }
1108 skipped_arm_nodes(graph, roots, &metas, &aliases)
1109}
1110
1111/// Nodes inside some branch's arm (an arm's backward cone minus the prefix every arm of that branch
1112/// shares) that are NOT live under the route `aliases` describes (`arm 0 exit -> chosen exit` for every
1113/// branch whose chosen arm is not arm 0): the nodes the route-aware lowering skips.
1114///
1115/// Liveness, not per-branch cones: the residency pass shares one inbound `Copy` between regions (CSE), so
1116/// a node can sit in one branch's non-chosen arm and another branch's chosen arm, and it must run; and a
1117/// chosen arm-0 cone reaches back through the runnability edge (a reconverge reads arm 0's exit) into an
1118/// earlier branch's arm 0, which a route that chose that branch's arm 1 never runs (ROADMAP row 158).
1119fn skipped_arm_nodes(
1120 graph: &Graph,
1121 roots: &[NodeId],
1122 metas: &[BranchArmMeta],
1123 aliases: &HashMap<NodeId, NodeId>,
1124) -> HashSet<NodeId> {
1125 let live = live_nodes(graph, roots, aliases);
1126 let mut skip: HashSet<NodeId> = HashSet::new();
1127 for meta in metas {
1128 for cone in &meta.cones {
1129 for &n in cone {
1130 if !meta.shared.contains(&n) && !live.contains(&n) {
1131 skip.insert(n);
1132 }
1133 }
1134 }
1135 }
1136 skip
1137}
1138
1139/// Nodes reachable backward from `roots` when a read of an arm-0 exit that `aliases` maps reads the chosen
1140/// arm's exit instead (the executor's alias of the chosen exit onto arm 0's exit).
1141fn live_nodes(
1142 graph: &Graph,
1143 roots: &[NodeId],
1144 aliases: &HashMap<NodeId, NodeId>,
1145) -> HashSet<NodeId> {
1146 let mut live: HashSet<NodeId> = HashSet::new();
1147 let mut stack: Vec<NodeId> = roots.to_vec();
1148 while let Some(n) = stack.pop() {
1149 if !live.insert(n) {
1150 continue;
1151 }
1152 for &input in &graph.node(n).inputs {
1153 let input = aliases.get(&input).copied().unwrap_or(input);
1154 if !live.contains(&input) {
1155 stack.push(input);
1156 }
1157 }
1158 }
1159 live
1160}
1161
1162/// Branch density: the share of reachable nodes that are decision
1163/// points ([`Op::Branch`] nodes), over `root`.
1164///
1165/// The **fewness gate** — deliberate-fork branching must stay sparse
1166/// (the granularity crux locked before Phase B). A real decode graph
1167/// branches only at "layer" boundaries and sits far below the threshold;
1168/// a synthetic per-op-branch graph blows past it.
1169pub fn branch_density(graph: &Graph, root: NodeId) -> f32 {
1170 branch_density_multi(graph, &[root])
1171}
1172
1173/// Multi-root variant of [`branch_density`].
1174pub fn branch_density_multi(graph: &Graph, roots: &[NodeId]) -> f32 {
1175 let eff_roots = effective_roots(graph, roots);
1176 let order = topo_order_multi(graph, &eff_roots);
1177 if order.is_empty() {
1178 return 0.0;
1179 }
1180 let branches = order
1181 .iter()
1182 .filter(|&&id| matches!(graph.node(id).op, Op::Branch { .. }))
1183 .count();
1184 branches as f32 / order.len() as f32
1185}
1186
1187/// The fewness-gate threshold: branch points must be at most ~5% of
1188/// reachable nodes. Deliberate-fork branching stays this sparse;
1189/// per-op branching does not.
1190pub const FEWNESS_THRESHOLD: f32 = 0.05;
1191
1192/// Whether the graph passes the fewness gate over `root` (branch
1193/// density strictly below [`FEWNESS_THRESHOLD`]).
1194pub fn passes_fewness_gate(graph: &Graph, root: NodeId) -> bool {
1195 branch_density(graph, root) < FEWNESS_THRESHOLD
1196}
1197
1198#[cfg(test)]
1199mod tests {
1200 use super::*;
1201 use crate::Node;
1202 use fuel_ir::{DType, Shape};
1203
1204 fn f32_node(g: &mut Graph, op: Op, inputs: Vec<NodeId>) -> NodeId {
1205 g.push(Node {
1206 op,
1207 inputs,
1208 shape: Shape::from_dims(&[2]),
1209 dtype: DType::F32,
1210 })
1211 }
1212
1213 /// Hand-build the same 2-arm diamond the branch-builder tests use,
1214 /// then finalize it into a real `Op::Branch`. Returns the graph and
1215 /// `(diverge, arm0, arm1, reconverge, branch)`.
1216 ///
1217 /// Topology: `diverge -> {arm0, arm1}`; `reconverge` reads arm0 (the
1218 /// runnability invariant); a `Branch` node merges {arm0, arm1} with
1219 /// `reconverge_at = reconverge`. `post` reads `reconverge` so the
1220 /// post-merge region is non-empty.
1221 fn diamond_with_branch() -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId, NodeId) {
1222 let mut g = Graph::new();
1223 let pre = f32_node(&mut g, Op::Const, vec![]);
1224 let diverge = f32_node(&mut g, Op::Relu, vec![pre]);
1225 let arm0 = f32_node(&mut g, Op::Silu, vec![diverge]);
1226 let arm1 = f32_node(&mut g, Op::GeluTanh, vec![diverge]);
1227 // reconverge reads arm0 (arm-0 runnability).
1228 let reconverge = f32_node(&mut g, Op::Relu, vec![arm0]);
1229 let mut b = g.open_branch(diverge);
1230 b.add_arm(arm0);
1231 b.add_arm(arm1);
1232 let branch = b
1233 .finalize_branches(&mut g, reconverge)
1234 .expect("well-formed 2-arm branch finalizes")
1235 .expect("2 arms survive");
1236 // A post node that reads the merge, so there is a real post-run.
1237 let post = f32_node(&mut g, Op::Tanh, vec![reconverge]);
1238 (g, diverge, arm0, arm1, reconverge, branch, post)
1239 }
1240
1241 /// (a) A straight-line graph with no branches extracts to exactly
1242 /// ONE run covering all reachable nodes, single-entry / single-exit.
1243 #[test]
1244 fn straight_line_extracts_to_one_run() {
1245 let mut g = Graph::new();
1246 let a = f32_node(&mut g, Op::Const, vec![]);
1247 let b = f32_node(&mut g, Op::Relu, vec![a]);
1248 let c = f32_node(&mut g, Op::Silu, vec![b]);
1249 let d = f32_node(&mut g, Op::Tanh, vec![c]);
1250
1251 let runs = extract_runs(&g, d);
1252 assert_eq!(runs.len(), 1, "a straight-line graph is exactly one run");
1253 let run = &runs[0];
1254 assert_eq!(run.entry, a, "the run enters at the source");
1255 assert_eq!(run.exit, d, "the run exits at the root");
1256 assert_eq!(
1257 run.members,
1258 vec![a, b, c, d],
1259 "the single run covers every reachable node in topo order",
1260 );
1261 // single-device: no explicit backend anywhere -> None.
1262 assert_eq!(run.device, None);
1263 // lower_run reproduces the ordered members.
1264 assert_eq!(lower_run(run), &[a, b, c, d]);
1265 }
1266
1267 /// (b) A finalized 2-arm branch extracts to exactly four runs —
1268 /// {pre-run, arm0-run, arm1-run, post-run} — each single-entry /
1269 /// single-exit.
1270 #[test]
1271 fn two_arm_branch_extracts_to_four_runs() {
1272 let (g, diverge, arm0, arm1, reconverge, _branch, post) = diamond_with_branch();
1273
1274 let runs = extract_runs(&g, post);
1275
1276 // Each run is single-entry/single-exit by construction.
1277 for r in &runs {
1278 assert_eq!(r.entry, r.members[0]);
1279 assert_eq!(r.exit, *r.members.last().unwrap());
1280 assert!(!r.members.is_empty());
1281 }
1282
1283 // Locate the run that contains each landmark node.
1284 let run_of = |node: NodeId| -> usize {
1285 runs.iter()
1286 .position(|r| r.members.contains(&node))
1287 .unwrap_or_else(|| panic!("no run contains Node#{}", node.0))
1288 };
1289 let pre_run = run_of(diverge);
1290 let arm0_run = run_of(arm0);
1291 let arm1_run = run_of(arm1);
1292 let post_run = run_of(reconverge);
1293
1294 // Four distinct runs: pre, arm0, arm1, post.
1295 let distinct: HashSet<usize> = [pre_run, arm0_run, arm1_run, post_run]
1296 .into_iter()
1297 .collect();
1298 assert_eq!(
1299 distinct.len(),
1300 4,
1301 "a 2-arm branch yields exactly {{pre, arm0, arm1, post}} = 4 runs; got runs={runs:?}",
1302 );
1303 assert_eq!(runs.len(), 4, "no run beyond the four; got {runs:?}");
1304
1305 // arm0 and arm1 are in *different* runs (a run never spans a
1306 // branch boundary).
1307 assert_ne!(arm0_run, arm1_run, "the two arms must be separate runs");
1308 // diverge is upstream of both arms and in neither arm's run.
1309 assert_ne!(pre_run, arm0_run);
1310 assert_ne!(pre_run, arm1_run);
1311 // the post region (reconverge + Branch + post) is its own run.
1312 assert!(runs[post_run].members.contains(&post));
1313 }
1314
1315 /// PR-A4 arm-0 single-route lowering: [`lower_runs_arm0`] follows
1316 /// arm 0 through the branch (pre, arm0, post) and SKIPS arm 1's run.
1317 /// arm 1's interior node never appears; arm 0's does. On a branchless
1318 /// graph it is identical to concatenating [`lower_run`] over the runs.
1319 #[test]
1320 fn lower_runs_arm0_follows_arm0_and_skips_other_arms() {
1321 let (g, diverge, arm0, arm1, reconverge, _branch, post) = diamond_with_branch();
1322
1323 let order = lower_runs_arm0(&g, &[post]);
1324
1325 // arm 1's interior is skipped; arm 0 + pre + post execute.
1326 assert!(
1327 !order.contains(&arm1),
1328 "arm-0 lowering skips arm 1's run; order={order:?} arm1={arm1:?}",
1329 );
1330 assert!(order.contains(&diverge), "the pre-run (diverge) executes");
1331 assert!(order.contains(&arm0), "arm 0 executes");
1332 assert!(order.contains(&reconverge), "the reconverge executes");
1333 assert!(order.contains(&post), "the post-run executes");
1334 // The phi/merge Branch node is structural — never an executable
1335 // member.
1336 for &id in &order {
1337 assert!(
1338 !matches!(g.node(id).op, Op::Branch { .. }),
1339 "the Branch node is never an executable member",
1340 );
1341 }
1342
1343 // Branchless: identical to concatenating lower_run over runs.
1344 let mut g2 = Graph::new();
1345 let a = f32_node(&mut g2, Op::Const, vec![]);
1346 let b = f32_node(&mut g2, Op::Relu, vec![a]);
1347 let c = f32_node(&mut g2, Op::Silu, vec![b]);
1348 let d = f32_node(&mut g2, Op::Tanh, vec![c]);
1349 let flat: Vec<NodeId> = extract_runs(&g2, d)
1350 .iter()
1351 .flat_map(|r| lower_run(r).to_vec())
1352 .collect();
1353 assert_eq!(
1354 lower_runs_arm0(&g2, &[d]),
1355 flat,
1356 "on a branchless graph the arm-0 lowering equals the flat concatenation",
1357 );
1358 }
1359
1360 /// PR-C1 (e) route-aware lowering: [`lower_picked_route`] follows the
1361 /// **chosen** arm and skips the non-chosen arms' runs, and equals
1362 /// [`lower_runs_arm0`] when every pick is arm 0 (the empty route).
1363 ///
1364 /// On the 2-arm diamond:
1365 /// - empty route (== arm 0 everywhere): arm 0 in, arm 1 out, and
1366 /// byte-identical to `lower_runs_arm0`.
1367 /// - pick arm 1 for the branch: arm 1 in, arm 0's interior out — the
1368 /// mirror image, proving the lowering follows the picked arm rather
1369 /// than hard-coding arm 0.
1370 #[test]
1371 fn lower_picked_route_follows_chosen_arm_and_skips_others() {
1372 let (g, _diverge, arm0, arm1, _reconverge, branch, post) = diamond_with_branch();
1373
1374 // (1) Empty route == arm-0 everywhere == lower_runs_arm0.
1375 let empty = PickedRoute::new();
1376 let route_order = lower_picked_route(&g, &[post], &empty);
1377 let arm0_order = lower_runs_arm0(&g, &[post]);
1378 assert_eq!(
1379 route_order, arm0_order,
1380 "the empty route lowers byte-identically to lower_runs_arm0",
1381 );
1382 assert!(route_order.contains(&arm0), "empty route follows arm 0");
1383 assert!(
1384 !route_order.contains(&arm1),
1385 "empty route skips arm 1's run; order={route_order:?}",
1386 );
1387
1388 // (2) Pick arm 1 for the branch — now arm 1 is followed, arm 0's
1389 // interior is skipped.
1390 let mut picked = PickedRoute::new();
1391 picked.insert(branch, 1);
1392 let order = lower_picked_route(&g, &[post], &picked);
1393 assert!(
1394 order.contains(&arm1),
1395 "picking arm 1 follows arm 1's run; order={order:?}",
1396 );
1397 assert!(
1398 !order.contains(&arm0),
1399 "picking arm 1 skips arm 0's interior run; order={order:?}",
1400 );
1401 // The Branch node is never an executable member regardless of pick.
1402 for &id in &order {
1403 assert!(
1404 !matches!(g.node(id).op, Op::Branch { .. }),
1405 "the Branch node is never an executable member",
1406 );
1407 }
1408
1409 // (3) A branch absent from the route still defaults to arm 0.
1410 let absent = PickedRoute::new();
1411 let absent_order = lower_picked_route(&g, &[post], &absent);
1412 assert_eq!(
1413 absent_order, arm0_order,
1414 "a branch the picker did not resolve defaults to arm 0",
1415 );
1416
1417 // (4) An out-of-range pick degrades to arm 0 (never panic).
1418 let mut bad = PickedRoute::new();
1419 bad.insert(branch, 99);
1420 let bad_order = lower_picked_route(&g, &[post], &bad);
1421 assert_eq!(
1422 bad_order, arm0_order,
1423 "an out-of-range arm index clamps to arm 0 rather than panicking",
1424 );
1425 }
1426
1427 /// **Optimize-time variant bake (collapse) — the graph-side primitive.**
1428 /// `Graph::collapse_variant_branch(branch, winner)` rewires the decision
1429 /// point so the chosen arm is the realized route WITHOUT any runtime pick
1430 /// (kernel-variant choice baked at optimize time):
1431 ///
1432 /// - collapse to arm 1 ⇒ `reconverge` reads arm 1, the branch is a single
1433 /// inert arm `[arm1]`, and `lower_runs_arm0` (the empty-route lowering)
1434 /// now follows arm 1 and drops arm 0's interior — the mirror image of the
1435 /// default, achieved structurally rather than via a `PickedRoute`;
1436 /// - collapse to arm 0 ⇒ the merge is unchanged, the branch reduces to
1437 /// `[arm0]`, and the lowering is byte-identical to today (arm 1 pruned).
1438 #[test]
1439 fn collapse_variant_branch_bakes_the_winner_into_the_route() {
1440 // --- (a) collapse to the variant arm (arm 1) ---
1441 let (mut g, _diverge, arm0, arm1, reconverge, branch, post) = diamond_with_branch();
1442 // Before: default lowering realizes arm 0 (the finding — a same-device
1443 // variant arm is never selected).
1444 let before = lower_runs_arm0(&g, &[post]);
1445 assert!(
1446 before.contains(&arm0) && !before.contains(&arm1),
1447 "before the bake the default route is arm 0"
1448 );
1449
1450 g.collapse_variant_branch(branch, 1)
1451 .expect("collapse to arm 1");
1452
1453 // The merge now reads the winner (arm 1); the branch is a single arm.
1454 assert!(
1455 g.node(reconverge).inputs.contains(&arm1),
1456 "reconverge rewired to read the baked winner (arm 1)"
1457 );
1458 assert!(
1459 !g.node(reconverge).inputs.contains(&arm0),
1460 "reconverge no longer reads the pruned arm 0"
1461 );
1462 assert_eq!(
1463 g.node(branch).inputs,
1464 vec![arm1],
1465 "the branch collapsed to the single winning arm"
1466 );
1467
1468 // The empty-route lowering now follows the baked winner (arm 1) and
1469 // drops arm 0's interior — with NO PickedRoute.
1470 let after = lower_runs_arm0(&g, &[post]);
1471 assert!(
1472 after.contains(&arm1),
1473 "after the bake the default route follows the winner (arm 1); order={after:?}"
1474 );
1475 assert!(
1476 !after.contains(&arm0),
1477 "after the bake arm 0's interior is pruned; order={after:?}"
1478 );
1479
1480 // --- (b) collapse to arm 0 is byte-identical to today (arm 1 pruned) ---
1481 let (mut g2, _d2, a0_2, a1_2, recon2, branch2, post2) = diamond_with_branch();
1482 let recon2_inputs_before = g2.node(recon2).inputs.clone();
1483 g2.collapse_variant_branch(branch2, 0)
1484 .expect("collapse to arm 0");
1485 assert_eq!(
1486 g2.node(recon2).inputs,
1487 recon2_inputs_before,
1488 "arm-0 collapse leaves the merge unchanged"
1489 );
1490 assert_eq!(
1491 g2.node(branch2).inputs,
1492 vec![a0_2],
1493 "arm-0 collapse reduces the branch to [arm0] (variant arm pruned)"
1494 );
1495 let order2 = lower_runs_arm0(&g2, &[post2]);
1496 assert!(
1497 order2.contains(&a0_2) && !order2.contains(&a1_2),
1498 "arm-0 collapse realizes arm 0 (byte-identical to today)"
1499 );
1500
1501 // --- (c) never-panic guards: bad node / out-of-range winner / non-branch ---
1502 let (mut g3, _d3, _a0_3, _a1_3, _r3, branch3, post3) = diamond_with_branch();
1503 assert!(
1504 g3.collapse_variant_branch(NodeId(9999), 0).is_err(),
1505 "out-of-bounds branch node ⇒ Err, not panic"
1506 );
1507 assert!(
1508 g3.collapse_variant_branch(branch3, 7).is_err(),
1509 "out-of-range winner_arm ⇒ Err, not panic"
1510 );
1511 assert!(
1512 g3.collapse_variant_branch(post3, 0).is_err(),
1513 "non-Op::Branch node ⇒ Err, not panic"
1514 );
1515 }
1516
1517 /// Build two coupled diamonds back-to-back (diamond-2 diverges off
1518 /// diamond-1's reconverge) so the streaming-walk equality test exercises
1519 /// upstream-first lazy resolution over more than one branch. Returns the
1520 /// graph + `(branch1, branch2, post, arm1_of_b1, arm1_of_b2)`.
1521 fn two_coupled_diamonds() -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId) {
1522 let mut g = Graph::new();
1523 let pre = f32_node(&mut g, Op::Const, vec![]);
1524 // diamond 1
1525 let div1 = f32_node(&mut g, Op::Relu, vec![pre]);
1526 let a0_1 = f32_node(&mut g, Op::Silu, vec![div1]);
1527 let a1_1 = f32_node(&mut g, Op::GeluTanh, vec![div1]);
1528 let recon1 = f32_node(&mut g, Op::Relu, vec![a0_1]);
1529 let mut b1 = g.open_branch(div1);
1530 b1.add_arm(a0_1);
1531 b1.add_arm(a1_1);
1532 let branch1 = b1
1533 .finalize_branches(&mut g, recon1)
1534 .expect("branch1 valid")
1535 .expect("2 arms");
1536 // diamond 2 (downstream of diamond 1's merge)
1537 let div2 = f32_node(&mut g, Op::Tanh, vec![recon1]);
1538 let a0_2 = f32_node(&mut g, Op::Silu, vec![div2]);
1539 let a1_2 = f32_node(&mut g, Op::GeluTanh, vec![div2]);
1540 let recon2 = f32_node(&mut g, Op::Relu, vec![a0_2]);
1541 let mut b2 = g.open_branch(div2);
1542 b2.add_arm(a0_2);
1543 b2.add_arm(a1_2);
1544 let branch2 = b2
1545 .finalize_branches(&mut g, recon2)
1546 .expect("branch2 valid")
1547 .expect("2 arms");
1548 let post = f32_node(&mut g, Op::Tanh, vec![recon2]);
1549 (g, branch1, branch2, post, a1_1, a1_2)
1550 }
1551
1552 /// **C1 byte-identity gate (fuel-graph layer).** The streaming lowering
1553 /// — which resolves each branch lazily, at the run-walk frontier, via a
1554 /// closure — emits the SAME `NodeId` order as the one-shot
1555 /// [`lower_picked_route`] over the route the same closure would produce,
1556 /// for every combination of arm picks across one and two branches. This
1557 /// is the structural proof that C1 changes *when* a branch resolves, not
1558 /// *which* arm it picks (or the order it emits).
1559 #[test]
1560 fn streaming_lowering_equals_one_shot_on_every_pick() {
1561 // --- single diamond: all four pick combinations ---
1562 let (g, _diverge, _arm0, _arm1, _reconverge, branch, post) = diamond_with_branch();
1563 for chosen in [0usize, 1, 99] {
1564 // One-shot: build the route then lower.
1565 let mut route = PickedRoute::new();
1566 if chosen != 0 {
1567 route.insert(branch, chosen);
1568 }
1569 let one_shot = lower_picked_route(&g, &[post], &route);
1570 // Streaming: resolve the branch lazily at its arm-entry.
1571 let streamed = lower_picked_route_streaming(&g, &[post], |b| {
1572 assert_eq!(b, branch, "only the diamond's branch is resolved");
1573 chosen
1574 });
1575 assert_eq!(
1576 streamed, one_shot,
1577 "streamed order must equal one-shot for branch pick {chosen}",
1578 );
1579 }
1580
1581 // --- two coupled diamonds: every (arm1, arm2) combination ---
1582 let (g2, branch1, branch2, post2, _a1_1, _a1_2) = two_coupled_diamonds();
1583 for c1 in [0usize, 1] {
1584 for c2 in [0usize, 1] {
1585 let mut route = PickedRoute::new();
1586 if c1 != 0 {
1587 route.insert(branch1, c1);
1588 }
1589 if c2 != 0 {
1590 route.insert(branch2, c2);
1591 }
1592 let one_shot = lower_picked_route(&g2, &[post2], &route);
1593
1594 // The streaming closure resolves each branch at most once
1595 // and upstream-first (branch1 before branch2). Assert that
1596 // discipline AND the resulting byte-identity.
1597 let mut seen: Vec<NodeId> = Vec::new();
1598 let streamed = lower_picked_route_streaming(&g2, &[post2], |b| {
1599 assert!(
1600 !seen.contains(&b),
1601 "each branch is resolved at most once; b={b:?} seen={seen:?}",
1602 );
1603 seen.push(b);
1604 if b == branch1 {
1605 c1
1606 } else if b == branch2 {
1607 c2
1608 } else {
1609 panic!("unexpected branch {b:?}")
1610 }
1611 });
1612 assert_eq!(
1613 seen,
1614 vec![branch1, branch2],
1615 "coupled branches resolve upstream-first at the frontier",
1616 );
1617 assert_eq!(
1618 streamed, one_shot,
1619 "streamed == one-shot for picks ({c1},{c2})",
1620 );
1621 }
1622 }
1623 }
1624
1625 /// (c) A `target_backend` change mid-chain (set via the existing
1626 /// accessor) starts a new run — a residency seam.
1627 #[test]
1628 fn residency_seam_starts_new_run() {
1629 let mut g = Graph::new();
1630 let a = f32_node(&mut g, Op::Const, vec![]);
1631 let b = f32_node(&mut g, Op::Relu, vec![a]);
1632 let c = f32_node(&mut g, Op::Silu, vec![b]);
1633 let d = f32_node(&mut g, Op::Tanh, vec![c]);
1634 // a,b live on CPU; c,d live on CUDA -> a seam between b and c.
1635 g.set_target_backend(a, BackendId::Cpu);
1636 g.set_target_backend(b, BackendId::Cpu);
1637 g.set_target_backend(c, BackendId::Cuda);
1638 g.set_target_backend(d, BackendId::Cuda);
1639
1640 let runs = extract_runs(&g, d);
1641 assert_eq!(
1642 runs.len(),
1643 2,
1644 "a residency change mid-chain cuts the chain into two runs; got {runs:?}",
1645 );
1646 assert_eq!(runs[0].members, vec![a, b]);
1647 assert_eq!(runs[0].device, Some(BackendId::Cpu));
1648 assert_eq!(runs[1].members, vec![c, d]);
1649 assert_eq!(runs[1].device, Some(BackendId::Cuda));
1650 }
1651
1652 /// (d) A multi-predecessor fan-in starts a fresh run: the joining
1653 /// node is the entry of a new run, distinct from either feeder run.
1654 #[test]
1655 fn fan_in_starts_new_run() {
1656 let mut g = Graph::new();
1657 // Two independent feeders that join at `sum`.
1658 let a = f32_node(&mut g, Op::Const, vec![]);
1659 let a1 = f32_node(&mut g, Op::Relu, vec![a]);
1660 let b = f32_node(&mut g, Op::Const, vec![]);
1661 let b1 = f32_node(&mut g, Op::Silu, vec![b]);
1662 let sum = f32_node(&mut g, Op::Add, vec![a1, b1]);
1663
1664 let runs = extract_runs(&g, sum);
1665 // The fan-in node `sum` must be the entry of its own run.
1666 let sum_run = runs
1667 .iter()
1668 .find(|r| r.members.contains(&sum))
1669 .expect("sum is in some run");
1670 assert_eq!(
1671 sum_run.entry, sum,
1672 "a fan-in node starts a fresh run (it is that run's entry)",
1673 );
1674 // `sum` shares a run with neither feeder chain.
1675 assert!(
1676 !sum_run.members.contains(&a1) && !sum_run.members.contains(&b1),
1677 "the fan-in run does not absorb either feeder; got {sum_run:?}",
1678 );
1679 }
1680
1681 /// (e) Fewness gate — PASS side: a graph that branches only at a
1682 /// "layer" boundary sits below the ~5% threshold.
1683 #[test]
1684 fn fewness_gate_passes_on_sparse_branching() {
1685 // A long straight-line "model" with a single deliberate branch.
1686 let mut g = Graph::new();
1687 let mut prev = f32_node(&mut g, Op::Const, vec![]);
1688 // ~40 ops of straight-line body.
1689 let mut body: Vec<NodeId> = vec![prev];
1690 for _ in 0..40 {
1691 prev = f32_node(&mut g, Op::Relu, vec![prev]);
1692 body.push(prev);
1693 }
1694 // One deliberate fork off `prev` (the layer boundary).
1695 let diverge = prev;
1696 let arm0 = f32_node(&mut g, Op::Silu, vec![diverge]);
1697 let arm1 = f32_node(&mut g, Op::GeluTanh, vec![diverge]);
1698 let reconverge = f32_node(&mut g, Op::Relu, vec![arm0]);
1699 let mut b = g.open_branch(diverge);
1700 b.add_arm(arm0);
1701 b.add_arm(arm1);
1702 b.finalize_branches(&mut g, reconverge)
1703 .expect("valid branch")
1704 .expect("2 arms survive");
1705 let root = f32_node(&mut g, Op::Tanh, vec![reconverge]);
1706
1707 let density = branch_density(&g, root);
1708 assert!(
1709 density < FEWNESS_THRESHOLD,
1710 "sparse layer-boundary branching must pass the fewness gate; density={density}",
1711 );
1712 assert!(passes_fewness_gate(&g, root));
1713 }
1714
1715 /// (e) Fewness gate — FAIL side: a synthetic graph that forks at
1716 /// (nearly) every op blows past the ~5% threshold.
1717 #[test]
1718 fn fewness_gate_fails_on_per_op_branching() {
1719 // Build a chain of N diamonds back-to-back, so a large fraction
1720 // of nodes are Op::Branch decision points.
1721 let mut g = Graph::new();
1722 let mut prev = f32_node(&mut g, Op::Const, vec![]);
1723 for _ in 0..12 {
1724 let diverge = prev;
1725 let arm0 = f32_node(&mut g, Op::Silu, vec![diverge]);
1726 let arm1 = f32_node(&mut g, Op::GeluTanh, vec![diverge]);
1727 let reconverge = f32_node(&mut g, Op::Relu, vec![arm0]);
1728 let mut b = g.open_branch(diverge);
1729 b.add_arm(arm0);
1730 b.add_arm(arm1);
1731 b.finalize_branches(&mut g, reconverge)
1732 .expect("valid branch")
1733 .expect("2 arms survive");
1734 prev = reconverge;
1735 }
1736 let root = prev;
1737
1738 let density = branch_density(&g, root);
1739 assert!(
1740 density >= FEWNESS_THRESHOLD,
1741 "per-op branching must FAIL the fewness gate; density={density}",
1742 );
1743 assert!(!passes_fewness_gate(&g, root));
1744 }
1745
1746 // ===== PR-C3: device-alternating reorder (auto-overlap) =====
1747
1748 /// Build the "arbitrary graph" the auto-overlap benchmark needs WITHOUT
1749 /// the hand-constructed crutch: two INDEPENDENT same-length device
1750 /// chains (one CUDA, one Vulkan) over distinct consts, reconverging at a
1751 /// final CUDA `add`. The reconverge inputs are `[cuda_root, vulkan_root]`
1752 /// — the "wrong" order that the un-reordered topo DFS pops CUDA-last, so
1753 /// it would emit the Vulkan chain + its cross-device copy FIRST (host
1754 /// blocks on Vulkan before CUDA is enqueued → serialized). One explicit
1755 /// `Op::Copy{target:Cuda}` bridges the Vulkan root to the CUDA
1756 /// reconverge (a run boundary). Returns `(graph, root, cuda_chain_nodes,
1757 /// vk_chain_nodes, copy_node)`.
1758 fn two_device_reconverge(
1759 cuda_len: usize,
1760 vk_len: usize,
1761 ) -> (Graph, NodeId, Vec<NodeId>, Vec<NodeId>, NodeId) {
1762 let mut g = Graph::new();
1763 // Distinct consts, one per device (CPU-resident sources H2D'd to
1764 // each device — modeled here as the chain heads carrying the device
1765 // stamp; the const itself is unplaced/default).
1766 let cc = f32_node(&mut g, Op::Const, vec![]);
1767 let vc = f32_node(&mut g, Op::Const, vec![]);
1768
1769 // CUDA chain.
1770 let mut cuda_nodes = Vec::new();
1771 let mut cprev = cc;
1772 for _ in 0..cuda_len {
1773 let n = f32_node(&mut g, Op::Relu, vec![cprev]);
1774 g.set_target_backend(n, BackendId::Cuda);
1775 cuda_nodes.push(n);
1776 cprev = n;
1777 }
1778 // Vulkan chain.
1779 let mut vk_nodes = Vec::new();
1780 let mut vprev = vc;
1781 for _ in 0..vk_len {
1782 let n = f32_node(&mut g, Op::Silu, vec![vprev]);
1783 g.set_target_backend(n, BackendId::Vulkan);
1784 vk_nodes.push(n);
1785 vprev = n;
1786 }
1787 // Cross-device copy: Vulkan root -> CUDA (a residency seam = its own
1788 // run). Reconverge on CUDA reads [cuda_root, copy].
1789 let copy = g.push(Node {
1790 op: Op::Copy {
1791 target: fuel_ir::DeviceLocation::Cuda { gpu_id: 0 },
1792 },
1793 inputs: vec![vprev],
1794 shape: Shape::from_dims(&[2]),
1795 dtype: DType::F32,
1796 });
1797 g.set_target_backend(copy, BackendId::Cuda);
1798 // Reconverge inputs in the "wrong" (cuda-first) order, so the DFS
1799 // pops the LAST input (the Vulkan-fed copy) first.
1800 let out = g.push(Node {
1801 op: Op::Add,
1802 inputs: vec![cprev, copy],
1803 shape: Shape::from_dims(&[2]),
1804 dtype: DType::F32,
1805 });
1806 g.set_target_backend(out, BackendId::Cuda);
1807 (g, out, cuda_nodes, vk_nodes, copy)
1808 }
1809
1810 /// Assert `order` is a valid topological reordering of `runs`: every run
1811 /// appears after all the runs it depends on (a member reads a member of
1812 /// the producer run).
1813 fn assert_valid_topo_run_order(graph: &Graph, runs: &[Run], order: &[usize]) {
1814 let mut run_of: HashMap<NodeId, usize> = HashMap::new();
1815 for (ri, r) in runs.iter().enumerate() {
1816 for &m in &r.members {
1817 run_of.insert(m, ri);
1818 }
1819 }
1820 let mut emitted: HashSet<usize> = HashSet::new();
1821 for &ri in order {
1822 for &m in &runs[ri].members {
1823 for &inp in &graph.node(m).inputs {
1824 if let Some(&pi) = run_of.get(&inp)
1825 && pi != ri
1826 {
1827 assert!(
1828 emitted.contains(&pi),
1829 "run {ri} emitted before its producer run {pi}",
1830 );
1831 }
1832 }
1833 }
1834 emitted.insert(ri);
1835 }
1836 assert_eq!(order.len(), runs.len(), "every run emitted exactly once");
1837 let distinct: HashSet<usize> = order.iter().copied().collect();
1838 assert_eq!(distinct.len(), runs.len(), "the order is a permutation");
1839 }
1840
1841 /// C3 core: a two-device run list is reordered into a valid topological
1842 /// order that INTERLEAVES the devices — the independent CUDA and Vulkan
1843 /// producer chunks are both emitted BEFORE the cross-device copy that
1844 /// feeds the reconverge (the A4b overlap topology), regardless of the
1845 /// reconverge's input order.
1846 #[test]
1847 fn device_alternating_reorder_interleaves_two_devices() {
1848 let (g, out, cuda_nodes, vk_nodes, copy) = two_device_reconverge(4, 4);
1849 let runs = extract_runs(&g, out);
1850 let perm = device_alternating_order(&g, &runs);
1851
1852 // (1) A valid topological reordering.
1853 assert_valid_topo_run_order(&g, &runs, &perm);
1854
1855 // Map each landmark node to its position in the FLATTENED reordered
1856 // order, so we can assert the overlap-relevant ordering.
1857 let flat: Vec<NodeId> = perm
1858 .iter()
1859 .flat_map(|&ri| runs[ri].members.clone())
1860 .collect();
1861 let pos = |n: NodeId| flat.iter().position(|&x| x == n).expect("node present");
1862
1863 let cuda_root = *cuda_nodes.last().unwrap();
1864 let vk_root = *vk_nodes.last().unwrap();
1865
1866 // (2) BOTH device producer chunks are emitted before the
1867 // cross-device copy (the host-blocking D2H). This is the
1868 // property the un-reordered cuda-last DFS violates and that the
1869 // A4b eager-submit mechanism turns into overlap.
1870 assert!(
1871 pos(cuda_root) < pos(copy),
1872 "the CUDA chunk must be enqueued before the cross-device copy; \
1873 flat={flat:?}",
1874 );
1875 assert!(
1876 pos(vk_root) < pos(copy),
1877 "the Vulkan chunk must be recorded before the cross-device copy; \
1878 flat={flat:?}",
1879 );
1880
1881 // (3) The devices INTERLEAVE rather than one draining fully first:
1882 // the run-device sequence has at least one CUDA<->Vulkan
1883 // transition before the copy. (With one chunk per device this is
1884 // just "both chunks precede the copy", already asserted; assert
1885 // the device sequence explicitly too.)
1886 let dev_seq: Vec<Option<BackendId>> = perm.iter().map(|&ri| runs[ri].device).collect();
1887 let switches = dev_seq.windows(2).filter(|w| w[0] != w[1]).count();
1888 assert!(
1889 switches >= 1,
1890 "a two-device run list must contain at least one device switch; \
1891 dev_seq={dev_seq:?}",
1892 );
1893 }
1894
1895 /// C3 gate: a SINGLE-device run list is the IDENTITY permutation — the
1896 /// reorder never diverges from the input order, so the lowering is
1897 /// byte-identical to today's (the primary single-device regression
1898 /// gate).
1899 #[test]
1900 fn device_alternating_reorder_single_device_is_identity() {
1901 // All-CUDA chain (one distinct device) → identity.
1902 let mut g = Graph::new();
1903 let mut prev = f32_node(&mut g, Op::Const, vec![]);
1904 for _ in 0..6 {
1905 prev = f32_node(&mut g, Op::Relu, vec![prev]);
1906 g.set_target_backend(prev, BackendId::Cuda);
1907 }
1908 let runs = extract_runs(&g, prev);
1909 let perm = device_alternating_order(&g, &runs);
1910 assert_eq!(
1911 perm,
1912 (0..runs.len()).collect::<Vec<_>>(),
1913 "a single-device run list reorders to the identity permutation",
1914 );
1915
1916 // A graph with NO explicit backend anywhere (all device == None) is
1917 // also a single bucket → identity (the branchless single-route CPU
1918 // graph — must stay byte-identical).
1919 let mut g2 = Graph::new();
1920 let a = f32_node(&mut g2, Op::Const, vec![]);
1921 let b = f32_node(&mut g2, Op::Relu, vec![a]);
1922 let c = f32_node(&mut g2, Op::Silu, vec![b]);
1923 let runs2 = extract_runs(&g2, c);
1924 assert_eq!(
1925 device_alternating_order(&g2, &runs2),
1926 (0..runs2.len()).collect::<Vec<_>>(),
1927 "an all-default (device=None) run list is identity",
1928 );
1929 }
1930
1931 /// C3 correctness: the reorder NEVER violates a data dependency, even
1932 /// when alternation "wants" to move a run earlier. A linear cross-device
1933 /// chain CPU→CUDA→Vulkan→CUDA (each a residency seam, so 4 runs, each
1934 /// depending strictly on the prior) must come out in dependency order —
1935 /// the device preference can't reorder a strict chain.
1936 #[test]
1937 fn device_alternating_reorder_respects_dependencies() {
1938 let mut g = Graph::new();
1939 let a = f32_node(&mut g, Op::Const, vec![]);
1940 g.set_target_backend(a, BackendId::Cpu);
1941 let b = f32_node(&mut g, Op::Relu, vec![a]);
1942 g.set_target_backend(b, BackendId::Cuda);
1943 let c = f32_node(&mut g, Op::Silu, vec![b]);
1944 g.set_target_backend(c, BackendId::Vulkan);
1945 let d = f32_node(&mut g, Op::Tanh, vec![c]);
1946 g.set_target_backend(d, BackendId::Cuda);
1947
1948 let runs = extract_runs(&g, d);
1949 let perm = device_alternating_order(&g, &runs);
1950 assert_valid_topo_run_order(&g, &runs, &perm);
1951 // A strict chain has exactly one valid topological order; the
1952 // alternation cannot change it.
1953 let flat: Vec<NodeId> = perm
1954 .iter()
1955 .flat_map(|&ri| runs[ri].members.clone())
1956 .collect();
1957 assert_eq!(
1958 flat,
1959 vec![a, b, c, d],
1960 "a strict cross-device chain keeps dependency order despite \
1961 device alternation",
1962 );
1963 }
1964
1965 /// C3 invariance (fuel-graph layer): the device-alternating lowering of
1966 /// a multi-device graph emits the SAME multiset of NodeIds as the
1967 /// un-reordered concatenation, in a VALID topological order — only the
1968 /// order across independent runs changes. (The byte-identical-OUTPUT
1969 /// proof is the live reorder-invariance test in `fuel-dispatch`; this is
1970 /// the structural guard that the reorder is a permutation, not a
1971 /// rewrite.)
1972 #[test]
1973 fn lower_picked_route_multidevice_is_a_valid_reordering() {
1974 let (g, out, _cuda, _vk, _copy) = two_device_reconverge(4, 4);
1975 let runs = extract_runs(&g, out);
1976
1977 // Un-reordered reference: concatenate runs in topo order.
1978 let reference: Vec<NodeId> = runs.iter().flat_map(|r| lower_run(r).to_vec()).collect();
1979 // The production lowering (now reorders multi-device).
1980 let lowered = lower_picked_route(&g, &[out], &PickedRoute::new());
1981
1982 // Same multiset of nodes (a permutation, no add/drop).
1983 let mut a = reference.clone();
1984 let mut b = lowered.clone();
1985 a.sort();
1986 b.sort();
1987 assert_eq!(a, b, "the reorder is a permutation of the same node set");
1988
1989 // The lowered order is a valid topological order of the graph: every
1990 // node appears after all of its (reachable, lowered) inputs.
1991 let lowered_pos: HashMap<NodeId, usize> =
1992 lowered.iter().enumerate().map(|(i, &n)| (n, i)).collect();
1993 for (i, &n) in lowered.iter().enumerate() {
1994 for &inp in &g.node(n).inputs {
1995 if let Some(&j) = lowered_pos.get(&inp) {
1996 assert!(j < i, "input {inp:?} of {n:?} must precede it");
1997 }
1998 }
1999 }
2000
2001 // And it genuinely diverged from the reference (the reorder fired) —
2002 // the cuda-last DFS reference puts the Vulkan-fed copy's chain before
2003 // the CUDA chain; the reorder interleaves them.
2004 assert_ne!(
2005 lowered, reference,
2006 "on this two-device graph the reorder must change the order \
2007 (else auto-overlap did nothing)",
2008 );
2009 }
2010
2011 /// C3 + C1 composition: the STREAMING lowering of a multi-device graph
2012 /// equals the one-shot `lower_picked_route` (both now reorder), and the
2013 /// streaming reorder is confined to branch-free segments. On a
2014 /// branchless multi-device graph there is exactly one segment, so the
2015 /// streamed order equals the one-shot reordered order byte-for-byte.
2016 #[test]
2017 fn streaming_multidevice_equals_one_shot_reordered() {
2018 let (g, out, _cuda, _vk, _copy) = two_device_reconverge(4, 4);
2019 let one_shot = lower_picked_route(&g, &[out], &PickedRoute::new());
2020 let streamed = lower_picked_route_streaming(&g, &[out], |_b| 0);
2021 assert_eq!(
2022 streamed, one_shot,
2023 "streamed multi-device order equals the one-shot reordered order",
2024 );
2025 }
2026
2027 /// C3 critical-path property (the live-overlap regression guard): when
2028 /// the two device chunks differ in size, the reorder emits the HEAVIER
2029 /// chunk's whole path FIRST — so the auto-submitting device (the one with
2030 /// the long chain) is enqueued and running before the lighter device's
2031 /// host-blocking drain. This mirrors the live benchmark (CUDA-768 vs
2032 /// Vulkan-120): the proven-overlap order is CUDA-chunk-first; the inverse
2033 /// (Vulkan-first) serialized at 0.0 efficiency. This test locks the
2034 /// heavy-first ordering that makes the arbitrary-graph benchmark
2035 /// auto-overlap.
2036 #[test]
2037 fn device_alternating_reorder_emits_heavier_chunk_first() {
2038 // CUDA chain HEAVY (8), Vulkan chain LIGHT (2). Reconverge inputs are
2039 // cuda-first (the "wrong" DFS order). The reorder must still emit the
2040 // heavy CUDA chunk's path before the light Vulkan chunk.
2041 let (g, out, cuda_nodes, vk_nodes, copy) = two_device_reconverge(8, 2);
2042 let runs = extract_runs(&g, out);
2043 let perm = device_alternating_order(&g, &runs);
2044 assert_valid_topo_run_order(&g, &runs, &perm);
2045
2046 let flat: Vec<NodeId> = perm
2047 .iter()
2048 .flat_map(|&ri| runs[ri].members.clone())
2049 .collect();
2050 let pos = |n: NodeId| flat.iter().position(|&x| x == n).expect("present");
2051 let cuda_root = *cuda_nodes.last().unwrap();
2052 let vk_root = *vk_nodes.last().unwrap();
2053
2054 // The HEAVY (CUDA) chunk's root is emitted BEFORE the LIGHT (Vulkan)
2055 // chunk's root — the heavy device is enqueued first.
2056 assert!(
2057 pos(cuda_root) < pos(vk_root),
2058 "the heavier CUDA chunk must be emitted before the lighter Vulkan \
2059 chunk (the auto-submit device runs first); flat={flat:?}",
2060 );
2061 // And BOTH chunks precede the host-blocking cross-device copy.
2062 assert!(pos(cuda_root) < pos(copy), "heavy chunk before the drain");
2063 assert!(pos(vk_root) < pos(copy), "light chunk before the drain");
2064
2065 // Symmetric check: make VULKAN the heavy chunk; now Vulkan's path
2066 // must come first. (Proves it's size-driven, not a CUDA hard-code.)
2067 let (g2, out2, cuda2, vk2, copy2) = two_device_reconverge(2, 8);
2068 let runs2 = extract_runs(&g2, out2);
2069 let perm2 = device_alternating_order(&g2, &runs2);
2070 assert_valid_topo_run_order(&g2, &runs2, &perm2);
2071 let flat2: Vec<NodeId> = perm2
2072 .iter()
2073 .flat_map(|&ri| runs2[ri].members.clone())
2074 .collect();
2075 let pos2 = |n: NodeId| flat2.iter().position(|&x| x == n).expect("present");
2076 assert!(
2077 pos2(*vk2.last().unwrap()) < pos2(*cuda2.last().unwrap()),
2078 "when Vulkan is the heavier chunk it is emitted first; flat2={flat2:?}",
2079 );
2080 assert!(pos2(*vk2.last().unwrap()) < pos2(copy2));
2081 assert!(pos2(*cuda2.last().unwrap()) < pos2(copy2));
2082 }
2083}