fuel_graph/opt.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Graph-level, backend-agnostic optimization passes.
3//!
4//! Transforms a `fuel-graph` computation graph before execution. Every
5//! backend benefits from these passes because they operate purely on
6//! the abstract op graph — no backend-specific knowledge required.
7//!
8//! **Passes today:**
9//!
10//! - **CSE** (common subexpression elimination): if the graph contains
11//! two structurally-identical nodes — same op, same inputs (after
12//! prior simplification), same shape/dtype — consumers of the
13//! duplicate are redirected to the canonical node. The duplicate
14//! becomes unreferenced and is silently dropped by the executor's
15//! topo-walk. Commutative ops (`Add`, `Mul`) are keyed on sorted input
16//! IDs so `a + b` and `b + a` fold to the same canonical node.
17//! `Maximum`/`Minimum` are NOT in that set: commutative in value, not in
18//! bits, because the NaN tie-break returns the FIRST operand. See GAP-271.
19//!
20//! - **Algebraic simplification**: a handful of identity/zero rules
21//! that eliminate no-op ops:
22//! - `AddScalar(0.0)(x)` → `x`
23//! - `MulScalar(1.0)(x)` → `x`
24//! - `Neg(Neg(x))` → `x`
25//! - `Reshape(Reshape(x, _), s)` → `Reshape(x, s)`
26//!
27//! These rarely appear in hand-written user code but show up
28//! routinely in autograd-generated backward graphs and in
29//! generic transformer building blocks that sometimes collapse.
30//!
31//! **Design:** graphs are append-only, so rewrites don't mutate
32//! existing nodes. Instead, the pass walks topologically, builds a
33//! remap `HashMap<NodeId, NodeId>` of old → canonical, and appends
34//! newly-canonicalized nodes to the same graph. Unreferenced originals
35//! remain in the arena but are never visited during realize. This is
36//! effectively a combined CSE + simplification + free DCE pass.
37//!
38//! **Return value:** the function takes the roots the caller cares
39//! about and returns the rewritten roots. Callers use these to update
40//! their `NodeHandle` handles.
41
42use crate::registry::{FusedOpEntry, FusedOpId, FusedOpParams, SubgraphPattern, default_registry};
43use crate::{Graph, Node, NodeId, Op, ScanEmit, ScanRole, SharedGraph, topo_order_multi};
44use fuel_ir::{DType, DeviceLocation};
45use std::collections::HashMap;
46
47// ---- Rule registry framework ----------------------------------------------
48//
49// Optimization is a pipeline of rule-driven graph rewrites. Two rule
50// families:
51//
52// - `RuleFamily::Lowering` — high-level op → primitive subgraph. Exposes
53// fusion opportunities and lets backends without a fused kernel run
54// the composition through whichever primitives they DO have.
55// - `RuleFamily::Fusion` — recognized primitive subgraph → fused op.
56// Recovers (or improves on) the original-flavour kernel where one
57// exists.
58//
59// A `Rule` is `(matcher, rewriter)`. The driver in
60// [`RuleRegistry::optimize_to_fixpoint`] runs lowering rules to fixpoint
61// first, then fusion rules to fixpoint. End state is post-fusion: for
62// SoftmaxLastDim (whose lower and fuse rules are inverses of each
63// other) the round-trip is identity. For lowering rules that ship
64// without a fusion partner — RmsNorm, LayerNorm, Affine, Clamp — the
65// post-pipeline graph is the lowered form.
66//
67// PR 3 ships the framework + a single (lower, fuse) rule pair for
68// `Op::SoftmaxLastDim`. The locked design (see ROADMAP.md → Phase 7.5)
69// also covers transactional snapshots, in-flight switching, and budget
70// modes; those are subsequent PRs that wrap this synchronous loop
71// without rewriting it.
72
73/// Which family a [`Rule`] belongs to. Drives the phase ordering in
74/// [`RuleRegistry::optimize_to_fixpoint`]: lowering runs to fixpoint
75/// first, then fusion. This ordering ensures inverse rule pairs
76/// converge cleanly — fusion has the last word, and its output is
77/// what the executor runs.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
79pub enum RuleFamily {
80 /// High-level op → primitive subgraph. Always grows the graph.
81 Lowering,
82 /// Recognized primitive subgraph → fused op. Always shrinks the
83 /// graph (the fused op replaces the canonical subgraph's output;
84 /// the orphaned subgraph nodes remain in the arena but are
85 /// unreachable from the user's roots after consumer rewiring).
86 Fusion,
87 /// Algebraic identity rewrites that don't fit the lowering or
88 /// fusion shapes: cast elimination (`Cast(src→dst) → Op(dst)`
89 /// becomes `Op(src)` when the consumer supports the source
90 /// dtype), constant folding, identity elimination, common-
91 /// subexpression hoisting. Runs after fusion so cast-elimination
92 /// can't break fusion-pattern dtype expectations.
93 Algebraic,
94}
95
96/// One graph-rewrite rule. A rule pairs a structural matcher with a
97/// rewriter that emits replacement nodes and records the
98/// `(old_id → new_id)` remapping so the driver can rewrite consumer
99/// input edges to point at the replacement.
100///
101/// Rules don't need to update the layout side-table for view nodes
102/// they insert: [`Graph::push`] auto-populates layout for view ops
103/// from the input's layout.
104///
105/// Rules don't express ordering edges for destructive ops they emit
106/// (e.g. `Op::Release`); [`derive_ordering`] does that automatically
107/// at execution-plan time.
108pub trait Rule: Send + Sync {
109 /// Stable, human-readable name. Shows up in panic messages and
110 /// debug traces.
111 fn name(&self) -> &'static str;
112
113 /// Which family this rule belongs to. Determines pass ordering.
114 fn family(&self) -> RuleFamily;
115
116 /// Whether this rule can rewrite the node at `id`. Should be
117 /// pure — same inputs, same answer. Called once per node per
118 /// pass; the first matching rule wins.
119 fn matches(&self, graph: &Graph, id: NodeId) -> bool;
120
121 /// Apply the rewrite: append fresh nodes to the graph, declare
122 /// any side-effect roots if the rewrite emits side-effecting
123 /// ops, and write `remap.insert(id, replacement_id)` so the
124 /// driver can redirect consumer edges. Calling this method
125 /// implies [`matches`](Self::matches) returned `true` for the
126 /// same `(graph, id)` — rewriters can rely on the structure
127 /// the matcher checked for.
128 fn rewrite(&self, graph: &mut Graph, id: NodeId, remap: &mut HashMap<NodeId, NodeId>);
129}
130
131/// A registry of [`Rule`]s. Drives optimize-to-fixpoint via
132/// [`Self::optimize_to_fixpoint`]: lowering rules run to fixpoint,
133/// then fusion rules run to fixpoint. The locked design (ROADMAP.md
134/// Phase 7.5) intends this entry point to be wrapped in transactions
135/// in subsequent PRs without rewriting the loop body — keep this API
136/// stable for that future evolution.
137#[derive(Default)]
138pub struct RuleRegistry {
139 rules: Vec<Box<dyn Rule>>,
140}
141
142impl RuleRegistry {
143 /// Empty registry. Use [`Self::with_rule`] to add rules, or
144 /// [`Self::default_rules`] / [`Self::lowering_only`] for the
145 /// shipped configurations.
146 pub fn new() -> Self {
147 Self { rules: Vec::new() }
148 }
149
150 /// Append a rule. Returns self for builder-style chaining.
151 pub fn with_rule(mut self, rule: Box<dyn Rule>) -> Self {
152 self.rules.push(rule);
153 self
154 }
155
156 /// Lower + fuse rules for every fused op registered in the
157 /// process-wide [`default_registry`]. Round-trip is identity for
158 /// canonical SoftmaxLastDim graphs (the lowered subgraph is
159 /// structurally re-fused). Use this in production realize paths.
160 ///
161 /// Phase 7.6 step 3: PR 3's hand-written
162 /// `SoftmaxLastDimLowerRule`/`SoftmaxLastDimFuseRule` are deleted;
163 /// equivalent behavior is auto-generated from the SoftmaxLastDim
164 /// registry entry. Subsequent fused-op migrations in step 4 add
165 /// their entries to the same registry; `default_rules` picks them
166 /// up automatically.
167 pub fn default_rules() -> Self {
168 Self::capability_gated_rules(|_| true).0
169 }
170
171 /// Build lower + fuse rules, but **fuse** a fused op only when
172 /// `has_kernel(id)` holds — the capability gate
173 /// (`runtime-fused-op-registration.md` §6). Every fused op (static +
174 /// runtime) still gets a *lowering* rule (so any already-fused node
175 /// decomposes); an op WITHOUT a kernel gets **no fusion rule**, so a
176 /// kernel-absent fused node never forms in the first place — the miss is
177 /// caught at the pattern-match step, not repaired afterward.
178 ///
179 /// Returns the rule set plus the ids that were **gated out of fusion** — the
180 /// miss candidates feeding the JIT work-order signal. The dispatch layer
181 /// supplies `has_kernel` from its `FusedKernelRegistry` + the target
182 /// backend; [`Self::default_rules`] is the all-available case.
183 pub fn capability_gated_rules(
184 has_kernel: impl Fn(FusedOpId) -> bool,
185 ) -> (Self, Vec<FusedOpId>) {
186 let registry = default_registry();
187 let mut r = Self::new();
188 let mut gated_out = Vec::new();
189 for entry in registry.entries_iter() {
190 r = r.with_rule(Box::new(LoweringRule::from_entry(entry)));
191 if has_kernel(entry.id) {
192 r = r.with_rule(Box::new(FusionRule::from_entry(entry)));
193 } else {
194 gated_out.push(entry.id);
195 }
196 }
197 // Runtime-registered fused ops (Tier-2), same gate. A runtime op with no
198 // kernel yet (JIT cold start) is gated out + reported as a miss — the
199 // synthesize work-order — and its region stays primitive this pass.
200 for e in crate::runtime_fused::runtime_entries() {
201 r = r.with_rule(Box::new(LoweringRule::runtime(e.id)));
202 if has_kernel(e.id) {
203 r = r.with_rule(Box::new(FusionRule::declarative(
204 e.id,
205 crate::registry::PatternTree {
206 root: e.region,
207 params: FusedOpParams::Runtime {
208 scalars: Vec::new(),
209 },
210 },
211 )));
212 } else {
213 gated_out.push(e.id);
214 }
215 }
216 (r, gated_out)
217 }
218
219 /// Lowering rules only — no fusion. Use this when the test or
220 /// caller wants the lowered form to be the post-pipeline state
221 /// (e.g. equivalence-testing the composed-math path on a backend
222 /// that has the primitives but not the fused kernel).
223 pub fn lowering_only() -> Self {
224 let registry = default_registry();
225 let mut r = Self::new();
226 for entry in registry.entries_iter() {
227 r = r.with_rule(Box::new(LoweringRule::from_entry(entry)));
228 }
229 // Runtime ops decompose to their region here too — this is the
230 // kernel-absent path (a backend without the synthesized kernel runs the
231 // primitive recipe).
232 for e in crate::runtime_fused::runtime_entries() {
233 r = r.with_rule(Box::new(LoweringRule::runtime(e.id)));
234 }
235 r
236 }
237
238 /// Number of registered rules.
239 pub fn len(&self) -> usize {
240 self.rules.len()
241 }
242
243 /// Whether the registry has any rules.
244 pub fn is_empty(&self) -> bool {
245 self.rules.is_empty()
246 }
247
248 /// Run lowering rules to fixpoint, then fusion rules to fixpoint.
249 /// Returns the (possibly-rewritten) roots — callers use these to
250 /// replace their `NodeHandle` handles.
251 ///
252 /// The two-phase ordering is important: rules that are inverses
253 /// of each other (e.g. SoftmaxLastDim's lower + fuse pair)
254 /// would oscillate in a single mixed-family fixpoint loop.
255 /// Phase ordering breaks the oscillation and gives fusion the
256 /// last word.
257 pub fn optimize_to_fixpoint(&self, graph: &SharedGraph, roots: &[NodeId]) -> Vec<NodeId> {
258 let mut roots = roots.to_vec();
259 if self.rules.is_empty() {
260 return roots;
261 }
262 // Phase 1: lowering to fixpoint.
263 loop {
264 let any = self.run_pass(RuleFamily::Lowering, graph, &mut roots);
265 if !any {
266 break;
267 }
268 }
269 // Phase 2: fusion to fixpoint.
270 loop {
271 let any = self.run_pass(RuleFamily::Fusion, graph, &mut roots);
272 if !any {
273 break;
274 }
275 }
276 // Phase 3: algebraic identities to fixpoint. Runs last so it
277 // can't disturb fusion patterns by eliminating casts that
278 // fusion was about to match on.
279 loop {
280 let any = self.run_pass(RuleFamily::Algebraic, graph, &mut roots);
281 if !any {
282 break;
283 }
284 }
285 roots
286 }
287
288 /// One pass over the graph for a single rule family. Returns
289 /// `true` if any rule fired during the pass — caller loops until
290 /// `false` for fixpoint.
291 fn run_pass(&self, family: RuleFamily, graph: &SharedGraph, roots: &mut [NodeId]) -> bool {
292 let order = {
293 let g = graph.read().unwrap();
294 topo_order_multi(&g, roots)
295 };
296
297 // Iterate this pass's family-rules in the order they were
298 // registered. First match wins per node.
299 let family_rules: Vec<&Box<dyn Rule>> =
300 self.rules.iter().filter(|r| r.family() == family).collect();
301 if family_rules.is_empty() {
302 return false;
303 }
304
305 let mut remap: HashMap<NodeId, NodeId> = HashMap::new();
306 let mut any_fired = false;
307
308 for id in order {
309 // Skip nodes that an earlier rule in this pass already
310 // rewrote — the consumer-edge rewrite happens after the
311 // pass, so the original node's structure still looks
312 // matchable mid-pass; we use `remap` as a "this pass
313 // already handled it" marker.
314 if remap.contains_key(&id) {
315 continue;
316 }
317
318 let firing_rule_idx = {
319 let g = graph.read().unwrap();
320 family_rules.iter().position(|r| r.matches(&g, id))
321 };
322 if let Some(idx) = firing_rule_idx {
323 let mut g = graph.write().unwrap();
324 let before = remap.len();
325 family_rules[idx].rewrite(&mut g, id, &mut remap);
326 // A rule that matched but recorded no remap entry made no
327 // progress — e.g. a `decompose` that returned self (G2's
328 // fixpoint signal: this op can't decompose further). Only
329 // count real rewrites, so the fixpoint loop terminates
330 // instead of spinning on a no-op match.
331 if remap.len() != before {
332 any_fired = true;
333 }
334 }
335 }
336
337 if !any_fired {
338 return false;
339 }
340
341 // Apply remap to every consumer's input list, in place. This
342 // is the moment the rewritten nodes become the live ones —
343 // any node whose inputs referenced a remapped id now reads
344 // from its replacement.
345 {
346 let mut g = graph.write().unwrap();
347 let n_nodes = g.len();
348 for nid in 0..n_nodes {
349 let inputs_len = g.node(NodeId(nid)).inputs.len();
350 for i in 0..inputs_len {
351 let cur = g.node(NodeId(nid)).inputs[i];
352 if let Some(&new) = remap.get(&cur) {
353 g.rewrite_input(NodeId(nid), cur, new);
354 }
355 }
356 }
357 }
358
359 // And update the user's roots so the next phase / the caller
360 // sees the canonical post-rewrite ids.
361 for r in roots.iter_mut() {
362 if let Some(&new) = remap.get(r) {
363 *r = new;
364 }
365 }
366
367 true
368 }
369}
370
371/// Lower every reachable fused op in `graph` (rooted at `roots`) to its
372/// primitive base map — the fixpoint of `decompose` over every node. A thin
373/// named wrapper over [`RuleRegistry::lowering_only`] + `optimize_to_fixpoint`
374/// (the machinery every fused op — static-registry AND runtime — already flows
375/// through). Never panics: a self-returning `decompose` is a clean fixpoint
376/// (the never-panic total-decompose contract), not a loop.
377pub fn lower_to_base_map(graph: &SharedGraph, roots: &[NodeId]) -> Vec<NodeId> {
378 RuleRegistry::lowering_only().optimize_to_fixpoint(graph, roots)
379}
380
381/// `NodeId`-independent content hash of the subgraph rooted at `root`.
382///
383/// Recursively hashes each node as `(op identity, child hashes)`, folding in
384/// each child's *hash* rather than its `NodeId` — so two independently-built
385/// graphs (different arenas, different `NodeId` numbering) that are
386/// structurally identical hash equal. Reuses this module's existing
387/// canonicalization primitives rather than duplicating them:
388///
389/// - `op_key` for op identity when available (covers every primitive +
390/// `Op::Fused` variant CSE already relies on).
391/// - `is_commutative` to sort child hashes for `Add`/`Mul`, so `a + b` and
392/// `b + a` hash equal (mirrors CSE's own commutative-operand
393/// canonicalization). `Maximum`/`Minimum` are excluded -- see GAP-271.
394///
395/// `op_key` deliberately excludes `Op::Const` (its payload lives in the
396/// graph's `storage_map` slot, not the `Op` enum) and returns `None`
397/// for a handful of other ops (in-place,
398/// indexing, and anything else not explicitly listed). For those, this
399/// function falls back to `(discriminant, shape, dtype)` — and, for
400/// `Op::Const` specifically, additionally folds the constant's real bytes
401/// when they're readable (see `fold_const_bytes` below) so two
402/// independently-built recipes with equal constants hash equal, not just
403/// equal-shaped placeholders.
404///
405/// This is a cheap structural *pre-filter* for cross-graph recipe identity:
406/// structurally-equal-up-to-commutative-reordering-and-fusion-depth base
407/// maps hash equal. It does NOT canonicalize associativity or
408/// distributivity (`(a + b) + c` vs `a + (b + c)` hash differently) — a
409/// numeric verify pass covers that residual. Hashes are only stable within
410/// one process / `DefaultHasher` instance; never persist or compare them
411/// across processes.
412pub fn base_map_hash(graph: &Graph, root: NodeId) -> u64 {
413 use std::collections::hash_map::DefaultHasher;
414 use std::hash::{Hash, Hasher};
415
416 // Fold a `Const` node's real bytes into `hasher`, when they're
417 // readable without blocking. Const bytes live in the graph's
418 // `storage_map` slot (`lib.rs:218-223`), populated via
419 // `Graph::set_storage`/`storage_for` — NOT in the `Op` enum, so
420 // `op_key` can't see them (by design; see `OpKey`'s doc comment).
421 //
422 // Falls back to a silent no-op (the caller has already folded this
423 // node's shape/dtype via the `op_key -> None` branch) when:
424 // - the slot is unpopulated (e.g. a bare `Node { op: Op::Const, .. }`
425 // pushed without ever calling `set_storage` — as the unit tests
426 // below do for their placeholder consts), or
427 // - the slot's `RwLock` is held by a writer (`try_read` avoids
428 // blocking a hash — a structural pre-filter — on live graph
429 // mutation), or
430 // - the backend can't produce a host buffer right now (e.g.
431 // device-only storage mid-capture).
432 //
433 // Documented limitation: in the fallback case, two *different*
434 // device-only (or unpopulated) consts of the same shape/dtype hash
435 // equal. `base_map_hash` is a pre-filter, not a full identity
436 // decision — a numeric verify pass is the source of truth when bytes
437 // aren't available at hash time.
438 fn fold_const_bytes(graph: &Graph, id: NodeId, hasher: &mut DefaultHasher) {
439 let Some(slot) = graph.storage_for(id) else {
440 return;
441 };
442 let Ok(guard) = slot.try_read() else { return };
443 let Ok(host) = guard.to_cpu_storage() else {
444 return;
445 };
446 fold_host_buffer(&host, hasher);
447 }
448
449 // Bridge every `HostBuffer` element dtype to something `Hash`. Integer
450 // variants (including the raw-byte-backed sub-byte dummy dtypes)
451 // already implement `Hash` directly; float variants don't (NaN
452 // equality is ambiguous under `Eq`, so std withholds `Hash`) — for
453 // those we fold each element's bit pattern via `to_bits()`, which is
454 // exact (including NaN payload bits) and matches the bit-pattern
455 // encoding `op_key` already uses for scalar payloads (e.g.
456 // `Op::AddScalar`'s `f64::to_bits()`).
457 fn fold_host_buffer(buf: &fuel_ir::HostBuffer, hasher: &mut DefaultHasher) {
458 use fuel_ir::HostBuffer as H;
459 match buf {
460 H::U8(v) | H::F6E2M3(v) | H::F6E3M2(v) | H::F4(v) | H::F8E8M0(v) | H::Bool(v) => {
461 v.hash(hasher)
462 }
463 H::I8(v) => v.hash(hasher),
464 H::U32(v) => v.hash(hasher),
465 H::I16(v) => v.hash(hasher),
466 H::I32(v) => v.hash(hasher),
467 H::I64(v) => v.hash(hasher),
468 H::BF16(v) => {
469 for x in v {
470 x.to_bits().hash(hasher);
471 }
472 }
473 H::F16(v) => {
474 for x in v {
475 x.to_bits().hash(hasher);
476 }
477 }
478 H::F32(v) => {
479 for x in v {
480 x.to_bits().hash(hasher);
481 }
482 }
483 H::F64(v) => {
484 for x in v {
485 x.to_bits().hash(hasher);
486 }
487 }
488 H::F8E4M3(v) => {
489 for x in v {
490 x.to_bits().hash(hasher);
491 }
492 }
493 }
494 }
495
496 fn go(graph: &Graph, id: NodeId, memo: &mut HashMap<NodeId, u64>) -> u64 {
497 if let Some(&h) = memo.get(&id) {
498 return h;
499 }
500 let n = graph.node(id);
501 let mut hasher = DefaultHasher::new();
502 match op_key(&n.op) {
503 Some(k) => k.hash(&mut hasher),
504 None => {
505 std::mem::discriminant(&n.op).hash(&mut hasher);
506 n.shape.dims().hash(&mut hasher);
507 n.dtype.hash(&mut hasher);
508 if matches!(n.op, Op::Const) {
509 fold_const_bytes(graph, id, &mut hasher);
510 }
511 }
512 }
513 let mut child_hashes: Vec<u64> = n.inputs.iter().map(|&c| go(graph, c, memo)).collect();
514 if is_commutative(&n.op) {
515 child_hashes.sort_unstable();
516 }
517 child_hashes.hash(&mut hasher);
518 let h = hasher.finish();
519 memo.insert(id, h);
520 h
521 }
522
523 go(graph, root, &mut HashMap::new())
524}
525
526// ---- Auto-generated lowering + fusion rules from FusedOpRegistry ----------
527//
528// Phase 7.6 step 3: PR 3's hand-written `SoftmaxLastDimLowerRule` and
529// `SoftmaxLastDimFuseRule` are replaced by [`LoweringRule`] +
530// [`FusionRule`] generic abstractions that read the per-fused-op
531// metadata (decompose function, pattern matcher) from a
532// [`FusedOpEntry`] in `crate::registry::default_registry`. Each rule
533// fires on `Op::Fused(id, _)` for lowering or on the pattern's
534// canonical primitive subgraph for fusion.
535//
536// Lowered form (7 nodes for SoftmaxLastDim, symmetric across max/sum):
537//
538// m = ReduceMaxTo([..., 1])(x) # max-keepdim in one node
539// mb = BroadcastTo([..., last])(m)
540// s = Sub(x, mb) # numerically-stable shift
541// e = Exp(s)
542// d = ReduceSumTo([..., 1])(e) # sum-keepdim in one node
543// db = BroadcastTo([..., last])(d)
544// out = Div(e, db)
545//
546// The compile_one auto-Contiguize at the executor catches any backend
547// that doesn't support the strided BroadcastTo output as a kernel
548// input. PR 2-wide lets CUDA binary F32 kernels consume the broadcast
549// strides directly without materialization.
550
551/// Auto-generated lowering rule from a [`FusedOpEntry`]. Matches
552/// `Op::Fused(id, _)` and decomposes via the entry's `decompose`
553/// function. Each rule corresponds to one fused-op id in the registry.
554///
555/// Step 3 also fires on the legacy per-fused-op `Op` variants (e.g.
556/// `Op::SoftmaxLastDim`) so emission sites that haven't yet migrated
557/// to `Op::Fused` continue to lower correctly. Step 5 deletes those
558/// variants and the legacy match arm with them.
559pub struct LoweringRule {
560 id: FusedOpId,
561 decompose: fn(&mut Graph, NodeId, &FusedOpParams) -> NodeId,
562}
563
564impl LoweringRule {
565 pub fn from_entry(entry: &FusedOpEntry) -> Self {
566 Self {
567 id: entry.id,
568 decompose: entry.decompose,
569 }
570 }
571
572 /// Lowering rule for a runtime-registered fused op: decompose by re-emitting
573 /// its `runtime_fused` sidecar region as primitives. One per runtime id.
574 pub fn runtime(id: FusedOpId) -> Self {
575 Self {
576 id,
577 decompose: crate::runtime_fused::runtime_lowering_decompose,
578 }
579 }
580}
581
582impl Rule for LoweringRule {
583 fn name(&self) -> &'static str {
584 // Step 3 ships only SoftmaxLastDim; step 4 generalizes per-id.
585 // Until then, all auto-generated lowering rules share one name —
586 // the registry id distinguishes them at the structural level.
587 "FusedOpLowering"
588 }
589
590 fn family(&self) -> RuleFamily {
591 RuleFamily::Lowering
592 }
593
594 fn matches(&self, graph: &Graph, id: NodeId) -> bool {
595 let node = graph.node(id);
596 // Arity is per-fused-op; the decompose function is the
597 // authority. We don't gate on `node.inputs.len()` here.
598 match &node.op {
599 Op::Fused(fid, _) if *fid == self.id => true,
600 // Phase 7.6 step 5 (2026-05-11): legacy-variant
601 // fallthroughs have been dropped — every migrated fused
602 // op now flows through `Op::Fused(id, _)`. Step 5 dropped
603 // the per-fused-op `Op` variants together with these
604 // matcher arms.
605 _ => false,
606 }
607 }
608
609 fn rewrite(&self, graph: &mut Graph, id: NodeId, remap: &mut HashMap<NodeId, NodeId>) {
610 // Read params from the matched `Op::Fused(_, p)` node; the
611 // legacy primitive-variant fallthroughs were dropped in
612 // step 5.
613 let params = match &graph.node(id).op {
614 Op::Fused(_, p) => p.clone(),
615 other => unreachable!(
616 "LoweringRule::rewrite reached with non-matching op {other:?} \
617 — matcher contract violated"
618 ),
619 };
620 let new_id = (self.decompose)(graph, id, ¶ms);
621 // G2 (2026-06-20): a `decompose` that returns the SAME node is at
622 // its fixpoint — the op can't decompose further (a primitive, or a
623 // coarse op whose recipe/primitives don't exist yet, which returns
624 // self). That is not a rewrite, so we record no remap entry; the
625 // driver (`run_pass`) then sees the unchanged remap and does not
626 // count it as progress, so the lowering fixpoint terminates instead
627 // of oscillating. The node is left as `Op::Fused` — a surfaced
628 // opaque-op gap that an inventory pass can find.
629 if new_id != id {
630 remap.insert(id, new_id);
631 }
632 }
633}
634
635/// Auto-generated fusion rule from a [`FusedOpEntry`]. Matches the
636/// canonical primitive-subgraph pattern carried by the entry's
637/// [`SubgraphPattern`] and emits a single `Op::Fused(id, params)`
638/// node. Round-trips with [`LoweringRule`] for the same id.
639///
640/// Currently params are reconstructed by-id: SoftmaxLastDim's variant
641/// is parameterless, so the fusion rule emits
642/// `FusedOpParams::SoftmaxLastDim`. Step 4 extends [`crate::registry::PatternMatch`]
643/// (or adds a sibling `extract_params` field on `FusedOpEntry`) so
644/// param-bearing fused ops can recover their parameters from the
645/// matched subgraph.
646pub struct FusionRule {
647 id: FusedOpId,
648 pattern: PatternKind,
649}
650
651/// Internal: the runtime-flavor of a registry entry's pattern. We
652/// keep a function-pointer copy here rather than holding a reference
653/// into the (process-wide) registry so the rule is `'static`.
654#[expect(
655 clippy::large_enum_variant,
656 reason = "matcher pattern enum; boxing the large variant is deferred to the same follow-up as PatternNode (docs/gaps.md GAP-215) -- a cross-cutting change to construction/match sites, not a lint-commit change"
657)]
658enum PatternKind {
659 Callable(fn(&Graph, NodeId) -> Option<crate::registry::PatternMatch>),
660 /// The declarative form (fkc-fusion-patterns §3): carries the owned
661 /// `PatternTree` (the §3 grammar root + the params to stamp) so the rule is
662 /// `'static`. `matches`/`rewrite` walk it via [`crate::jit::match_region`].
663 Declarative(crate::registry::PatternTree),
664}
665
666impl FusionRule {
667 pub fn from_entry(entry: &FusedOpEntry) -> Self {
668 let pattern = match &entry.pattern {
669 SubgraphPattern::Callable(f) => PatternKind::Callable(*f),
670 SubgraphPattern::Declarative(tree) => PatternKind::Declarative(tree.clone()),
671 };
672 Self {
673 id: entry.id,
674 pattern,
675 }
676 }
677
678 /// Fusion rule from a declarative pattern (the runtime path): match the
679 /// region and stamp `tree.params` on the emitted `Op::Fused(id, _)`.
680 pub fn declarative(id: FusedOpId, tree: crate::registry::PatternTree) -> Self {
681 Self {
682 id,
683 pattern: PatternKind::Declarative(tree),
684 }
685 }
686}
687
688impl Rule for FusionRule {
689 fn name(&self) -> &'static str {
690 "FusedOpFusion"
691 }
692 fn family(&self) -> RuleFamily {
693 RuleFamily::Fusion
694 }
695
696 fn matches(&self, graph: &Graph, id: NodeId) -> bool {
697 match &self.pattern {
698 PatternKind::Callable(f) => (*f)(graph, id).is_some(),
699 PatternKind::Declarative(tree) => {
700 let consumers = |n: NodeId| {
701 (0..graph.len())
702 .filter(|&i| graph.node(NodeId(i)).inputs.contains(&n))
703 .count()
704 };
705 crate::jit::match_region(graph, id, &tree.root, &consumers).is_some()
706 }
707 }
708 }
709
710 fn rewrite(&self, graph: &mut Graph, id: NodeId, remap: &mut HashMap<NodeId, NodeId>) {
711 let pattern_match = match &self.pattern {
712 PatternKind::Callable(f) => (*f)(graph, id)
713 .expect("rewrite called with non-matching id — matcher contract violated"),
714 PatternKind::Declarative(tree) => {
715 // match_region_extract returns the region's external inputs in
716 // bind-index order PLUS the live scalar values its open slots
717 // matched (the `extract:` layer). Wrap them as a PatternMatch
718 // so the shared reconstruction path below applies. For a
719 // Runtime params template the extracted scalars REPLACE the
720 // template's (fusing a scalar region with the template's empty
721 // scalars would silently lose the live values); non-Runtime
722 // templates stamp as-is (their matchers are value-agnostic).
723 let consumers = |n: NodeId| {
724 (0..graph.len())
725 .filter(|&i| graph.node(NodeId(i)).inputs.contains(&n))
726 .count()
727 };
728 let (inputs, extracted) =
729 crate::jit::match_region_extract(graph, id, &tree.root, &consumers)
730 .expect("rewrite called with non-matching declarative pattern");
731 let params = match &tree.params {
732 FusedOpParams::Runtime { .. } => FusedOpParams::Runtime { scalars: extracted },
733 other => other.clone(),
734 };
735 crate::registry::PatternMatch {
736 bindings: inputs.iter().enumerate().map(|(i, n)| (i, *n)).collect(),
737 params,
738 }
739 }
740 };
741 // General-arity input reconstruction: bindings are (index, NodeId)
742 // pairs; sorting by index yields the emitted node's inputs in
743 // canonical order. SoftmaxLastDim binds {0 → x_id}; FusedLinear
744 // binds {0 → a, 1 → b, 2 → bias}. Missing index in the [0, N)
745 // range is a matcher contract violation.
746 let mut sorted = pattern_match.bindings.clone();
747 sorted.sort_by_key(|(idx, _)| *idx);
748 for (expected_idx, (got_idx, _)) in sorted.iter().enumerate() {
749 debug_assert_eq!(
750 *got_idx, expected_idx,
751 "FusionRule: bindings must be dense [0..N); pattern for id \
752 {:?} returned non-contiguous indices",
753 self.id,
754 );
755 }
756 let inputs: Vec<NodeId> = sorted.iter().map(|(_, n)| *n).collect();
757 // Params come from the matcher — it's authoritative on what
758 // variant the recognized subgraph represents.
759 let params = pattern_match.params;
760 let dtype = graph.node(id).dtype;
761 let shape = graph.node(id).shape.clone();
762 // A multi-output root keeps its bundle contract on the replacement node
763 // (the fused node produces the SAME slots), so `View` consumers remapped
764 // onto it stay valid. Row 172 item 2 step B (TopKLastDim(MatMul) ->
765 // MatMulTopK) is the first rule whose root is multi-output.
766 let views = graph.output_views_arc(id);
767 let new_id = graph.push(Node {
768 op: Op::Fused(self.id, params),
769 inputs,
770 shape,
771 dtype,
772 });
773 if let Some(v) = views {
774 graph
775 .set_output_views(new_id, v)
776 .expect("a fused node reproducing the root's slots keeps its bundle contract");
777 }
778 remap.insert(id, new_id);
779 }
780}
781
782// ---- Cast-fusion algebraic rule ------------------------------------------
783//
784// `CastFusionRule` fires on `Cast(src→dst) → Op(dst, ...)` chains
785// where:
786// - the Cast (or chain of casts) has exactly one consumer at
787// each link of the chain,
788// - the consumer is a **type-preserving op** (its output dtype
789// equals the cast-fed input dtype — true for unary/binary
790// arithmetic, reductions, MatMul; *false* for compare ops,
791// Where, Cast),
792// - the consumer has a kernel for the cast's *source* dtype on
793// all input slots (capability predicate says yes).
794//
795// On fire: a new consumer node is appended with the cast input
796// replaced by the cast's source. **The new consumer's output dtype
797// is the cast-source dtype, not the original output dtype.** Any
798// downstream consumers reading from the rewritten node now see the
799// new dtype. This is by design — the rule fires aggressively under
800// the assumption that downstream consumers either (a) are
801// type-tolerant or (b) will have their own cast-fusion applied,
802// collapsing the chain.
803//
804// **Caveat — semantic change**: in graphs where the downstream
805// expects the original dst_dtype (e.g. a sink that returns BF16),
806// aggressive cast-fusion silently changes the dtype the user
807// observes. Wire this rule opt-in until a downstream-tolerance
808// framework (precision filter, op-tolerance metadata) is in place
809// to guard against unsafe rewrites.
810//
811// Chain cancellation is the always-safe sub-case: when the chain
812// is a net no-op (`Cast(F32→BF16) → Cast(BF16→F32) → Op(F32)`),
813// the final source dtype already matches the consumer's input
814// slot, so neither output dtype nor kernel selection changes.
815//
816// Architecture v1.0: this is the first "algebraic" family rule.
817// Future algebraic rewrites (constant folding, identity
818// elimination, CSE hoisting) join the same family and run in the
819// same Phase 3 loop.
820//
821// Decoupling: `fuel-graph::opt` doesn't know about binding tables,
822// PrecisionGuarantee, or BackendId. The capability check is
823// injected at rule construction via [`CapabilityPredicate`]; the
824// consumer (typically the route-picker layer in fuel-storage or a
825// higher crate) is responsible for closing over a binding-table
826// reference and answering the predicate.
827
828use std::sync::Arc;
829
830/// Predicate answering "is there a registered kernel for this op
831/// with these input/output dtypes?" The dtypes vector is the
832/// consumer's full input-dtype list (after the cast-source
833/// substitution) followed by the consumer's output dtype. Format
834/// matches the binding-table key shape used by `fuel-storage`.
835///
836/// Returns `true` if at least one backend has a kernel registered
837/// for the proposed (op, dtypes) combination — the route picker
838/// later decides which backend to use.
839pub type CapabilityPredicate = Arc<dyn Fn(&Op, &[DType]) -> bool + Send + Sync>;
840
841/// `Cast(src→dst) → Op(dst) ≡ Op(src)` when the consumer has a
842/// kernel for `src`.
843///
844/// Only fires when the cast has exactly one consumer (MVP: avoids
845/// the DAG complication of partial fan-out elimination). Multi-
846/// consumer Cast handling is a follow-up: rewrite one consumer and
847/// keep the cast alive for the others.
848pub struct CastFusionRule {
849 capabilities: CapabilityPredicate,
850}
851
852impl CastFusionRule {
853 /// Build the rule with a capability predicate. The predicate
854 /// closes over whatever capability source the caller has (a
855 /// binding table, a route picker, a static manifest). The rule
856 /// itself stays decoupled from those internals.
857 pub fn new(capabilities: CapabilityPredicate) -> Self {
858 Self { capabilities }
859 }
860
861 /// Walk `node.inputs` looking for an edge ending at a Cast (or
862 /// a chain of Casts) where every link in the chain has exactly
863 /// one consumer (the next link). Returns `Some((input_index,
864 /// final_src_id, consumer_dtypes))` where `final_src_id` is the
865 /// deepest reachable source after walking through the chain.
866 /// `consumer_dtypes` is the dtypes vector to ask the predicate
867 /// about. Returns `None` if no input qualifies.
868 ///
869 /// Walking through chained casts in one pass avoids a subtle
870 /// fixpoint trap: after the outer Cast is eliminated, the inner
871 /// Cast's other consumer (the now-orphan outer Cast) is still
872 /// in the arena and would make `count_consumers != 1` on the
873 /// next iteration. Collapsing the whole chain at once sidesteps
874 /// this because we never re-examine intermediate links.
875 ///
876 /// Shared by `matches` (which discards the index) and `rewrite`
877 /// (which uses the index to point the new consumer's input edge
878 /// at the deepest source). Computed twice intentionally — the
879 /// alternative is mutable state across `matches`/`rewrite`,
880 /// which conflicts with the trait's pure-matcher contract.
881 fn find_eligible_cast_input(
882 &self,
883 graph: &Graph,
884 id: NodeId,
885 ) -> Option<(usize, NodeId, Vec<fuel_ir::DType>)> {
886 let node = graph.node(id);
887 // Don't fire on a Cast node itself — fire on the consumer.
888 if matches!(node.op, Op::Cast(_)) {
889 return None;
890 }
891 for (idx, &input_id) in node.inputs.iter().enumerate() {
892 // Walk through chained casts. `current` is the cast (or
893 // chain of casts) currently being examined; `prev` is
894 // the consumer at this link of the chain (initially `id`,
895 // then the outer-most cast as we descend).
896 if !matches!(graph.node(input_id).op, Op::Cast(_)) {
897 continue;
898 }
899 // Type-preserving filter: the consumer's output dtype
900 // must equal the cast'd input slot's dtype. This is the
901 // family of ops where rewriting the input dtype is
902 // equivalent to rewriting the output dtype — Neg/Add/
903 // Mul/Div, reductions, MatMul, etc. Excludes Compare
904 // (T→U8), Where (U8+T+T→T), and Cast itself (which we
905 // already filtered above). For non-type-preserving
906 // consumers, swapping the input dtype would produce an
907 // output we can't predict without per-op knowledge.
908 if node.dtype != graph.node(input_id).dtype {
909 continue;
910 }
911 let mut prev = id;
912 let mut current = input_id;
913 let final_src_id = loop {
914 let current_node = graph.node(current);
915 if !matches!(current_node.op, Op::Cast(_)) {
916 break current;
917 }
918 // Single-consumer constraint at this link: the cast
919 // at `current` must feed only `prev`. Otherwise we
920 // can't eliminate it (would orphan the other consumer's
921 // input edge).
922 if !is_only_consumer(graph, current, prev) {
923 // The chain stops here; we treat the current node
924 // (a Cast) as the source. The consumer takes the
925 // dst dtype of this Cast.
926 break current;
927 }
928 let Some(&next) = current_node.inputs.first() else {
929 break current;
930 };
931 prev = current;
932 current = next;
933 };
934 // If the walk didn't move past the first cast (e.g.
935 // because the first cast has multiple consumers), there's
936 // nothing to fuse for this input.
937 if final_src_id == input_id {
938 continue;
939 }
940 let final_src_dtype = graph.node(final_src_id).dtype;
941 // Build the proposed input-dtypes + output-dtype vector.
942 // Type-preserving filter above guarantees output dtype
943 // tracks the cast-fed input, so the new output dtype is
944 // `final_src_dtype` (not the original `node.dtype`).
945 let mut dtypes: Vec<fuel_ir::DType> = node
946 .inputs
947 .iter()
948 .map(|&iid| {
949 if iid == input_id {
950 final_src_dtype
951 } else {
952 graph.node(iid).dtype
953 }
954 })
955 .collect();
956 dtypes.push(final_src_dtype);
957 if (self.capabilities)(&node.op, &dtypes) {
958 return Some((idx, final_src_id, dtypes));
959 }
960 }
961 None
962 }
963}
964
965/// Returns `true` if `expected_consumer` is the only consumer of
966/// `target` in the arena. Used to guard chained-cast elimination.
967fn is_only_consumer(graph: &Graph, target: NodeId, expected_consumer: NodeId) -> bool {
968 let mut found_others = false;
969 for i in 0..graph.len() {
970 let nid = NodeId(i);
971 if nid == expected_consumer {
972 continue;
973 }
974 if graph.node(nid).inputs.contains(&target) {
975 found_others = true;
976 break;
977 }
978 }
979 !found_others
980}
981
982impl Rule for CastFusionRule {
983 fn name(&self) -> &'static str {
984 "CastFusion"
985 }
986 fn family(&self) -> RuleFamily {
987 RuleFamily::Algebraic
988 }
989
990 fn matches(&self, graph: &Graph, id: NodeId) -> bool {
991 self.find_eligible_cast_input(graph, id).is_some()
992 }
993
994 fn rewrite(&self, graph: &mut Graph, id: NodeId, remap: &mut HashMap<NodeId, NodeId>) {
995 let (idx, final_src_id, _dtypes) = self
996 .find_eligible_cast_input(graph, id)
997 .expect("CastFusionRule::rewrite called on non-matching node");
998 let node = graph.node(id).clone();
999 let final_src_dtype = graph.node(final_src_id).dtype;
1000 let mut new_inputs = node.inputs.clone();
1001 new_inputs[idx] = final_src_id;
1002 let new_id = graph.push(Node {
1003 op: node.op.clone(),
1004 inputs: new_inputs,
1005 shape: node.shape.clone(),
1006 // Type-preserving op (matcher's invariant): the new
1007 // output dtype tracks the new input dtype. Downstream
1008 // consumers seeing this node may observe a different
1009 // dtype than before the rewrite — see the module
1010 // docstring on the aggressive-semantics caveat.
1011 dtype: final_src_dtype,
1012 });
1013 remap.insert(id, new_id);
1014 }
1015}
1016
1017/// A HashMap-friendly encoding of `Op`. Needed because `Op` carries
1018/// `f64` (in `AddScalar`, `MulScalar`, `Clamp`, `LayerNormLastDim`,
1019/// `LayerNormLastDimBackward`) and `ConstData` (in `Const`), neither
1020/// of which is `Hash + Eq`. We keep `Const` out of CSE entirely
1021/// (identity-dedup happens via the executor's Arc-pointer const pool
1022/// already) and encode scalar payloads as their bit patterns.
1023#[derive(Debug, Hash, PartialEq, Eq)]
1024struct OpKey {
1025 tag: u16,
1026 ints: Vec<i64>,
1027 bits: Vec<u64>,
1028 // Sparse payloads we don't need to index into for equality are
1029 // serialized via their Debug repr as a fallback. Cheap and
1030 // correct; not used on the hot path outside simplification.
1031 dims: Vec<usize>,
1032 shape: Option<Vec<usize>>,
1033 dtype: Option<u32>,
1034}
1035
1036fn op_key(op: &Op) -> Option<OpKey> {
1037 // We deliberately refuse to CSE `Const`. Rationale above.
1038 let (tag, ints, bits, dims, shape, dtype) = match op {
1039 Op::Const => return None,
1040
1041 Op::Add => (1, vec![], vec![], vec![], None, None),
1042 Op::Sub => (2, vec![], vec![], vec![], None, None),
1043 Op::Mul => (3, vec![], vec![], vec![], None, None),
1044 Op::Div => (4, vec![], vec![], vec![], None, None),
1045
1046 Op::Neg => (10, vec![], vec![], vec![], None, None),
1047 Op::Sqr => (11, vec![], vec![], vec![], None, None),
1048 Op::Sqrt => (12, vec![], vec![], vec![], None, None),
1049 Op::Exp => (13, vec![], vec![], vec![], None, None),
1050 Op::Log => (14, vec![], vec![], vec![], None, None),
1051 Op::Sin => (15, vec![], vec![], vec![], None, None),
1052 Op::Cos => (16, vec![], vec![], vec![], None, None),
1053 Op::Tanh => (17, vec![], vec![], vec![], None, None),
1054 Op::Sigmoid => (18, vec![], vec![], vec![], None, None),
1055 Op::Silu => (19, vec![], vec![], vec![], None, None),
1056 Op::GeluTanh => (20, vec![], vec![], vec![], None, None),
1057 Op::Relu => (21, vec![], vec![], vec![], None, None),
1058 Op::Step => (22, vec![], vec![], vec![], None, None),
1059 Op::Recip => (23, vec![], vec![], vec![], None, None),
1060 Op::Abs => (24, vec![], vec![], vec![], None, None),
1061
1062 // --- comparison family (output dtype is U8) ---
1063 Op::Equal => (25, vec![], vec![], vec![], None, None),
1064 Op::Ne => (26, vec![], vec![], vec![], None, None),
1065 Op::Lt => (27, vec![], vec![], vec![], None, None),
1066 Op::Le => (28, vec![], vec![], vec![], None, None),
1067 Op::Gt => (29, vec![], vec![], vec![], None, None),
1068 // Tag 30 already taken by Op::MatMul below; the comparison
1069 // family wraps to 33 (the next free slot above linear-algebra)
1070 // for Op::Ge. The family sits at 25-29 + 33 — a small
1071 // contiguity break tolerated rather than renumbering existing
1072 // ops opportunistically.
1073 Op::Ge => (33, vec![], vec![], vec![], None, None),
1074
1075 // Ternary select. Slot 34 (next free after the comparison
1076 // family's wrap to 33).
1077 Op::Where => (34, vec![], vec![], vec![], None, None),
1078
1079 // --- rounding family (non-differentiable) ---
1080 Op::Floor => (35, vec![], vec![], vec![], None, None),
1081 Op::Ceil => (36, vec![], vec![], vec![], None, None),
1082 Op::Round => (37, vec![], vec![], vec![], None, None),
1083 Op::Sign => (38, vec![], vec![], vec![], None, None),
1084 Op::Erf => (39, vec![], vec![], vec![], None, None),
1085 // Tag 40 was Op::Cast; the unary fanout wraps to 47 (next
1086 // free slot above the 40-46 cast/shape/reduce cluster).
1087 Op::Gelu => (47, vec![], vec![], vec![], None, None),
1088 Op::Pow => (49, vec![], vec![], vec![], None, None),
1089 Op::Rsqrt => (54, vec![], vec![], vec![], None, None),
1090 Op::Rem => (55, vec![], vec![], vec![], None, None),
1091 Op::Flip { dim } => (56, vec![*dim as i64], vec![], vec![], None, None),
1092 Op::Roll { dim, shift } => (57, vec![*dim as i64, *shift], vec![], vec![], None, None),
1093 Op::CumSum { dim } => (58, vec![*dim as i64], vec![], vec![], None, None),
1094 Op::PadBackward {
1095 in_shape,
1096 padding,
1097 mode,
1098 } => {
1099 let mode_tag = match mode {
1100 crate::PadMode::Constant => 0_i64,
1101 crate::PadMode::Reflect => 1,
1102 crate::PadMode::Replicate => 2,
1103 };
1104 let mut ints: Vec<i64> = Vec::with_capacity(padding.len() * 2 + 1);
1105 for &(b, a) in padding {
1106 ints.push(b as i64);
1107 ints.push(a as i64);
1108 }
1109 ints.push(mode_tag);
1110 (
1111 60,
1112 ints,
1113 vec![],
1114 vec![],
1115 Some(in_shape.dims().to_vec()),
1116 None,
1117 )
1118 }
1119 Op::Pad {
1120 padding,
1121 mode,
1122 value,
1123 } => {
1124 let mode_tag = match mode {
1125 crate::PadMode::Constant => 0_i64,
1126 crate::PadMode::Reflect => 1,
1127 crate::PadMode::Replicate => 2,
1128 };
1129 // Flatten padding pairs into [b0, a0, b1, a1, ...] + the
1130 // mode tag. Multi-dim padding keys uniquely off this vec.
1131 let mut ints: Vec<i64> = Vec::with_capacity(padding.len() * 2 + 1);
1132 for &(b, a) in padding {
1133 ints.push(b as i64);
1134 ints.push(a as i64);
1135 }
1136 ints.push(mode_tag);
1137 (59, ints, vec![value.to_bits()], vec![], None, None)
1138 }
1139
1140 Op::MatMul => (30, vec![], vec![], vec![], None, None),
1141 Op::Transpose => (31, vec![], vec![], vec![], None, None),
1142 Op::Permute(axes) => (32, vec![], vec![], axes.clone(), None, None),
1143
1144 Op::Cast(dt) => (40, vec![], vec![], vec![], None, Some(dtype_key(*dt))),
1145 Op::BroadcastTo(s) => (41, vec![], vec![], vec![], Some(s.dims().to_vec()), None),
1146 Op::Reshape(s) => (42, vec![], vec![], vec![], Some(s.dims().to_vec()), None),
1147 Op::Contiguize => (46, vec![], vec![], vec![], None, None),
1148 Op::Unsqueeze { dim } => (45, vec![*dim as i64], vec![], vec![], None, None),
1149 Op::Squeeze { dim } => (48, vec![*dim as i64], vec![], vec![], None, None),
1150 Op::ReduceSumTo(s) => (43, vec![], vec![], vec![], Some(s.dims().to_vec()), None),
1151 Op::ReduceMaxTo(s) => (44, vec![], vec![], vec![], Some(s.dims().to_vec()), None),
1152 // Phase 7.6 step 5 (2026-05-11): tags 46/70/71/72/73/74/75/76
1153 // formerly assigned to SoftmaxLastDim, LayerNormLastDim,
1154 // RmsNormLastDim, Rope and the four backward helpers have
1155 // been retired with their `Op` variants. Those ops now flow
1156 // through the `Op::Fused(fid, fparams)` arm below (tag 200,
1157 // with id + params encoded into the int/bit slots) and CSE
1158 // dedupes correctly because each entry produces a distinct
1159 // FusedOpId.
1160 Op::SumAll => (50, vec![], vec![], vec![], None, None),
1161 Op::MaxAll => (51, vec![], vec![], vec![], None, None),
1162 Op::MinAll => (52, vec![], vec![], vec![], None, None),
1163 Op::MeanAll => (53, vec![], vec![], vec![], None, None),
1164
1165 Op::SumDim(d) => (60, vec![*d as i64], vec![], vec![], None, None),
1166 Op::MaxDim(d) => (61, vec![*d as i64], vec![], vec![], None, None),
1167 Op::MinDim(d) => (62, vec![*d as i64], vec![], vec![], None, None),
1168 Op::MeanDim(d) => (63, vec![*d as i64], vec![], vec![], None, None),
1169 Op::ArgMaxDim(d) => (64, vec![*d as i64], vec![], vec![], None, None),
1170 Op::ArgMinDim(d) => (65, vec![*d as i64], vec![], vec![], None, None),
1171
1172 Op::Concat { dim } => (80, vec![*dim as i64], vec![], vec![], None, None),
1173 Op::Slice { dim, start, len } => (
1174 81,
1175 vec![*dim as i64, *start as i64, *len as i64],
1176 vec![],
1177 vec![],
1178 None,
1179 None,
1180 ),
1181
1182 Op::AddScalar(c) => (90, vec![], vec![c.to_bits()], vec![], None, None),
1183 Op::MulScalar(c) => (91, vec![], vec![c.to_bits()], vec![], None, None),
1184 Op::PowI(n) => (92, vec![*n as i64], vec![], vec![], None, None),
1185 Op::Clamp { min, max } => (
1186 93,
1187 vec![],
1188 vec![min.to_bits(), max.to_bits()],
1189 vec![],
1190 None,
1191 None,
1192 ),
1193
1194 Op::Maximum => (100, vec![], vec![], vec![], None, None),
1195 Op::Minimum => (101, vec![], vec![], vec![], None, None),
1196
1197 // Phase 7.6 step 2: registry-extended fused ops. CSE folds two
1198 // Op::Fused nodes with identical (id, params) to one. Encoding:
1199 // base tag 200; ints = [id.0, params.tag, ...params.ints]; bits
1200 // = params.bits. Mirrors the FusedOpParamsKey shape from
1201 // crate::registry so the encoding tracks any future param
1202 // variants without rewriting this arm.
1203 Op::Fused(fid, fparams) => {
1204 let pk = fparams.key();
1205 let mut ints: Vec<i64> = Vec::with_capacity(2 + pk.ints.len());
1206 ints.push(fid.0 as i64);
1207 ints.push(pk.tag as i64);
1208 ints.extend_from_slice(&pk.ints);
1209 (200, ints, pk.bits, vec![], None, None)
1210 }
1211
1212 // Op::Scan folds ONLY its own params (n_xs, bound, emit tag,
1213 // early_exit-present flag). The BODY is hashed automatically by
1214 // base_map_hash's child-recursion, because the body-exit NodeIds are
1215 // the last two entries of the node's `inputs` (the lax.scan encoding).
1216 // Two scans with identical params but different bodies therefore get
1217 // different child-hashes and different base_map_hash. Tag 210.
1218 Op::Scan {
1219 n_carries,
1220 n_xs,
1221 bound,
1222 emit,
1223 early_exit,
1224 } => {
1225 let emit_tag: i64 = match emit {
1226 ScanEmit::All => 0,
1227 ScanEmit::Final => 1,
1228 };
1229 let exit_flag: i64 = if early_exit.is_some() { 1 } else { 0 };
1230 (
1231 210,
1232 // ⚠️ GAP-303: `n_carries` MUST be folded here. This is Fuel's own
1233 // recipe identity (base_map_hash) -- omit it and a 1-carry and a
1234 // 3-carry Scan with the same n_xs/bound/emit hash IDENTICALLY, so
1235 // cover-finding and the plan cache treat them as one recipe. Same
1236 // defect class as KISS-OPS-6.19 (an arm reading too few attrs made
1237 // Gather-on-axis-2 and axis-0 emit identical bytes), and a SECOND
1238 // site beside the seam's canonical body.
1239 //
1240 // Appended LAST so existing single-carry hashes are the only ones
1241 // that move, and they move uniformly.
1242 vec![
1243 *n_xs as i64,
1244 *bound as i64,
1245 emit_tag,
1246 exit_flag,
1247 *n_carries as i64,
1248 ],
1249 vec![],
1250 vec![],
1251 None,
1252 None,
1253 )
1254 }
1255 // Op::ScanPlaceholder folds role tag + index so Carry/0, Elem/0,
1256 // Carry/1 are all distinct in the body hash. Tag 211.
1257 Op::ScanPlaceholder { role, index } => {
1258 let role_tag: i64 = match role {
1259 ScanRole::Carry => 0,
1260 ScanRole::Elem => 1,
1261 };
1262 (
1263 211,
1264 vec![role_tag, *index as i64],
1265 vec![],
1266 vec![],
1267 None,
1268 None,
1269 )
1270 }
1271
1272 // Indexing and anything else we haven't explicitly listed:
1273 // fall back to a unique tag that includes a structural
1274 // discriminant. These ops rarely appear more than once with
1275 // identical inputs, so we just mark them non-CSE-able by
1276 // returning None. Conservative; safe.
1277 _ => return None,
1278 };
1279 Some(OpKey {
1280 tag,
1281 ints,
1282 bits,
1283 dims,
1284 shape,
1285 dtype,
1286 })
1287}
1288
1289fn dtype_key(dt: DType) -> u32 {
1290 // Cheap injection: the Debug form is stable.
1291 // For tiny enums this compiles to a jump table.
1292 format!("{dt:?}")
1293 .as_bytes()
1294 .iter()
1295 .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(*b as u32))
1296}
1297
1298/// `Maximum`/`Minimum` are DELIBERATELY ABSENT. They are commutative in
1299/// value and NOT in bits: `chassis/binary.rs` returns the FIRST NaN operand
1300/// (`if a.is_nan() { a } else if b.is_nan() { b }`), a documented lhs-first
1301/// tie-break matching `torch.maximum`. Two distinct NaN payloads therefore
1302/// swap with operand order -- measured, `max(0x7FC00001, 0x7FC00002)` gives
1303/// `0x7FC00001` and the reverse gives `0x7FC00002` -- so folding `min(a,b)`
1304/// with `min(b,a)` is an INVALID rewrite. See GAP-271.
1305///
1306/// The +-0 tie ALSO makes the fold invalid, but do not state it as a fixed
1307/// bias: the +-0 answer is NOT A PROPERTY OF THIS SOURCE. It is decided per
1308/// CALL SITE by the optimizer, because we delegate to Rust's `f32::max`,
1309/// which disclaims the zero tie. Measured in ONE binary at opt-level 3:
1310/// const-folded literals give +0 for both orders; `black_box` operands give
1311/// -0 for both; `#[inline(never)]` gives -0 and +0 -- ORDER-DEPENDENT.
1312/// Three answers, same source. That is itself a reason the fold is invalid:
1313/// folding two call sites merges forms the compiler may resolve differently.
1314///
1315/// Rely on the NaN-payload argument, because it is STABLE -- verified
1316/// identical at opt-level 0 and 3, under `black_box` and under
1317/// `#[inline(never)]`. It is stable precisely because that tie-break is
1318/// EXPLICIT IN OUR SOURCE, where the +-0 tie is delegated to the compiler.
1319fn is_commutative(op: &Op) -> bool {
1320 matches!(op, Op::Add | Op::Mul)
1321}
1322
1323/// Run CSE + algebraic simplification on the graph reachable from
1324/// `roots`. Returns the (possibly-rewritten) roots the caller should
1325/// use afterward.
1326///
1327/// The pass runs to a fixed point on a single topological walk: each
1328/// node is visited once, canonicalized (inputs remapped, constants
1329/// folded where trivial), then either matched to an existing canonical
1330/// node (CSE) or appended as fresh. No multi-pass iteration — the
1331/// simplification rules are chosen so one forward pass suffices.
1332pub fn optimize(graph: &SharedGraph, roots: &[NodeId]) -> Vec<NodeId> {
1333 let order = {
1334 let g = graph.read().unwrap();
1335 topo_order_multi(&g, roots)
1336 };
1337
1338 let mut g = graph.write().unwrap();
1339 let mut remap: HashMap<NodeId, NodeId> = HashMap::new();
1340 let mut cse: HashMap<(OpKey, Vec<NodeId>), NodeId> = HashMap::new();
1341
1342 for id in order {
1343 let (op, inputs, shape, dtype) = {
1344 let node = g.node(id);
1345 (
1346 node.op.clone(),
1347 node.inputs.clone(),
1348 node.shape.clone(),
1349 node.dtype,
1350 )
1351 };
1352 let mapped_inputs: Vec<NodeId> = inputs
1353 .iter()
1354 .map(|input_id| *remap.get(input_id).unwrap_or(input_id))
1355 .collect();
1356 let inputs_unchanged = mapped_inputs == inputs;
1357
1358 // 1. Algebraic simplifications that produce an alias (no new
1359 // node). If a rule fires, we remap this id to an existing
1360 // node and skip CSE for it entirely.
1361 //
1362 // Identity Cast(d) on a dtype-d input is a no-op: dispatch keys
1363 // casts on [src, dst] and intentionally registers no [d, d]
1364 // kernel, so this elision (not a kernel) is what makes a same-dtype
1365 // cast disappear before realize. Needs the input node's dtype, so
1366 // it lives here rather than in `try_simplify` (which sees only
1367 // op + inputs).
1368 if let Op::Cast(target) = &op {
1369 if g.node(mapped_inputs[0]).dtype == *target {
1370 remap.insert(id, mapped_inputs[0]);
1371 continue;
1372 }
1373 // GAP-183: lower `Cast(float -> Bool)` to `Ne(x, x*0)`.
1374 //
1375 // WHY A LOWERING RATHER THAN A KERNEL: CUDA already ships the
1376 // `!= 0` test — `ne_{f32,f64,f16,bf16}_u8` in
1377 // `cuda/compare.fkc.md` — but a STORAGE-level cast cannot compose
1378 // graph ops, so those kernels are unreachable from `to_dtype`.
1379 // Rewriting here reaches them. The INTEGER half is deliberately
1380 // left alone: CUDA has no integer compare kernel, so lowering it
1381 // would relocate the same decline while bypassing CPU's real
1382 // int->Bool cast kernels.
1383 //
1384 // WHY `MulScalar(0.0)` FOR THE ZEROS: its own doc says it exists
1385 // "to avoid building a full-shape const just to add or multiply by
1386 // a constant" — so the zeros inherit shape AND dtype from the
1387 // input by construction, with nothing materialized. `Op::ZeroFill`
1388 // is NOT usable here: it is DESTRUCTIVE (writes through input 0).
1389 //
1390 // ⚠️ THE IEEE REASONING, because a reader will stop at `x*0` and
1391 // wonder about non-finite inputs:
1392 // finite x != 0 : x*0 = ±0 -> x != 0 -> true
1393 // x = ±0.0 : x*0 = ±0 -> equal -> false
1394 // (IEEE: -0.0 == 0.0, so -0.0 is FALSE)
1395 // x = NaN : NaN*0 = NaN -> NaN != NaN -> TRUE
1396 // x = ±inf : inf*0 = NaN -> x != NaN -> true
1397 // NaN being truthy matches PyTorch's `.bool()` and the CPU cast
1398 // kernels, so both paths agree.
1399 //
1400 // NOTE the zeros operand is NaN (not 0) whenever x is NaN or ±inf,
1401 // and that is HARMLESS rather than load-bearing: for every
1402 // non-finite x, `x != NaN` and `x != 0` are both true, so the two
1403 // spellings agree everywhere. A future "x*0 => zeros" fold would
1404 // therefore be SAFE here — recorded because the opposite is the
1405 // intuitive guess, and an earlier draft of this comment asserted
1406 // it as a hazard. Only `AddScalar(0)`/`MulScalar(1)` fold today.
1407 if *target == fuel_ir::DType::Bool {
1408 let src_dtype = g.node(mapped_inputs[0]).dtype;
1409 if src_dtype.is_float() {
1410 let src_shape = g.node(mapped_inputs[0]).shape.clone();
1411 let zeros = g.push(Node {
1412 op: Op::MulScalar(0.0),
1413 inputs: vec![mapped_inputs[0]],
1414 shape: src_shape.clone(),
1415 dtype: src_dtype,
1416 });
1417 let ne = g.push(Node {
1418 op: Op::Ne,
1419 inputs: vec![mapped_inputs[0], zeros],
1420 shape: src_shape,
1421 dtype: fuel_ir::DType::Bool,
1422 });
1423 remap.insert(id, ne);
1424 continue;
1425 }
1426 }
1427 }
1428 if let Some(aliased) = try_simplify(&op, &mapped_inputs) {
1429 remap.insert(id, aliased);
1430 continue;
1431 }
1432
1433 // 2. CSE: if a structurally-identical canonical node already
1434 // exists, reuse it. Commutative ops use sorted inputs as
1435 // the key so `a+b` and `b+a` match. If no match exists and
1436 // nothing about this node needs rewriting (inputs unchanged,
1437 // no simplification fired), keep the original node in place
1438 // to avoid polluting the arena with identical copies.
1439 if let Some(key) = op_key(&op) {
1440 let key_inputs = if is_commutative(&op) {
1441 let mut v = mapped_inputs.clone();
1442 v.sort();
1443 v
1444 } else {
1445 mapped_inputs.clone()
1446 };
1447 let full_key = (key, key_inputs);
1448 if let Some(&existing) = cse.get(&full_key) {
1449 remap.insert(id, existing);
1450 continue;
1451 }
1452 let canonical_id = if inputs_unchanged {
1453 id
1454 } else {
1455 g.push(Node {
1456 op: op.clone(),
1457 inputs: mapped_inputs.clone(),
1458 shape: shape.clone(),
1459 dtype,
1460 })
1461 };
1462 cse.insert(full_key, canonical_id);
1463 remap.insert(id, canonical_id);
1464 } else {
1465 // Const or other non-CSE-able op. Keep the original if
1466 // unchanged; otherwise append a rewritten copy (Const
1467 // never has inputs, so this branch effectively keeps
1468 // Const originals).
1469 let canonical_id = if inputs_unchanged {
1470 id
1471 } else {
1472 g.push(Node {
1473 op: op.clone(),
1474 inputs: mapped_inputs,
1475 shape,
1476 dtype,
1477 })
1478 };
1479 remap.insert(id, canonical_id);
1480 }
1481 }
1482
1483 roots.iter().map(|r| *remap.get(r).unwrap_or(r)).collect()
1484}
1485
1486/// Insert `Op::Copy` nodes so every op's inputs live on the same
1487/// device as the op itself. Returns the rewritten roots.
1488///
1489/// This is the Phase-3.5 pass that lifts the Router from "explicit
1490/// copies only" to "auto-insert where needed."
1491///
1492/// ## Device inference rules
1493///
1494/// For each node N, walked in topological order:
1495///
1496/// 1. **Target device** = first match wins:
1497/// - If N has a placement hint via `graph.set_placement(n, d)`, use `d`.
1498/// - Else, inherit from N's first input's inferred device.
1499/// - Else (N is a Const or the first input has no inferred device
1500/// either), the target is `None` — N is "placeless" and will be
1501/// placed by its consumer's demands.
1502///
1503/// 2. **Input reconciliation**: for each input I of N, if I's inferred
1504/// device differs from N's target device, insert an
1505/// `Op::Copy { target }` node and redirect N's input edge to the
1506/// new Copy.
1507///
1508/// ## What it doesn't do
1509///
1510/// - **Backward ops:** the pass currently treats all ops the same
1511/// way — no special reasoning about what device a backward node
1512/// should run on. For pure inference this is fine; for training
1513/// through the Router we'd want a reverse-mode pass that mirrors
1514/// forward placement. Tracked as a follow-up TODO.
1515/// - **Const placement lowering:** if a Const flows into a single
1516/// consumer on device D, we emit `Copy(Const, D)` instead of
1517/// tagging the Const itself as on-device-D. A future cost-lowering
1518/// pass can fuse the two — tracked as a TODO alongside Phase 4's
1519/// scheduler.
1520/// - **Redundant copy elision:** `Copy(X, A) -> Copy(_, A)` when X is
1521/// already on A is dropped via the idempotent check in step 2, but
1522/// there's no pass that merges `Copy(X, A) -> Copy(_, B) -> Copy(_, A)`
1523/// (cross-device round-trips that cancel). Also future.
1524pub fn insert_copies(graph: &SharedGraph, roots: &[NodeId]) -> Vec<NodeId> {
1525 let order = {
1526 let g = graph.read().unwrap();
1527 topo_order_multi(&g, roots)
1528 };
1529
1530 // Inferred output device per node. `None` = placeless (e.g., an
1531 // unplaced Const). Read on the input side to decide whether a
1532 // Copy is needed.
1533 let mut inferred: HashMap<NodeId, Option<DeviceLocation>> = HashMap::new();
1534 // Rewritten (old → new) node ID map. A node gets rewritten when
1535 // any of its inputs needed a Copy interposed.
1536 let mut remap: HashMap<NodeId, NodeId> = HashMap::new();
1537
1538 let mut g = graph.write().unwrap();
1539
1540 for id in order {
1541 // Snapshot the node — all subsequent reads need the old id's
1542 // metadata, not whatever we're about to rewrite.
1543 let (op, inputs, shape, dtype) = {
1544 let node = g.node(id);
1545 (
1546 node.op.clone(),
1547 node.inputs.clone(),
1548 node.shape.clone(),
1549 node.dtype,
1550 )
1551 };
1552 let placement_hint = g.placement(id);
1553
1554 // Target device for this node: explicit hint > first input's
1555 // inferred device > None (placeless).
1556 let target_device: Option<DeviceLocation> = match placement_hint {
1557 Some(d) => Some(d),
1558 None => inputs.first().and_then(|i| {
1559 let mapped = *remap.get(i).unwrap_or(i);
1560 inferred.get(&mapped).copied().flatten()
1561 }),
1562 };
1563
1564 // Walk inputs, inserting Copy where needed.
1565 let mut new_inputs: Vec<NodeId> = Vec::with_capacity(inputs.len());
1566 let mut any_changed = false;
1567 for input_id in &inputs {
1568 let mapped_in = *remap.get(input_id).unwrap_or(input_id);
1569 let in_device = inferred.get(&mapped_in).copied().flatten();
1570
1571 let needs_copy = match (in_device, target_device) {
1572 // Both known and disagree → copy.
1573 (Some(src), Some(tgt)) if src != tgt => true,
1574 // Input is placeless and we have a target → copy
1575 // (Const gets Copy'd onto the target device; the
1576 // future cost-lowering pass can fuse this).
1577 (None, Some(_)) => true,
1578 // Everything else (match, or no target) → no copy.
1579 _ => false,
1580 };
1581
1582 if needs_copy {
1583 let tgt = target_device.expect("needs_copy implies target is Some");
1584 // A Copy preserves the INPUT's shape/dtype, not the
1585 // outer consumer's. Read them from the source node.
1586 let (in_shape, in_dtype) = {
1587 let n = g.node(mapped_in);
1588 (n.shape.clone(), n.dtype)
1589 };
1590 let copy_id = g.push(Node {
1591 op: Op::Copy { target: tgt },
1592 inputs: vec![mapped_in],
1593 shape: in_shape,
1594 dtype: in_dtype,
1595 });
1596 inferred.insert(copy_id, Some(tgt));
1597 new_inputs.push(copy_id);
1598 any_changed = true;
1599 } else {
1600 if mapped_in != *input_id {
1601 any_changed = true;
1602 }
1603 new_inputs.push(mapped_in);
1604 }
1605 }
1606
1607 // If nothing changed and this isn't a node whose inference
1608 // output device we need to record fresh, keep the original.
1609 let canonical_id = if any_changed {
1610 let new_id = g.push(Node {
1611 op: op.clone(),
1612 inputs: new_inputs,
1613 shape,
1614 dtype,
1615 });
1616 // Carry placement hint to the rewritten node so downstream
1617 // consumers see the same target.
1618 if let Some(d) = placement_hint {
1619 g.set_placement(new_id, d);
1620 }
1621 new_id
1622 } else {
1623 id
1624 };
1625
1626 // Record this node's inferred output device:
1627 // - Op::Copy / Op::Move: output is the transfer target.
1628 // - Else if we have a target_device, that's the output
1629 // device (it matches all inputs post-reconciliation).
1630 // - Else None (placeless forward).
1631 let out_device = match &op {
1632 Op::Copy { target } | Op::Move { target } => Some(*target),
1633 _ => target_device,
1634 };
1635 inferred.insert(canonical_id, out_device);
1636 remap.insert(id, canonical_id);
1637 }
1638
1639 roots.iter().map(|r| *remap.get(r).unwrap_or(r)).collect()
1640}
1641
1642/// Lower `Const` placements: if every consumer of an unplaced Const
1643/// has the same placement hint, tag the Const with that placement.
1644///
1645/// This is a pre-pass for [`insert_copies`]. Without it, a model's
1646/// weight Consts (unplaced at graph-build time) flow into ops tagged
1647/// for a specific device; insert_copies then emits a Copy for each
1648/// such Const every forward. Lowering the Const's placement directly
1649/// tells the Router to upload it straight to the target device, and
1650/// insert_copies skips the Copy.
1651///
1652/// Conservative: a Const whose consumers disagree on device stays
1653/// unplaced. A future replication pass could clone the Const to each
1654/// target, but that needs to weigh replication cost against transfer
1655/// cost — scheduler territory (Phase 4).
1656///
1657/// Returns the number of Const placements set. Mutates `graph`
1658/// placements in place.
1659pub fn lower_const_placement(graph: &SharedGraph, roots: &[NodeId]) -> usize {
1660 // Reverse edges: for each node, list its consumers. Only walks
1661 // nodes reachable from `roots`, so unused Consts don't waste work.
1662 let order = {
1663 let g = graph.read().unwrap();
1664 topo_order_multi(&g, roots)
1665 };
1666
1667 let mut consumers: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
1668 {
1669 let g = graph.read().unwrap();
1670 for &nid in &order {
1671 let node = g.node(nid);
1672 for &input in &node.inputs {
1673 consumers.entry(input).or_default().push(nid);
1674 }
1675 }
1676 }
1677
1678 let mut lowered = 0;
1679 let mut g = graph.write().unwrap();
1680 for &nid in &order {
1681 // Only consider Const nodes without an explicit placement.
1682 let is_const = matches!(g.node(nid).op, Op::Const);
1683 if !is_const || g.placement(nid).is_some() {
1684 continue;
1685 }
1686 let Some(cs) = consumers.get(&nid) else {
1687 continue; // Const is a root — no consumers to infer from.
1688 };
1689 // Walk consumers; collect their placements. If all are
1690 // Some and agree, adopt that device.
1691 let mut target: Option<DeviceLocation> = None;
1692 let mut unanimous = true;
1693 for &c in cs {
1694 match g.placement(c) {
1695 Some(d) => match target {
1696 None => target = Some(d),
1697 Some(prev) if prev == d => {}
1698 Some(_) => {
1699 unanimous = false;
1700 break;
1701 }
1702 },
1703 None => {
1704 unanimous = false;
1705 break;
1706 }
1707 }
1708 }
1709 if unanimous && let Some(d) = target {
1710 g.set_placement(nid, d);
1711 lowered += 1;
1712 }
1713 }
1714 lowered
1715}
1716
1717/// Try to produce an aliasing simplification: "this op is equivalent
1718/// to one of its inputs." Returns the aliased NodeId if so.
1719fn try_simplify(op: &Op, inputs: &[NodeId]) -> Option<NodeId> {
1720 match op {
1721 // AddScalar(0) and MulScalar(1) are no-ops. Route consumers
1722 // straight to the input and drop the op.
1723 Op::AddScalar(c) if *c == 0.0 => Some(inputs[0]),
1724 Op::MulScalar(c) if *c == 1.0 => Some(inputs[0]),
1725 // PowI(1) is a no-op. PowI(0) would be "1" but that needs a
1726 // new const node with the right shape — skip here, let the
1727 // executor handle or another rule add it.
1728 Op::PowI(1) => Some(inputs[0]),
1729 _ => None,
1730 }
1731}
1732
1733// ---- Ordering analysis for destructive ops ---------------------------------
1734//
1735// A destructive op (one whose `Op::destructive_input()` is `Some(i)`)
1736// invalidates its i-th input when it runs. For correctness, every
1737// non-destructive reader of that input must complete BEFORE the
1738// destructive op runs. The graph's data-flow edges don't express this
1739// — they'd let a backend schedule the destructive op any time after
1740// its input is produced, including AHEAD of sibling readers.
1741//
1742// `derive_ordering` analyzes the graph and returns a map of
1743// destructive-op → sibling-readers. The [`execution_plan`] below
1744// consumes this map alongside the data graph in a Kahn's-algorithm
1745// walk to produce an execution order that respects both constraint
1746// kinds.
1747
1748/// Derived ordering edges beyond the data-flow graph. Each entry
1749/// `(nid, deps)` means `nid` must run after every node in `deps`.
1750///
1751/// Produced by [`derive_ordering`] from destructive-op metadata
1752/// ([`Op::destructive_input`]). Consumed by [`execution_plan`].
1753#[derive(Debug, Clone, Default)]
1754pub struct OrderingEdges(pub HashMap<NodeId, Vec<NodeId>>);
1755
1756impl OrderingEdges {
1757 pub fn new() -> Self {
1758 Self(HashMap::new())
1759 }
1760
1761 /// True if the map is empty — no destructive ops in the analyzed
1762 /// subgraph, so the execution plan is just the plain topo order.
1763 pub fn is_empty(&self) -> bool {
1764 self.0.is_empty()
1765 }
1766
1767 /// Get the set of must-run-before nodes for `nid`, if any.
1768 pub fn deps_of(&self, nid: NodeId) -> &[NodeId] {
1769 self.0.get(&nid).map(|v| v.as_slice()).unwrap_or(&[])
1770 }
1771}
1772
1773/// Fuse `MatMul → Add(rank-1 bias)` patterns into `Op::FusedLinear`
1774/// (Phase 6d Track 3). Walks the graph; for each `Add` whose LHS is
1775/// a `MatMul` and whose RHS is a rank-1 bias whose length equals the
1776/// matmul output's last dim, emits a fresh `FusedLinear` node and
1777/// remaps consumers of the `Add` to it.
1778///
1779/// Conservative: only fires when the `Add` is the sole consumer of
1780/// the `MatMul`. Otherwise we'd be creating a duplicate matmul
1781/// computation. CSE doesn't help here because `MatMul` and
1782/// `MatMul-inside-FusedLinear` aren't structurally equal at the IR
1783/// level — backends with truly fused kernels are the ones that
1784/// benefit, so we'd rather skip the fusion than waste the work.
1785///
1786/// Returns the count of fusions applied.
1787pub fn fuse_linear(graph: &SharedGraph, roots: &[NodeId]) -> usize {
1788 let order = {
1789 let g = graph.read().unwrap();
1790 topo_order_multi(&g, roots)
1791 };
1792 // Count consumers of each node (so we can guard "single consumer of matmul").
1793 let mut consumer_count: HashMap<NodeId, usize> = HashMap::new();
1794 {
1795 let g = graph.read().unwrap();
1796 for &nid in &order {
1797 for &input in &g.node(nid).inputs {
1798 *consumer_count.entry(input).or_insert(0) += 1;
1799 }
1800 }
1801 // Also count root references — a root is implicitly a consumer.
1802 for &r in roots {
1803 *consumer_count.entry(r).or_insert(0) += 1;
1804 }
1805 }
1806
1807 let mut g = graph.write().unwrap();
1808 let mut remap: HashMap<NodeId, NodeId> = HashMap::new();
1809 let mut fused = 0usize;
1810
1811 for nid in order {
1812 // Apply already-known remappings to inputs.
1813 let (op, inputs, shape, dtype) = {
1814 let n = g.node(nid);
1815 (n.op.clone(), n.inputs.clone(), n.shape.clone(), n.dtype)
1816 };
1817 let mapped: Vec<NodeId> = inputs.iter().map(|i| *remap.get(i).unwrap_or(i)).collect();
1818 // Pattern: Op::Add { inputs[0]=matmul_node, inputs[1]=rank-1 bias }.
1819 if !matches!(op, Op::Add) || mapped.len() != 2 {
1820 continue;
1821 }
1822 let lhs = mapped[0];
1823 let rhs = mapped[1];
1824 // LHS must be a MatMul.
1825 let lhs_op = g.node(lhs).op.clone();
1826 if !matches!(lhs_op, Op::MatMul) {
1827 continue;
1828 }
1829 // LHS matmul must have only THIS Add as a consumer (otherwise
1830 // fusing would duplicate the matmul computation).
1831 // Note: consumer_count counts pre-remapping references; remap
1832 // only happens for skipped nodes here so it's still valid.
1833 if consumer_count.get(&lhs).copied().unwrap_or(0) != 1 {
1834 continue;
1835 }
1836 // RHS must be a BroadcastTo of a rank-1 bias whose length
1837 // equals the matmul output's last dim. The build-time `Add`
1838 // requires same-shape inputs, so user code typically does:
1839 // bias[N].broadcast_to([..., M, N]).add(matmul_out)
1840 // Walk through that BroadcastTo to find the rank-1 source.
1841 let mm_dims = g.node(lhs).shape.dims().to_vec();
1842 if mm_dims.is_empty() {
1843 continue;
1844 }
1845 let last_dim = mm_dims[mm_dims.len() - 1];
1846 let rhs_node = g.node(rhs);
1847 let bias_src_id = if matches!(rhs_node.op, Op::BroadcastTo(_)) && rhs_node.inputs.len() == 1
1848 {
1849 *remap
1850 .get(&rhs_node.inputs[0])
1851 .unwrap_or(&rhs_node.inputs[0])
1852 } else {
1853 // Bias broadcast may also have been pre-shaped; allow rank-1
1854 // direct (rare with build-time shape checks but cheap to
1855 // recognize).
1856 rhs
1857 };
1858 let bias_dims = g.node(bias_src_id).shape.dims().to_vec();
1859 if bias_dims.len() != 1 || bias_dims[0] != last_dim {
1860 continue;
1861 }
1862 // Pull the matmul's a, b inputs (apply remap to those too).
1863 let mm_inputs = g.node(lhs).inputs.clone();
1864 if mm_inputs.len() != 2 {
1865 continue;
1866 }
1867 let a = *remap.get(&mm_inputs[0]).unwrap_or(&mm_inputs[0]);
1868 let b = *remap.get(&mm_inputs[1]).unwrap_or(&mm_inputs[1]);
1869 // Phase 7.6 step 4: emit the registry-extended shape. The
1870 // executor's `Op::Fused(FUSED_LINEAR, _)` arm dispatches to
1871 // the same fused-linear kernel as the legacy variant. Step 5
1872 // drops the legacy `Op::FusedLinear` variant entirely.
1873 let new_id = g.push(Node {
1874 op: Op::Fused(
1875 crate::registry::FusedOps::FUSED_LINEAR,
1876 crate::registry::FusedOpParams::FusedLinear,
1877 ),
1878 // FusedLinear takes the *original* rank-1 bias, not the
1879 // BroadcastTo'd one — the kernel broadcasts it internally
1880 // to the matmul output shape.
1881 inputs: vec![a, b, bias_src_id],
1882 shape,
1883 dtype,
1884 });
1885 remap.insert(nid, new_id);
1886 fused += 1;
1887 }
1888
1889 // Apply remap by rewriting any consumer that still references an
1890 // un-fused Add. Using the existing `rewrite_input` helper.
1891 if !remap.is_empty() {
1892 // Collect all node ids; iterate to update inputs that point at
1893 // remapped nodes. We need the mutable borrow; clone the set of
1894 // nodes to iterate without borrow conflicts.
1895 let n_nodes = g.nodes.len();
1896 for nid in 0..n_nodes {
1897 let node = &mut g.nodes[nid];
1898 for input in node.inputs.iter_mut() {
1899 if let Some(&new) = remap.get(input) {
1900 *input = new;
1901 }
1902 }
1903 }
1904 }
1905 fused
1906}
1907
1908/// Derive ordering edges for every destructive op reachable from
1909/// `roots`. Result: `nid` → list of other readers of `nid`'s
1910/// destroyed input.
1911///
1912/// **Bundle-aware aliasing** (Option C, Session 3): the alias-set
1913/// computation treats `Op::View { slot }` as alias-extending — every
1914/// View of a multi-output producer shares the bundle's storage Arc, so
1915/// a destructive op on the producer (or on any sibling View) must
1916/// run after every reader of every other View of the same producer.
1917/// `Op::ViewOwned` is NOT alias-extending: after its forward memcpy,
1918/// the ViewOwned's output is an independent Storage; it is still
1919/// pinned-after destructive ops on the producer via the regular
1920/// data-dependency edge (`inputs[0] == producer`), which falls out
1921/// of the standard reader analysis below without needing the
1922/// alias-set extension. The full alias-extension rule covers
1923/// `Op::Reshape` / `Op::Contiguize`
1924/// (conditionally-zero-copy contiguize ops), added to close the MLA
1925/// decode multi-round `WriteSlice` ordering defect: a destructive op
1926/// on `X` only pins the readers of nodes actually IN the alias set,
1927/// so any alias-extending op excluded from that set is a hole a
1928/// reader can fall through unpinned. `Op::Reshape`/`Op::Contiguize`
1929/// were exactly that hole (see `collect_alias_set`'s doc for the
1930/// full mechanism and the shipped workaround this makes unnecessary
1931/// for correctness).
1932///
1933/// O(V + E). Does not mutate the graph.
1934pub fn derive_ordering(graph: &crate::Graph, roots: &[NodeId]) -> OrderingEdges {
1935 let order = topo_order_multi(graph, roots);
1936
1937 // Consumer index: tensor NodeId → list of consumers of that tensor.
1938 let mut consumers: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
1939 for &nid in &order {
1940 for &input in &graph.node(nid).inputs {
1941 consumers.entry(input).or_default().push(nid);
1942 }
1943 }
1944
1945 // Alias groups, built ONCE for the whole graph instead of re-derived
1946 // per destructive op (`collect_alias_set` used to re-walk the entire
1947 // `order` from scratch for every one of them — O(destructive_ops *
1948 // order.len())). Every alias-extending node (view/bundle-projection/
1949 // reshape-contiguize — see `alias_group_of`'s doc) points at the SAME
1950 // group id as whatever it extends, in a single forward pass; querying
1951 // a group's members is then an O(1) map lookup. See `alias_group_of`
1952 // for why this produces the identical partition `collect_alias_set`
1953 // did, including the sibling-bundle case.
1954 let (alias_group_of, alias_members) = alias_groups(graph, &order);
1955
1956 let mut ordering: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
1957 for &nid in &order {
1958 let node = graph.node(nid);
1959 let Some(d_idx) = node.op.destructive_input() else {
1960 continue;
1961 };
1962 if d_idx >= node.inputs.len() {
1963 continue;
1964 }
1965 let destroyed = node.inputs[d_idx];
1966 // The alias set of `destroyed`: the destructive op writes
1967 // through `destroyed`'s Storage Arc, and every view-op node
1968 // transitively derived from `destroyed` shares that same Arc
1969 // (executor's view-op materialization wraps the source's Arc
1970 // in a fresh Layout — see `is_view_op` in `lib.rs`). So a
1971 // reader of any alias-set member sees `destroyed`'s bytes
1972 // and must run BEFORE the destructive op. Without this
1973 // walk, `y = x.transpose(); z = relu(y); x.relu_inplace()`
1974 // would not pin `relu(y)` before `relu_inplace(x)`, even
1975 // though they share storage.
1976 let group = alias_group_of.get(&destroyed).copied().unwrap_or(destroyed);
1977 // `destroyed` itself is always a member, even when nothing
1978 // aliases it (the common case: no entry in `alias_members` at
1979 // all) — mirrors `collect_alias_set`'s unconditional seed
1980 // `alias.insert(root)`. Without this fallback a non-aliased
1981 // target's own direct readers would never get visited below.
1982 let singleton = vec![group];
1983 let alias_set = alias_members.get(&group).unwrap_or(&singleton);
1984 for &alias in alias_set {
1985 let Some(readers) = consumers.get(&alias) else {
1986 continue;
1987 };
1988 for &reader in readers {
1989 // Skip the destructive op itself + readers that are
1990 // themselves alias members (those are view ops; their
1991 // own consumers are what we actually need to pin, and
1992 // they show up in subsequent iterations).
1993 if reader != nid && !alias_set.contains(&reader) {
1994 ordering.entry(nid).or_default().push(reader);
1995 }
1996 }
1997 }
1998 }
1999 OrderingEdges(ordering)
2000}
2001
2002/// Collect the alias set of `root`: every node whose realized Storage
2003/// is the same `Arc<RwLock<Storage>>` as `root`'s.
2004///
2005/// Three families of alias-extending op share the input's Storage Arc
2006/// at realize time:
2007///
2008/// 1. **Single-input view ops** ([`Op::is_view_op`]): the executor
2009/// wraps the source's Arc with a fresh Layout — no copy. Examples:
2010/// `Op::Transpose`, `Op::Permute`, `Op::Slice`, `Op::Unsqueeze`,
2011/// `Op::Squeeze`, `Op::BroadcastTo`, `Op::Flip`.
2012/// 2. **Multi-output projection** (`Op::View { slot }`): the
2013/// realized View clones the producer's bundled storage Arc and
2014/// exposes one slot's window — bytes are shared, the bundle's Arc
2015/// refcount tracks the consumer's lifetime (Session 1 of the
2016/// multi-output Option C design — see
2017/// [`fuel_ir::storage::OutputView`]).
2018/// 3. **Conditionally zero-copy contiguize ops** (`Op::Reshape`,
2019/// `Op::Contiguize`): `fuel-dispatch`'s `WorkItemKind::ContiguizeOf`
2020/// execution arm ADOPTS the input's Storage Arc verbatim — no
2021/// allocation, no copy — whenever the input layout is already
2022/// contiguous at offset 0; only a non-contiguous or offset input
2023/// forces a fresh `auto_contiguize` allocation. Because that check
2024/// is a RUNTIME layout fact `collect_alias_set` cannot evaluate at
2025/// graph-build time (offset-0-contiguity depends on the layouts
2026/// realized upstream), Reshape/Contiguize are treated as
2027/// UNCONDITIONALLY alias-extending here — conservative in the
2028/// (rarer) case they materialize a fresh copy, since an extra
2029/// ordering pin only serializes two ops that didn't actually need
2030/// it; never unsafe, since the alternative (treating them as
2031/// alias-opaque) is exactly the ordering defect this variant
2032/// fixes: a destructive op's OWN direct alias-set members were
2033/// already pinned-after-their-readers correctly, but a
2034/// Reshape/Contiguize hop is a graph-visible node in its own right
2035/// — if it's excluded from the alias set, its consumers are never
2036/// visited by the pin loop below, so a reader on the OTHER side of
2037/// an adopted-Arc Reshape/Contiguize has no ordering guarantee
2038/// against a destructive op reusing the SAME storage. This is the
2039/// MLA decode multi-round `WriteSlice` defect: layer `L`'s
2040/// post-append cache buffer is read once (non-destructively)
2041/// through a `Slice` → `Reshape` (head-split-style) → kernel chain
2042/// that becomes an ancestor of layer `L+1`'s write, and again as
2043/// the destination of layer `L`'s NEXT round's append — see
2044/// `fuel-core/src/lazy_deepseek2.rs`'s
2045/// `DeepSeek2Model::rebind_latent_cache_fresh_graph` doc, whose
2046/// graph-rebinding workaround this fix makes unnecessary for
2047/// CORRECTNESS (rebinding remains a legitimate memory/perf choice —
2048/// it also caps unbounded graph growth across steps — but a
2049/// same-graph multi-step decode no longer silently corrupts or
2050/// hard-errors without it).
2051///
2052/// `Op::ViewOwned` is explicitly NOT alias-extending: at execution
2053/// time it allocates a fresh standalone Storage and memcpys the
2054/// slot's bytes in. After the memcpy runs, no Arc handle on the
2055/// producer's bundle remains in the ViewOwned's chain. ViewOwned is
2056/// still pinned-after destructive readers via the regular
2057/// data-dependency edge (its `inputs[0]` is the producer), which the
2058/// caller already accounts for outside this function.
2059///
2060/// **Sibling-bundle rule**: when `root` is itself an `Op::View`,
2061/// every other `Op::View` of the same producer shares the same
2062/// bundle Arc. To capture them, the function pre-seeds the producer
2063/// into the alias set so the forward walk picks up siblings the same
2064/// way it picks up downstream `is_view_op` derivatives.
2065///
2066/// Implementation: O(|order|) forward walk after a constant-time
2067/// pre-seed. A node enters the alias set iff its op is in the
2068/// alias-extending union AND its `inputs[0]` is already in the set.
2069/// Builds the alias-equivalence partition over the WHOLE `order` in a
2070/// single forward pass, replacing the old `collect_alias_set`'s
2071/// per-destructive-op walk of the entire `order` (O(destructive_ops *
2072/// order.len()) — a second, independent quadratic cost alongside
2073/// `insert_safety_copies`' own, confirmed as the dominant cost in a live
2074/// decode-step profile: ~55% of total step time went to this family of
2075/// per-call graph rebuilds).
2076///
2077/// Every alias-extending node (the same three families as before: single-
2078/// input view ops, `Op::View{slot}` bundle projections, and the
2079/// conservatively-always-aliasing `Reshape`/`Contiguize`) is mapped to the
2080/// SAME group id as whatever it extends; a group's id is always its
2081/// earliest (topologically first) non-alias-extending member. Returns
2082/// `(group_of, members)`: `group_of[n]` is `n`'s group id (only present
2083/// for alias-extending nodes — absent means `n` is its own trivial
2084/// singleton group), and `members[g]` is every node in group `g`,
2085/// `g` itself included.
2086///
2087/// This produces the IDENTICAL partition the old per-call
2088/// `collect_alias_set(root, ...)` computed when called with `root` equal
2089/// to the group's EARLIEST member — the case every existing call site
2090/// exercises (`derive_ordering` always queries with a destructive op's
2091/// direct input, and a destructive op's direct input was never itself
2092/// observed, in this codebase's test suite, to be a multi-hop view
2093/// chain) — INCLUDING the sibling-bundle case (`Op::View{slot}`'s shared
2094/// producer `P`): the first `Op::View` of `P` resolves to group `P`
2095/// (since `P` is never itself inserted as a key, so `.unwrap_or(&P)`
2096/// defaults to `P`); every later `Op::View` of the same `P` resolves to
2097/// the identical group, landing all of them — and `P` itself — in one
2098/// membership list, exactly what `collect_alias_set`'s explicit "root is
2099/// a View ⇒ also seed its producer" special case achieved per-call.
2100///
2101/// ⚠️ NOT proven byte-identical for a query against a NON-earliest member
2102/// of a multi-hop alias chain (e.g. `destroyed` being a `Slice` of a
2103/// `Transpose` of a plain producer): the old per-call walk only ever
2104/// extended FORWARD from its seed, so querying from a late chain member
2105/// could under-report versus querying from the chain's root — a
2106/// pre-existing asymmetry in the old code, not introduced here. This
2107/// version computes the full, symmetric equivalence class regardless of
2108/// which member is queried (matching the function's own doc contract:
2109/// "every node whose realized Storage is the same Arc as root's"), which
2110/// can only ADD members relative to the old behavior, never drop any —
2111/// so if the two ever disagree, this version is the more conservative
2112/// (more copies/pins, never fewer) of the two. All existing
2113/// `insert_safety_copies`/`derive_ordering` tests pass unchanged.
2114fn alias_groups(
2115 graph: &crate::Graph,
2116 order: &[NodeId],
2117) -> (HashMap<NodeId, NodeId>, HashMap<NodeId, Vec<NodeId>>) {
2118 use crate::Op;
2119
2120 let mut group_of: HashMap<NodeId, NodeId> = HashMap::new();
2121 let mut members: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
2122
2123 for &nid in order {
2124 let node = graph.node(nid);
2125 // Op::View shares the producer's bundle Arc — it extends the
2126 // alias set even though it isn't an `is_view_op` in the
2127 // narrower single-storage-strided-view sense. Op::Reshape /
2128 // Op::Contiguize are CONDITIONALLY zero-copy (adopt the input
2129 // Arc iff contiguous at offset 0 — a runtime fact); treated
2130 // unconditionally alias-extending here is the conservative,
2131 // always-safe direction (see the function doc).
2132 let extends_alias = node.op.is_view_op()
2133 || matches!(node.op, Op::View { .. } | Op::Reshape(_) | Op::Contiguize);
2134 if !extends_alias {
2135 continue;
2136 }
2137 let Some(&inp) = node.inputs.first() else {
2138 continue;
2139 };
2140 let group = group_of.get(&inp).copied().unwrap_or(inp);
2141 group_of.insert(nid, group);
2142 members
2143 .entry(group)
2144 .or_insert_with(|| vec![group])
2145 .push(nid);
2146 }
2147 (group_of, members)
2148}
2149
2150/// Insert defensive `Op::Copy` snapshots ahead of destructive ops
2151/// that would otherwise produce a data-flow ↔ ordering-edge cycle.
2152///
2153/// Phase 5 of the in-place ops infrastructure
2154/// (`docs/session-prompts/in-place-ops-infrastructure.md`). The
2155/// view-aware [`derive_ordering`] (Phase 4a) handles the common case
2156/// where a destructive op's target is read only by upstream consumers
2157/// — pinning the destructive op after those reads is enough. The
2158/// case Phase 5 addresses is when a single op reads BOTH the
2159/// in-place target X AND a downstream consumer of the in-place op
2160/// (e.g., residual connections: `y = x.relu_inplace(); z = y + x`).
2161///
2162/// In that case, the data-flow says the reader (`z`) must run after
2163/// the destructive op (because it depends on `y`), and the ordering
2164/// edge says the destructive op must run after the reader (because
2165/// the reader reads `x`). Without intervention, [`execution_plan`]
2166/// detects the cycle and panics.
2167///
2168/// ## Conflict predicate (dependency-based, NOT topo-position-based)
2169///
2170/// A reader `R` of the destructive op `D`'s target needs a safety
2171/// copy iff `R` is not **provably ordered before** `D`. The proof
2172/// obligation is grounded in the executor's actual contract:
2173/// [`execution_plan`] emits a linear extension of the *combined*
2174/// precedence graph — data edges (`input → consumer`) plus
2175/// [`derive_ordering`]'s ordering edges (`reader → destructive op`) —
2176/// and the executor dispatches work items strictly sequentially in
2177/// that order. Therefore:
2178///
2179/// - `R` has a path to `D` in the combined graph AND `D` has no
2180/// path back to `R` → every valid plan runs `R` before `D`'s
2181/// mutation. Safe; **no copy**. (This covers every reader
2182/// `derive_ordering` pins directly, plus view-op readers whose
2183/// consumers are pinned — the pre-gap readers of an evict-chain
2184/// `Op::Move`, for example.)
2185/// - `D` has a path to `R` (e.g., the residual pattern: `R`
2186/// consumes `D`'s output while also reading `D`'s target) → the
2187/// pin edge `R → D` would close a cycle; the executor cannot
2188/// order `R` first. **Copy needed.**
2189/// - Neither direction → no ordering guarantee exists (possible for
2190/// alias-member view readers, which `derive_ordering` deliberately
2191/// does not pin). Safety cannot be proven, so **copy needed** —
2192/// the conservative default: a spurious copy costs bytes, a
2193/// missing copy is silent data corruption.
2194///
2195/// Historical note: this pass originally inferred conflicts from DFS
2196/// topo-order *position* (any reader appearing after `D` in
2197/// `topo_order_multi` order was treated as conflicting). Position in
2198/// a DFS walk carries no dependency information — an independent
2199/// pre-gap reader of a `Op::Move`d tensor could land after the Move
2200/// purely because of root visit order, earning a spurious copy
2201/// stamped onto the destructive op's device (live-GPU failure,
2202/// 2026-06-11).
2203///
2204/// This pass rewrites each conflict by:
2205/// 1. Inserting an `Op::Copy { target: same_device }(X) → X_safe` —
2206/// a same-device byte snapshot independent of `X`'s storage.
2207/// 2. Rewiring the conflicting reader's input from `X` to `X_safe`.
2208///
2209/// After the rewrite, the reader reads the snapshot (pre-mutation
2210/// bytes) while the destructive op proceeds on `X`. No cycle.
2211///
2212/// Scope: detects DIRECT conflicts (reader's input IS the
2213/// destructive op's target). View-mediated conflicts (reader reads
2214/// `view(X)`) fall through and produce the cycle panic from
2215/// `execution_plan` — a clear-but-not-friendly error pointing the
2216/// user at the pattern. View-mediated auto-resolution is a follow-up
2217/// (would need to insert `Copy(X)` then re-derive the view from the
2218/// snapshot for each conflicting reader).
2219///
2220/// Idempotent: calling this twice on the same graph inserts copies
2221/// at most once per conflict (the rewrite removes the conflict by
2222/// redirecting the reader's input edge to the copy).
2223///
2224/// Returns the number of safety copies inserted (for telemetry /
2225/// testing).
2226pub fn insert_safety_copies(graph: &mut crate::Graph, roots: &[NodeId]) -> usize {
2227 let order = topo_order_multi(graph, roots);
2228
2229 // Combined precedence graph: data edges (input → consumer) plus
2230 // derive_ordering's edges (reader → destructive op). This is
2231 // exactly the edge set execution_plan linearizes, so path
2232 // queries here answer "does every valid plan order A before B?".
2233 let ordering = derive_ordering(graph, roots);
2234 let node_set: std::collections::HashSet<NodeId> = order.iter().copied().collect();
2235 let mut succ: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
2236 let mut pred: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
2237 for &nid in &order {
2238 for &input in &graph.node(nid).inputs {
2239 if node_set.contains(&input) {
2240 succ.entry(input).or_default().push(nid);
2241 pred.entry(nid).or_default().push(input);
2242 }
2243 }
2244 for &dep in ordering.deps_of(nid) {
2245 if node_set.contains(&dep) {
2246 succ.entry(dep).or_default().push(nid);
2247 pred.entry(nid).or_default().push(dep);
2248 }
2249 }
2250 }
2251
2252 // All nodes reachable from `start` over `adj` (excluding `start`
2253 // itself unless it sits on a cycle). Iterative DFS; the visited
2254 // set terminates cyclic combined graphs (the very cycles this
2255 // pass exists to break).
2256 fn reach(
2257 start: NodeId,
2258 adj: &HashMap<NodeId, Vec<NodeId>>,
2259 ) -> std::collections::HashSet<NodeId> {
2260 let mut seen: std::collections::HashSet<NodeId> = std::collections::HashSet::new();
2261 let mut stack = vec![start];
2262 while let Some(n) = stack.pop() {
2263 if let Some(next) = adj.get(&n) {
2264 for &m in next {
2265 if seen.insert(m) {
2266 stack.push(m);
2267 }
2268 }
2269 }
2270 }
2271 seen
2272 }
2273
2274 // Snapshot conflicts before mutating the graph: collect
2275 // (destructive_op_id, target, conflicting_readers) tuples.
2276 struct Conflict {
2277 destructive_nid: NodeId,
2278 target: NodeId,
2279 target_shape: crate::Shape,
2280 target_dtype: DType,
2281 conflicting_readers: Vec<NodeId>,
2282 }
2283 let mut conflicts: Vec<Conflict> = Vec::new();
2284
2285 for &nid in &order {
2286 let node = graph.node(nid);
2287 let Some(d_idx) = node.op.destructive_input() else {
2288 continue;
2289 };
2290 if d_idx >= node.inputs.len() {
2291 continue;
2292 }
2293 let target = node.inputs[d_idx];
2294
2295 // Cheap pre-check: skip BOTH `reach()` walks and the
2296 // `order.len()`-sized readers scan below entirely when `target`
2297 // provably has no OTHER reader at all — the common case in a real
2298 // decode graph (KV-cache writes, release markers: nothing besides
2299 // the destructive op itself touches their target). `succ` was
2300 // already built above from EVERY node's `.inputs` edges (plus
2301 // ordering deps) for every node whose INPUT is in `node_set`, so
2302 // when `target` is in `node_set`, `succ[target]` is the COMPLETE
2303 // set of nodes with `target` as a direct input or an ordering
2304 // dependent — a superset of what the scan below finds (ordering
2305 // deps can appear here without a matching direct-input reader, but
2306 // never the reverse). Empty there (besides `nid` itself) therefore
2307 // guarantees the scan would find nothing either, so this cannot
2308 // change which copies get inserted — it only skips redundant work.
2309 // Falls through to the full computation when `target` isn't in
2310 // `node_set` (rare; `succ` doesn't cover it there).
2311 if node_set.contains(&target) {
2312 let any_other_reader = succ
2313 .get(&target)
2314 .is_some_and(|rs| rs.iter().any(|&r| r != nid));
2315 if !any_other_reader {
2316 continue;
2317 }
2318 }
2319
2320 // `forced_before`: nodes with a combined-graph path TO the
2321 // destructive op. `forced_after`: nodes the destructive op
2322 // has a combined-graph path to. A reader is provably safe
2323 // iff it is forced-before AND not forced-after (the latter
2324 // would mean its pin edge closes a cycle the executor cannot
2325 // satisfy). Anything else — cycle members, descendants, or
2326 // readers with no ordering guarantee in either direction —
2327 // gets a safety copy. False positives cost a snapshot;
2328 // false negatives are silent data corruption.
2329 let forced_before = reach(nid, &pred);
2330 let forced_after = reach(nid, &succ);
2331
2332 let mut readers: Vec<NodeId> = Vec::new();
2333 for &maybe_reader in &order {
2334 if maybe_reader == nid {
2335 continue;
2336 }
2337 if !graph.node(maybe_reader).inputs.contains(&target) {
2338 continue;
2339 }
2340 let provably_before =
2341 forced_before.contains(&maybe_reader) && !forced_after.contains(&maybe_reader);
2342 if !provably_before {
2343 readers.push(maybe_reader);
2344 }
2345 }
2346 if readers.is_empty() {
2347 continue;
2348 }
2349
2350 let target_node = graph.node(target);
2351 conflicts.push(Conflict {
2352 destructive_nid: nid,
2353 target,
2354 target_shape: target_node.shape.clone(),
2355 target_dtype: target_node.dtype,
2356 conflicting_readers: readers,
2357 });
2358 }
2359
2360 let inserted = conflicts.len();
2361 for Conflict {
2362 destructive_nid,
2363 target,
2364 target_shape,
2365 target_dtype,
2366 conflicting_readers,
2367 } in conflicts
2368 {
2369 // Pick the copy's target_location. Prefer the target's own
2370 // placement (if any) — that's the device the data lives on.
2371 // Fall back to the destructive op's placement. Most graphs
2372 // populate NEITHER `placement` (a rarely-used explicit pin,
2373 // `Graph::set_placement` / `.on_device(..)`) — ordinary
2374 // single-device `optimize_graph` only stamps the coarser
2375 // `target_backend` (`BackendId`, no gpu_id) — so fall back
2376 // further to a same-device location DERIVED from
2377 // `target_backend` before ever reaching for `Cpu`. Getting
2378 // this wrong silently strands a same-device CUDA/Vulkan
2379 // safety snapshot on the host: the (unrelated) reader this
2380 // copy exists to protect keeps its original device, so the
2381 // optimizer's own backend-follows-data logic then drags the
2382 // reader onto CPU too, and — the capture-specific failure
2383 // mode a same-device CUDA decode graph hits — an ordinary
2384 // same-device snapshot becomes a genuinely cross-device D2H
2385 // that can never be part of a CUDA graph capture (see
2386 // `fuel_dispatch::pipelined::capture_decode`, which only
2387 // ever accepts `Op::Copy` when `target` is same-device Cuda).
2388 // Only truly unplaced AND unbackended nodes (neither hint
2389 // available anywhere) fall all the way through to `Cpu`.
2390 let target_location = graph
2391 .placement(target)
2392 .or_else(|| graph.placement(destructive_nid))
2393 .or_else(|| {
2394 graph
2395 .target_backend(target)
2396 .or_else(|| graph.target_backend(destructive_nid))
2397 .map(fuel_ir::probe::BackendId::default_location)
2398 })
2399 .unwrap_or(DeviceLocation::Cpu);
2400 let copy_id = graph.push(crate::Node {
2401 op: crate::Op::Copy {
2402 target: target_location,
2403 },
2404 inputs: vec![target],
2405 shape: target_shape,
2406 dtype: target_dtype,
2407 });
2408 // Propagate target_backend so the executor can look up the
2409 // copy's wrapper. Inherit from the target (the source of the
2410 // copy), falling back to the destructive op's target_backend.
2411 if let Some(backend) = graph
2412 .target_backend(target)
2413 .or_else(|| graph.target_backend(destructive_nid))
2414 {
2415 graph.set_target_backend(copy_id, backend);
2416 }
2417 for reader_id in conflicting_readers {
2418 graph.rewrite_input(reader_id, target, copy_id);
2419 }
2420 }
2421 inserted
2422}
2423
2424/// Walk every multi-output producer in the graph and promote some of
2425/// its `Op::View` consumers to `Op::ViewOwned` when slot lifetimes
2426/// are sufficiently asymmetric that keeping the whole bundle alive
2427/// for the longest-lived slot is wasteful.
2428///
2429/// v1 heuristic (Option C, Session 2): for each multi-output producer
2430/// P, compute the per-slot "last use" position in topo order (the
2431/// max position over each slot's Views and their transitive
2432/// consumers). Slots whose last use is strictly later than at least
2433/// one other slot's last use get all their Views promoted to
2434/// `Op::ViewOwned`. The remaining short-lived slots stay as
2435/// `Op::View` so the bundle drops naturally when their last consumer
2436/// finishes.
2437///
2438/// Concrete example: SelectiveScan's `y` (slot 0) consumed at the
2439/// next layer; `last_state` (slot 1) retained across a barrier into
2440/// the next autoregressive step. `last_state`'s last use is much
2441/// later → it gets promoted to `ViewOwned`, the bundle drops once
2442/// `y`'s consumer finishes, and `last_state`'s standalone copy
2443/// survives across the gap.
2444///
2445/// Implementation: builds a consumer index over the topo order,
2446/// computes `last_use[N] = max(pos[N], last_use[consumers])` by
2447/// reverse-iterating, then per producer makes a per-slot rollup
2448/// and rewrites edges from the promoted Views to fresh
2449/// `Op::ViewOwned` nodes. Returns the number of promotions made.
2450/// Idempotent on already-promoted Views (an `Op::ViewOwned` is a
2451/// fixpoint).
2452///
2453/// **Where this plugs in:** today the multi-output infra has no
2454/// production consumer (Session 2 ships the authoring contract and
2455/// this pass; consumers light up in the
2456/// `selective-scan-ssd-chunk-multi-output-followup` session). The
2457/// pass is a no-op on graphs without any `Op::View` consumers of a
2458/// multi-output producer — the common case until consumers migrate.
2459/// Long-term it likely runs after the ranker/picker pass and before
2460/// `compile_plan`; placement is the picker session's call.
2461pub fn promote_views_for_liveness(graph: &mut crate::Graph, roots: &[NodeId]) -> usize {
2462 use crate::Op;
2463
2464 let order = topo_order_multi(graph, roots);
2465 if order.is_empty() {
2466 return 0;
2467 }
2468 // Forward consumer index: producer NodeId → list of consumer NodeIds.
2469 let mut consumers: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
2470 for &nid in &order {
2471 for &input in &graph.node(nid).inputs {
2472 consumers.entry(input).or_default().push(nid);
2473 }
2474 }
2475
2476 // `depth[N]`: longest-input-chain length feeding into N. Two
2477 // sibling consumers in the same conceptual layer get the same
2478 // depth, so the lifetime comparison below treats them symmetrically
2479 // even when topo *position* puts them in different slots of the
2480 // walk (which depends on roots[] order and traversal direction —
2481 // unstable for our purposes).
2482 let mut depth: HashMap<NodeId, usize> = HashMap::with_capacity(order.len());
2483 for &nid in &order {
2484 let mut d = 0usize;
2485 for &inp in &graph.node(nid).inputs {
2486 if let Some(&di) = depth.get(&inp)
2487 && di + 1 > d
2488 {
2489 d = di + 1;
2490 }
2491 }
2492 depth.insert(nid, d);
2493 }
2494
2495 // `last_use[N]`: max downstream depth reachable from N (including
2496 // N itself). Computed by reverse-iterating the topo order and
2497 // propagating each node's depth back to its inputs.
2498 let mut last_use: HashMap<NodeId, usize> = HashMap::with_capacity(order.len());
2499 for &nid in order.iter().rev() {
2500 let mut lu = depth[&nid];
2501 if let Some(downstream) = consumers.get(&nid) {
2502 for &c in downstream {
2503 if let Some(&cl) = last_use.get(&c)
2504 && cl > lu
2505 {
2506 lu = cl;
2507 }
2508 }
2509 }
2510 last_use.insert(nid, lu);
2511 }
2512
2513 // Find every multi-output producer that has any View / ViewOwned
2514 // consumers in this graph. Per producer: bucket the Views by slot
2515 // and compute the per-slot last-use position.
2516 struct ViewEntry {
2517 view_id: NodeId,
2518 slot: u32,
2519 is_owned: bool,
2520 }
2521 let mut by_producer: HashMap<NodeId, Vec<ViewEntry>> = HashMap::new();
2522 for &nid in &order {
2523 let node = graph.node(nid);
2524 let (slot, is_owned) = match node.op {
2525 Op::View { slot } => (slot, false),
2526 Op::ViewOwned { slot } => (slot, true),
2527 _ => continue,
2528 };
2529 // View / ViewOwned have a single input (the producer).
2530 let Some(&producer) = node.inputs.first() else {
2531 continue;
2532 };
2533 // Only meaningful if producer was declared multi-output;
2534 // otherwise it's an authoring bug that the NodeHandle::view
2535 // builder already rejected. Defensive skip.
2536 if !graph.is_multi_output(producer) {
2537 continue;
2538 }
2539 by_producer.entry(producer).or_default().push(ViewEntry {
2540 view_id: nid,
2541 slot,
2542 is_owned,
2543 });
2544 }
2545
2546 // For each producer, decide which slots get promoted and collect
2547 // the per-View promotions. Defer the actual graph mutations to a
2548 // second pass so we can iterate the analysis with `&Graph`.
2549 struct Promotion {
2550 view_id: NodeId,
2551 slot: u32,
2552 view_shape: crate::Shape,
2553 view_dtype: DType,
2554 // Consumers of `view_id` at analysis time — every edge gets
2555 // rewired to the new ViewOwned node.
2556 view_consumers: Vec<NodeId>,
2557 }
2558 let mut promotions: Vec<Promotion> = Vec::new();
2559 for views in by_producer.values() {
2560 // Per-slot last use rollup.
2561 let mut slot_last_use: HashMap<u32, usize> = HashMap::new();
2562 for v in views {
2563 let lu = last_use[&v.view_id];
2564 slot_last_use
2565 .entry(v.slot)
2566 .and_modify(|cur| {
2567 if lu > *cur {
2568 *cur = lu;
2569 }
2570 })
2571 .or_insert(lu);
2572 }
2573 // If every slot in this producer has the same last_use, the
2574 // bundle's natural drop position is fine — no promotions.
2575 let min_lu = match slot_last_use.values().copied().min() {
2576 Some(v) => v,
2577 None => continue,
2578 };
2579 for v in views {
2580 if v.is_owned {
2581 // Already owned — nothing to do (idempotent).
2582 continue;
2583 }
2584 let lu = slot_last_use[&v.slot];
2585 if lu <= min_lu {
2586 // This slot is among the shortest-lived → stays View.
2587 continue;
2588 }
2589 let v_node = graph.node(v.view_id);
2590 promotions.push(Promotion {
2591 view_id: v.view_id,
2592 slot: v.slot,
2593 view_shape: v_node.shape.clone(),
2594 view_dtype: v_node.dtype,
2595 view_consumers: consumers.get(&v.view_id).cloned().unwrap_or_default(),
2596 });
2597 }
2598 }
2599
2600 // Apply mutations: each promoted Op::View becomes a fresh
2601 // Op::ViewOwned that consumers point at instead. The old Op::View
2602 // node stays in the arena (no in-place op mutation) but is
2603 // unreachable from the roots — execution_plan + topo skip it
2604 // naturally. This mirrors the insert_safety_copies pattern of
2605 // "add new nodes + rewrite_input" rather than mutating ops in
2606 // place.
2607 let count = promotions.len();
2608 for p in promotions {
2609 let producer = graph.node(p.view_id).inputs[0];
2610 let owned_id = graph.push(crate::Node {
2611 op: Op::ViewOwned { slot: p.slot },
2612 inputs: vec![producer],
2613 shape: p.view_shape,
2614 dtype: p.view_dtype,
2615 });
2616 // Inherit target_backend from the original View when set, so
2617 // the executor can look up ViewOwned's wrapper without a
2618 // re-resolution pass.
2619 if let Some(backend) = graph.target_backend(p.view_id) {
2620 graph.set_target_backend(owned_id, backend);
2621 }
2622 for consumer in p.view_consumers {
2623 graph.rewrite_input(consumer, p.view_id, owned_id);
2624 }
2625 }
2626 count
2627}
2628
2629/// Build an execution plan that respects both data-flow edges (via
2630/// [`topo_order_multi`]) and ordering edges (via [`derive_ordering`]).
2631/// Returns a `Vec<NodeId>` in an order the executor can walk linearly,
2632/// evaluating each node's dependencies before it.
2633///
2634/// **Fast path:** when the graph has no destructive ops, this returns
2635/// the same order `topo_order_multi` does — no extra cost beyond the
2636/// analysis pass.
2637///
2638/// **Cycle detection:** if the combined (data + ordering) graph has a
2639/// cycle — the residency rule emitted a destructive op that
2640/// transitively depends on itself — this panics with a clear error
2641/// message. That panic indicates a bug in the rule that emitted the
2642/// destructive op, not user code.
2643///
2644/// **Stability:** among nodes that are concurrently ready, this
2645/// picks the one whose `topo_order_multi` index is smallest. Result:
2646/// when there are no ordering edges, the output matches
2647/// `topo_order_multi` exactly.
2648pub fn execution_plan(graph: &crate::Graph, roots: &[NodeId]) -> Vec<NodeId> {
2649 let base_order = topo_order_multi(graph, roots);
2650 let ordering = derive_ordering(graph, roots);
2651 if ordering.is_empty() {
2652 return base_order;
2653 }
2654
2655 // Position of each node in base_order — used as the stable tiebreaker.
2656 let pos: HashMap<NodeId, usize> = base_order
2657 .iter()
2658 .enumerate()
2659 .map(|(i, &n)| (n, i))
2660 .collect();
2661 let node_set: std::collections::HashSet<NodeId> = base_order.iter().copied().collect();
2662
2663 // Build in-degree + reverse adjacency for Kahn's.
2664 let mut in_degree: HashMap<NodeId, usize> = HashMap::with_capacity(base_order.len());
2665 let mut forward: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
2666 for &nid in &base_order {
2667 let node = graph.node(nid);
2668 let mut d = 0usize;
2669 for &input in &node.inputs {
2670 if node_set.contains(&input) {
2671 d += 1;
2672 forward.entry(input).or_default().push(nid);
2673 }
2674 }
2675 for &dep in ordering.deps_of(nid) {
2676 if node_set.contains(&dep) {
2677 d += 1;
2678 forward.entry(dep).or_default().push(nid);
2679 }
2680 }
2681 in_degree.insert(nid, d);
2682 }
2683
2684 // Stable ready-set keyed by base_order position. BTreeSet pops the
2685 // smallest → output matches topo order when ordering edges allow it.
2686 let mut ready: std::collections::BTreeSet<(usize, NodeId)> = base_order
2687 .iter()
2688 .copied()
2689 .filter(|n| in_degree[n] == 0)
2690 .map(|n| (pos[&n], n))
2691 .collect();
2692
2693 let mut plan = Vec::with_capacity(base_order.len());
2694 while let Some(&(_, n)) = ready.iter().next() {
2695 ready.remove(&(pos[&n], n));
2696 plan.push(n);
2697 if let Some(succs) = forward.get(&n) {
2698 for &s in succs {
2699 let d = in_degree.get_mut(&s).expect("in_degree covers all nodes");
2700 *d -= 1;
2701 if *d == 0 {
2702 ready.insert((pos[&s], s));
2703 }
2704 }
2705 }
2706 }
2707
2708 if plan.len() != base_order.len() {
2709 panic!(
2710 "execution_plan: cycle in ordering edges (plan={}, base={}) — \
2711 a destructive op transitively depends on itself. This is a \
2712 bug in whatever rule emitted the destructive op.",
2713 plan.len(),
2714 base_order.len(),
2715 );
2716 }
2717 plan
2718}
2719
2720// ---- Evict + reload graph surgery -----------------------------------------
2721
2722/// Insert an evict-chain around `candidate` to free its device storage
2723/// during a gap between uses, with automatic reload before the post-gap
2724/// consumers. Returns `(move_id, reload_id)`.
2725///
2726/// ## What it does
2727///
2728/// Inserts two new nodes:
2729/// 1. `mv = Op::Move { target: Cpu }` reading `candidate` — stages the
2730/// data to host memory AND destructively releases `candidate`'s
2731/// device-resident storage once it runs ([`Op::Move`] is the fused
2732/// Copy + Release: `destructive_input() == Some(0)`). The
2733/// [`derive_ordering`] pass pins it to run AFTER every
2734/// non-destructive reader of `candidate` (the pre-gap consumers the
2735/// caller left untouched).
2736/// 2. `reload = Op::Copy { target: src_device }` reading `mv` —
2737/// restages the data to the device for the post-gap consumers.
2738///
2739/// Then rewrites every `post_gap_consumer`'s input edge from `candidate`
2740/// to `reload`. Pre-gap consumers keep reading `candidate` directly.
2741///
2742/// Historical note: the original (legacy-executor era) chain was three
2743/// nodes — `Op::Copy{Cpu}` + side-effect-root `Op::Release` +
2744/// `Op::Copy{device}`. `Op::Move` collapsed the first two; the fused
2745/// node's output is consumed by `reload`, so no side-effect root is
2746/// needed.
2747///
2748/// ## Caller's responsibility
2749///
2750/// - `candidate` is a NodeId currently in the graph whose device
2751/// residency is `src_device`.
2752/// - `post_gap_consumers` are NodeIds currently in the graph that each
2753/// have `candidate` in their `inputs`. Typically these come from the
2754/// residency analyzer's gap-positioning logic.
2755/// - The caller stamps placement/backend metadata on the new nodes
2756/// (`mv` runs on `src_device`'s backend, `reload` on Cpu — the
2757/// staged copy's residency) before realizing on the pipelined
2758/// executor. `fuel-dispatch::residency::insert_residency_evictions`
2759/// does this.
2760pub fn insert_evict_reload(
2761 graph: &SharedGraph,
2762 candidate: NodeId,
2763 src_device: DeviceLocation,
2764 post_gap_consumers: &[NodeId],
2765) -> (NodeId, NodeId) {
2766 let mut g = graph.write().unwrap();
2767 insert_evict_reload_in(&mut g, candidate, src_device, post_gap_consumers)
2768}
2769
2770/// [`insert_evict_reload`] on a graph the caller already holds mutably (the optimizer's
2771/// `optimize_graph` takes `&mut Graph`, not a `SharedGraph`). Same chain, same rewrite.
2772pub fn insert_evict_reload_in(
2773 g: &mut Graph,
2774 candidate: NodeId,
2775 src_device: DeviceLocation,
2776 post_gap_consumers: &[NodeId],
2777) -> (NodeId, NodeId) {
2778 let (shape, dtype) = {
2779 let n = g.node(candidate);
2780 (n.shape.clone(), n.dtype)
2781 };
2782
2783 let move_id = g.push(Node {
2784 op: Op::Move {
2785 target: DeviceLocation::Cpu,
2786 },
2787 inputs: vec![candidate],
2788 shape: shape.clone(),
2789 dtype,
2790 });
2791
2792 let reload_id = g.push(Node {
2793 op: Op::Copy { target: src_device },
2794 inputs: vec![move_id],
2795 shape,
2796 dtype,
2797 });
2798
2799 // Rewrite each post-gap consumer's `candidate` input to `reload_id`.
2800 // Pre-gap consumers (not in this list) continue reading `candidate`
2801 // directly, which is why derive_ordering needs `move_id` to run
2802 // after them.
2803 for &consumer in post_gap_consumers {
2804 g.rewrite_input(consumer, candidate, reload_id);
2805 }
2806
2807 (move_id, reload_id)
2808}
2809
2810// ===========================================================================
2811// Phase 2.1 — cross-device `Op::Copy` insertion
2812// ===========================================================================
2813//
2814// When the picker (or a user pin) commits a kernel-bearing node to a
2815// `DeviceLocation` that doesn't share a storage substrate with one of
2816// its inputs' resident `DeviceLocation`, the data needs to actually
2817// move. The executor handles the FINAL output via `pipelined_bridge`'s
2818// realize-root splicing; cross-device edges INSIDE the graph are
2819// handled here.
2820//
2821// `insert_cross_device_copies` is the pre-execute pass that handles
2822// internal cross-device edges. Architecture v1.0 §04 names the
2823// optimizer as the owner of transfer-op insertion — this is that
2824// owner. Wired into `fuel-tensor::pipelined_bridge::prepare()` (picker
2825// arc step 2): the bridge derives `placement_for` from the monolithic
2826// `target_backend` pinning + the StorageCache's resident locations,
2827// and `shares_storage` from `SystemTopology`.
2828//
2829// The pass deliberately doesn't decide placements itself — callers
2830// (the optimizer ranker / picker) commit to placements first, then
2831// hand the pass `(graph, placement_for_node, shares_storage)` and
2832// it materializes the implied transfers. Same pattern as the
2833// JudgeOracle / CapabilitiesLookup callbacks in
2834// `fuel-dispatch::ranker`: keep `fuel-graph` ignorant of how
2835// placements / topology are derived; the closure is the seam.
2836
2837/// Insert `Op::Copy { target }` nodes on every edge where the
2838/// consumer's intended `DeviceLocation` doesn't share a storage
2839/// substrate with the producer's. Returns a remap of original
2840/// `NodeId`s to their post-rewrite equivalents (most NodeIds map to
2841/// themselves; only consumers of cross-device edges acquire new
2842/// inputs in-place via `rewrite_input`).
2843///
2844/// # Arguments
2845///
2846/// - `graph` — the graph to rewrite, mutably. New `Op::Copy` nodes
2847/// are appended via `Graph::push`; consumer edges are rewired via
2848/// the internal `rewrite_input` helper.
2849/// - `roots` — the realize roots the caller cares about. The pass
2850/// walks `topo_order_multi(roots)` and considers every node it
2851/// visits.
2852/// - `placement_for` — `Fn(NodeId) -> Option<DeviceLocation>`.
2853/// Returns the picker's committed placement for the node, or
2854/// `None` if the node has no placement (view ops, structural ops,
2855/// user-unpinned ops in a single-backend realize). When either
2856/// the producer or consumer has no placement, the pass leaves
2857/// the edge alone — the executor falls back to its existing
2858/// handling (auto_contiguize or the realize-root splice).
2859/// - `shares_storage` — `Fn(DeviceLocation, DeviceLocation) -> bool`.
2860/// The topology query. Typical implementation is
2861/// `SystemTopology::shares_storage((b1, dev1), (b2, dev2))` after
2862/// the caller resolves backends to devices; we pass just the
2863/// `DeviceLocation` pair here because the substrate question is
2864/// device-level (`Cpu` shares with `Cpu`, `Cuda{0}` shares with
2865/// `Cuda{0}` but not `Cuda{1}`, etc.). Same-device queries should
2866/// return `true`.
2867/// - `needs_host_staging` — `Fn(DeviceLocation, DeviceLocation) -> bool`.
2868/// For a non-shared edge that this pass IS bridging, returns `true`
2869/// when the transfer cannot be done as a SINGLE `Op::Copy` hop and
2870/// must instead route through host memory as TWO hops
2871/// (producer-GPU → CPU, then CPU → consumer-GPU). This is the
2872/// cross-VENDOR GPU↔GPU case (CUDA↔Vulkan): there is no direct
2873/// device-to-device copy kernel between distinct GPU substrates, so
2874/// the source-backend Copy kernel only accepts a CPU or same-substrate
2875/// output. The single-hop cases — CPU↔CUDA, CPU↔Vulkan, and any edge
2876/// touching CPU on either end — return `false` and get exactly ONE
2877/// `Op::Copy` (byte-identical to the pre-two-hop behavior). Typical
2878/// wiring derives this from `SystemTopology::transfer_path(src, dst)
2879/// == TransferPath::HostStaging` for GPU↔GPU pairs. When `true`, the
2880/// pass inserts a CPU intermediate `Op::Copy { target: Cpu }` (placed
2881/// on CPU) and a second `Op::Copy { target: consumer }` reading it;
2882/// the consumer is rewired to the second hop.
2883///
2884/// # Returns
2885///
2886/// The `NodeId`s of the inserted `Op::Copy` nodes, in insertion
2887/// order. Callers typically need these to stamp executor metadata
2888/// on the new nodes — e.g. `fuel-tensor::pipelined_bridge` sets
2889/// `target_backend` = the SOURCE backend (the pipelined executor's
2890/// Op::Copy kernel-lookup convention: the transfer kernel runs on
2891/// the backend the bytes come FROM). `.len()` is the transfer-count
2892/// metric the optimizer reports when deciding whether to pursue
2893/// alternative placements that minimize transfers. A two-hop
2894/// (host-staged) edge contributes BOTH inserted copies (the CPU
2895/// intermediate and the consumer-side hop) to this vec; the SOURCE-
2896/// backend re-stamp the caller applies to `inputs.first()` is
2897/// correct for each hop independently (the CPU hop's source is the
2898/// producer GPU; the consumer hop's source is the CPU intermediate).
2899///
2900/// # Idempotence
2901///
2902/// The pass is idempotent — re-running on an already-rewritten
2903/// graph adds zero new copies (the inserted `Op::Copy` nodes
2904/// carry `placement` matching the consumer's, so subsequent
2905/// passes see same-device edges from `Op::Copy` to consumer).
2906///
2907/// # CSE on inserted copies
2908///
2909/// When two consumers share an input AND both need to bring it to
2910/// the same target device, the pass deduplicates: one `Op::Copy`
2911/// node serves both consumers. This matches the existing CSE
2912/// pattern in `optimize_to_fixpoint`.
2913pub fn insert_cross_device_copies<P, S, H>(
2914 graph: &mut Graph,
2915 roots: &[NodeId],
2916 placement_for: P,
2917 shares_storage: S,
2918 needs_host_staging: H,
2919) -> Vec<NodeId>
2920where
2921 P: Fn(NodeId) -> Option<DeviceLocation>,
2922 S: Fn(DeviceLocation, DeviceLocation) -> bool,
2923 H: Fn(DeviceLocation, DeviceLocation) -> bool,
2924{
2925 let order = topo_order_multi(graph, roots);
2926 // CSE on inserted copies: `(producer, target_device) → Op::Copy NodeId`.
2927 // For a two-hop edge the CPU intermediate is itself CSE-keyed at
2928 // `(producer, Cpu)` and the consumer hop at `(cpu_intermediate, target)`,
2929 // so a producer feeding several cross-vendor consumers stages to CPU
2930 // exactly once and each distinct target gets one consumer-side hop.
2931 let mut copy_cache: HashMap<(NodeId, DeviceLocation), NodeId> = HashMap::new();
2932 let mut inserted: Vec<NodeId> = Vec::new();
2933
2934 // Two passes: first compute the rewires we want, then apply
2935 // them. Splitting avoids borrow issues with graph mutation
2936 // mid-iteration and keeps the iteration order stable.
2937 let mut rewires: Vec<(NodeId, NodeId, NodeId)> = Vec::new();
2938
2939 for &consumer_id in &order {
2940 let consumer_placement = match placement_for(consumer_id) {
2941 Some(p) => p,
2942 None => continue,
2943 };
2944 // Skip ops that are themselves transfers — `Op::Copy` /
2945 // `Op::Move` exist precisely TO bridge devices; inserting
2946 // another copy on their input would be infinite-regress.
2947 let consumer_op = &graph.node(consumer_id).op;
2948 if matches!(consumer_op, Op::Copy { .. } | Op::Move { .. }) {
2949 continue;
2950 }
2951
2952 // Snapshot inputs so we don't reborrow during the loop.
2953 let inputs: Vec<NodeId> = graph.node(consumer_id).inputs.clone();
2954 for producer_id in inputs {
2955 let producer_placement = match placement_for(producer_id) {
2956 Some(p) => p,
2957 None => continue,
2958 };
2959 if shares_storage(producer_placement, consumer_placement) {
2960 continue;
2961 }
2962
2963 // Decide hop count. A cross-VENDOR GPU↔GPU edge (e.g.
2964 // CUDA↔Vulkan) can't be done as one `Op::Copy` — there's no
2965 // direct device-to-device copy kernel between distinct GPU
2966 // substrates, so the source-backend Copy kernel rejects the
2967 // foreign-GPU output. Route it through host memory as TWO hops:
2968 // producer-GPU → CPU (intermediate), then CPU → consumer-GPU.
2969 // Single-hop edges (anything touching CPU on either end, or a
2970 // same-vendor pair the topology can copy directly) stay exactly
2971 // one `Op::Copy` — byte-identical to the pre-two-hop behavior.
2972 let two_hop = needs_host_staging(producer_placement, consumer_placement);
2973
2974 // `source_for_consumer_hop` is the node the consumer-side
2975 // `Op::Copy { target: consumer_placement }` reads FROM: the
2976 // producer directly for a single hop, or the CPU intermediate
2977 // for a two-hop edge.
2978 let source_for_consumer_hop = if two_hop {
2979 // Hop 1: producer-GPU → CPU intermediate. CSE-keyed at
2980 // `(producer, Cpu)` so a producer feeding several cross-
2981 // vendor consumers stages to CPU exactly once.
2982 match copy_cache.get(&(producer_id, DeviceLocation::Cpu)) {
2983 Some(&id) => id,
2984 None => {
2985 let producer = graph.node(producer_id);
2986 let shape = producer.shape.clone();
2987 let dtype = producer.dtype;
2988 let cpu_id = graph.push(Node {
2989 op: Op::Copy {
2990 target: DeviceLocation::Cpu,
2991 },
2992 inputs: vec![producer_id],
2993 shape,
2994 dtype,
2995 });
2996 // The CPU intermediate bridges the two hops; place
2997 // it on CPU.
2998 graph.set_placement(cpu_id, DeviceLocation::Cpu);
2999 copy_cache.insert((producer_id, DeviceLocation::Cpu), cpu_id);
3000 inserted.push(cpu_id);
3001 cpu_id
3002 }
3003 }
3004 } else {
3005 producer_id
3006 };
3007
3008 // Hop 2 (or the single hop): `source_for_consumer_hop` →
3009 // consumer device. CSE-keyed at `(source, consumer_placement)`.
3010 let copy_id = match copy_cache.get(&(source_for_consumer_hop, consumer_placement)) {
3011 Some(&id) => id,
3012 None => {
3013 let src = graph.node(source_for_consumer_hop);
3014 let shape = src.shape.clone();
3015 let dtype = src.dtype;
3016 let id = graph.push(Node {
3017 op: Op::Copy {
3018 target: consumer_placement,
3019 },
3020 inputs: vec![source_for_consumer_hop],
3021 shape,
3022 dtype,
3023 });
3024 // The inserted copy itself sits on the
3025 // consumer's device — its output is what the
3026 // consumer reads.
3027 graph.set_placement(id, consumer_placement);
3028 copy_cache.insert((source_for_consumer_hop, consumer_placement), id);
3029 inserted.push(id);
3030 id
3031 }
3032 };
3033 rewires.push((consumer_id, producer_id, copy_id));
3034 }
3035 }
3036
3037 for (consumer, old_input, new_input) in rewires {
3038 graph.rewrite_input(consumer, old_input, new_input);
3039 }
3040
3041 inserted
3042}
3043
3044/// Phase 2.2 of the picker arc — insert `Op::Contiguize` before any
3045/// kernel-bearing node whose chosen kernel doesn't accept strided
3046/// inputs but whose live input layout is non-contiguous (strided,
3047/// offset, or both).
3048///
3049/// # When to call
3050///
3051/// After Phase 2.1's `insert_cross_device_copies` and after the
3052/// picker has committed to per-node kernel choices. The picker's
3053/// commitment determines the `KernelCaps::strided_input` flag for
3054/// each node; this pass reads that flag via the `kernel_accepts_strided`
3055/// callback and inserts layout-fixups where the flag is false and
3056/// the input is strided.
3057///
3058/// # Callback contract
3059///
3060/// `kernel_accepts_strided(consumer_id) -> bool` returns `true` if
3061/// the kernel resolved for that node tolerates strided / offset
3062/// inputs (i.e. its `KernelCaps::strided_input == true`). The
3063/// callback is opaque to this pass — typical wiring reads the
3064/// picker's commit-to-winner alternative set and queries the
3065/// winner's caps. When `false`, this pass inserts `Op::Contiguize`
3066/// on every non-contiguous input.
3067///
3068/// # Skips
3069///
3070/// - View ops (`Transpose`, `Permute`, `BroadcastTo`, `Slice`,
3071/// `Unsqueeze`, `Squeeze`, `Flip`) — they preserve strided
3072/// layouts intentionally.
3073/// - Structural ops (`Const`, `Release`, `Reshape`, `Contiguize`,
3074/// `Copy`, `Move`, `Alloc`, `ZeroFill`, `WriteSlice`) — their
3075/// executor arms handle strided naturally or are not kernel-
3076/// bearing.
3077///
3078/// # CSE
3079///
3080/// When two consumers share a non-contiguous input AND both kernels
3081/// reject strided, one `Op::Contiguize` node serves both. The
3082/// per-pass cache is keyed on producer NodeId (no target-device
3083/// dimension — Contiguize is device-inheriting).
3084///
3085/// # Idempotence
3086///
3087/// Running this pass on an already-rewritten graph adds zero new
3088/// nodes: an inserted `Op::Contiguize` has a contiguous + zero-offset
3089/// output layout, so the subsequent fixup check (`is_contiguous &&
3090/// start_offset == 0`) succeeds and the input is skipped.
3091///
3092/// Returns the number of `Op::Contiguize` nodes inserted.
3093pub fn insert_layout_fixups<F>(
3094 graph: &mut Graph,
3095 roots: &[NodeId],
3096 kernel_accepts_strided: F,
3097) -> usize
3098where
3099 F: Fn(NodeId) -> bool,
3100{
3101 let order = topo_order_multi(graph, roots);
3102 // CSE: producer NodeId → Contiguize NodeId. No device dim since
3103 // Contiguize inherits the producer's residency.
3104 let mut fixup_cache: HashMap<NodeId, NodeId> = HashMap::new();
3105 let mut inserted = 0usize;
3106 let mut rewires: Vec<(NodeId, NodeId, NodeId)> = Vec::new();
3107
3108 for &consumer_id in &order {
3109 // Snapshot the consumer to release the borrow before
3110 // mutation.
3111 let (consumer_op, consumer_inputs) = {
3112 let node = graph.node(consumer_id);
3113 (node.op.clone(), node.inputs.clone())
3114 };
3115
3116 // Skip non-kernel-bearing nodes — their executor arms
3117 // either preserve strided layouts (view ops, Reshape) or
3118 // are structural with no kernel to mismatch on (Const,
3119 // Release, Copy, Move, Alloc, ZeroFill, WriteSlice,
3120 // WriteSliceDoff, Contiguize). WriteSlice/WriteSliceDoff
3121 // adopt `dest` in place + auto-contiguize their source in the
3122 // execute arm, so a pass-inserted contiguize on `dest` would
3123 // break the in-place adoption — skip them here.
3124 if consumer_op.is_view_op()
3125 || matches!(
3126 consumer_op,
3127 Op::Const
3128 | Op::Release
3129 | Op::Reshape(_)
3130 | Op::Contiguize
3131 | Op::Copy { .. }
3132 | Op::Move { .. }
3133 | Op::Alloc { .. }
3134 | Op::ZeroFill
3135 | Op::WriteSlice { .. }
3136 | Op::WriteSliceDoff { .. }
3137 )
3138 {
3139 continue;
3140 }
3141
3142 // The kernel accepts strided inputs directly — no fixup.
3143 if kernel_accepts_strided(consumer_id) {
3144 continue;
3145 }
3146
3147 for input_id in consumer_inputs {
3148 let input_layout = graph.layout(input_id);
3149 if input_layout.is_contiguous() && input_layout.start_offset() == 0 {
3150 continue;
3151 }
3152
3153 let fixup_id = match fixup_cache.get(&input_id) {
3154 Some(&id) => id,
3155 None => {
3156 let (shape, dtype) = {
3157 let p = graph.node(input_id);
3158 (p.shape.clone(), p.dtype)
3159 };
3160 let id = graph.push(Node {
3161 op: Op::Contiguize,
3162 inputs: vec![input_id],
3163 shape,
3164 dtype,
3165 });
3166 fixup_cache.insert(input_id, id);
3167 inserted += 1;
3168 id
3169 }
3170 };
3171 rewires.push((consumer_id, input_id, fixup_id));
3172 }
3173 }
3174
3175 for (consumer, old_input, new_input) in rewires {
3176 graph.rewrite_input(consumer, old_input, new_input);
3177 }
3178
3179 inserted
3180}
3181
3182/// A fused node chosen for lowering: its id, its params, and the registry's `decompose` function.
3183type PickedFused = (
3184 NodeId,
3185 FusedOpParams,
3186 fn(&mut Graph, NodeId, &FusedOpParams) -> NodeId,
3187);
3188
3189/// Lower, in place, each reachable `Op::Fused` node that `select` picks to its primitive base map
3190/// (the registered `decompose`), and rewire every consumer to the lowered output. The
3191/// *selective* sibling of [`lower_to_base_map`]: that lowers every fused op; this lowers only the
3192/// ones the caller's predicate names, so the optimizer can decide per node, from facts only it has
3193/// (which backend is pinned, which kernels are bound), without the graph layer knowing a backend.
3194///
3195/// Contract: total and never-panic. A fused id with no registry entry, or a `decompose` that
3196/// declines (returns the node's own id: wrong params, malformed node), leaves the node untouched
3197/// (the driver's fixpoint signal). **Roots are not remapped** (the caller's slice is immutable), so
3198/// a selected node that IS a root is skipped and stays fused: still correct, just not lowered.
3199/// The lowered node's orphaned original stays in the arena, unreachable from any root.
3200///
3201/// Returns the number of nodes lowered.
3202pub fn lower_selected_fused(
3203 graph: &mut Graph,
3204 roots: &[NodeId],
3205 select: &dyn Fn(&Graph, NodeId) -> bool,
3206) -> usize {
3207 let order = topo_order_multi(graph, roots);
3208 let registry = default_registry();
3209 let mut picked: Vec<PickedFused> = Vec::new();
3210 for &id in &order {
3211 if roots.contains(&id) {
3212 continue;
3213 }
3214 let Op::Fused(fid, params) = &graph.node(id).op else {
3215 continue;
3216 };
3217 let Some(entry) = registry.entry(*fid) else {
3218 continue;
3219 };
3220 if select(graph, id) {
3221 picked.push((id, params.clone(), entry.decompose));
3222 }
3223 }
3224 let mut remap: HashMap<NodeId, NodeId> = HashMap::new();
3225 for (id, params, decompose) in picked {
3226 let new_id = decompose(graph, id, ¶ms);
3227 if new_id != id {
3228 remap.insert(id, new_id);
3229 }
3230 }
3231 if remap.is_empty() {
3232 return 0;
3233 }
3234 let n_nodes = graph.len();
3235 for nid in 0..n_nodes {
3236 let inputs = graph.node(NodeId(nid)).inputs.clone();
3237 for cur in inputs {
3238 if let Some(&new) = remap.get(&cur) {
3239 graph.rewrite_input(NodeId(nid), cur, new);
3240 }
3241 }
3242 }
3243 remap.len()
3244}
3245
3246/// Insert `Op::Cast` fixups that CHANGE a consumer's input dtype — the sibling of
3247/// [`insert_layout_fixups`], for dtype rather than layout. Given precomputed
3248/// `(consumer, input, target_dtype)` edges (an input whose dtype should be
3249/// promoted so the consumer's `(op, per-operand-dtypes)` key becomes servable),
3250/// insert one `Op::Cast(target)` per distinct `(input, target)` — CSE-shared
3251/// across consumers — and rewire each consumer's edge to it.
3252///
3253/// Unlike `Graph::rewrite_input` (whose contract is a *same-dtype* redirect),
3254/// this DELIBERATELY changes the consumer's input dtype — that is the point: it
3255/// is the graph-side half of the optimizer's dtype-reconciliation pass
3256/// (`fuel_dispatch::optimize::insert_dtype_fixups`), which decides WHICH edges to
3257/// promote from backend kernel coverage. Edges apply in the given order
3258/// (deterministic when the caller passes topo order). Returns the rewires applied.
3259pub fn insert_cast_fixups(graph: &mut Graph, casts: &[(NodeId, NodeId, DType)]) -> usize {
3260 let mut cache: HashMap<(NodeId, DType), NodeId> = HashMap::new();
3261 let mut applied = 0;
3262 for &(consumer, input, target) in casts {
3263 if graph.node(input).dtype == target {
3264 continue; // already the target dtype — nothing to cast
3265 }
3266 let cast_id = *cache.entry((input, target)).or_insert_with(|| {
3267 let shape = graph.node(input).shape.clone();
3268 graph.push(Node {
3269 op: Op::Cast(target),
3270 inputs: vec![input],
3271 shape,
3272 dtype: target,
3273 })
3274 });
3275 graph.rewrite_input(consumer, input, cast_id);
3276 applied += 1;
3277 }
3278 applied
3279}
3280
3281#[cfg(test)]
3282mod tests {
3283 use super::*;
3284 use crate::NodeHandle;
3285 // `FusedOps` is referenced only in these tests; the lib-level `use` above
3286 // correctly dropped it as unused, so import it here where it's used.
3287 use crate::registry::FusedOps;
3288 use fuel_ir::{DeviceLocation, Shape};
3289 use std::sync::Arc;
3290
3291 /// Phase 7.5 G2: tests need a real device for slot-populating
3292 /// constructors. Singleton CpuBackendDevice via OnceLock.
3293 fn cpu_dev() -> &'static Arc<dyn fuel_backend_contract::DynBackendDevice> {
3294 static D: std::sync::OnceLock<Arc<dyn fuel_backend_contract::DynBackendDevice>> =
3295 std::sync::OnceLock::new();
3296 D.get_or_init(|| Arc::new(fuel_cpu_backend::dyn_impl::CpuBackendDevice))
3297 }
3298
3299 fn make_scalar_graph() -> (SharedGraph, NodeHandle) {
3300 let t = NodeHandle::from_f32(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[4]), cpu_dev())
3301 .unwrap();
3302 (t.graph().clone(), t)
3303 }
3304
3305 fn count_copy_nodes(graph: &SharedGraph) -> usize {
3306 let g = graph.read().unwrap();
3307 (0..g.len())
3308 .filter(|i| matches!(g.node(NodeId(*i)).op, Op::Copy { .. }))
3309 .count()
3310 }
3311
3312 #[test]
3313 fn insert_copies_no_placement_no_copies() {
3314 // Graph with no placement hints: pass should be a no-op, no
3315 // Copies inserted, roots unchanged.
3316 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
3317 let b = a
3318 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
3319 .unwrap();
3320 let c = a.add(&b);
3321 let graph = c.graph().clone();
3322 let before = count_copy_nodes(&graph);
3323 let new_roots = insert_copies(&graph, &[c.id()]);
3324 assert_eq!(new_roots, vec![c.id()]);
3325 assert_eq!(count_copy_nodes(&graph), before);
3326 }
3327
3328 #[test]
3329 fn insert_copies_tagged_node_pulls_inputs_to_its_device() {
3330 // Const a, Const b, Add(a, b) placed on Vulkan.
3331 // Expected: two Copy(a, Vulkan) and Copy(b, Vulkan) inserted,
3332 // Add's inputs rewritten to reference the Copies.
3333 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
3334 let b = a
3335 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
3336 .unwrap();
3337 let c = a.add(&b).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3338 let graph = c.graph().clone();
3339
3340 let before_copies = count_copy_nodes(&graph);
3341 let new_roots = insert_copies(&graph, &[c.id()]);
3342
3343 // Should be exactly 2 new Copies (one per input).
3344 assert_eq!(count_copy_nodes(&graph) - before_copies, 2);
3345
3346 // Rewritten Add should reference two Copy nodes.
3347 let g = graph.read().unwrap();
3348 let new_add = g.node(new_roots[0]);
3349 assert_eq!(new_add.inputs.len(), 2);
3350 for input in &new_add.inputs {
3351 let node = g.node(*input);
3352 assert!(matches!(
3353 node.op,
3354 Op::Copy {
3355 target: DeviceLocation::Vulkan { gpu_id: 0 }
3356 }
3357 ));
3358 }
3359 }
3360
3361 #[test]
3362 fn insert_copies_matching_device_no_copies_inserted() {
3363 // Const a and Add both placed on Vulkan. Const flows into
3364 // Add, both want Vulkan — no Copy needed.
3365 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev())
3366 .unwrap()
3367 .on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3368 let b = a
3369 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
3370 .unwrap()
3371 .on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3372 let c = a.add(&b).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3373 let graph = c.graph().clone();
3374
3375 let before = count_copy_nodes(&graph);
3376 insert_copies(&graph, &[c.id()]);
3377 assert_eq!(count_copy_nodes(&graph), before);
3378 }
3379
3380 #[test]
3381 fn insert_copies_handles_backward_graph() {
3382 // Forward: y = sum(x * x) with x placed on Vulkan.
3383 // Call backward — this appends gradient nodes to the same graph.
3384 // Then run insert_copies on BOTH the forward root and the
3385 // gradient root. Every backward op should end up on Vulkan
3386 // (inherited from its inputs, which trace back to Vulkan-placed x).
3387 let x = NodeHandle::from_f32(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[4]), cpu_dev())
3388 .unwrap()
3389 .on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3390 let sq = x.mul(&x).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3391 let y = sq.sum_all().on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3392 let graph = y.graph().clone();
3393
3394 let grads = y.backward();
3395 let grad_x = grads.get(&x).expect("dL/dx should exist");
3396
3397 // Run insert_copies on both roots.
3398 let before_copies = count_copy_nodes(&graph);
3399 let _new = insert_copies(&graph, &[y.id(), grad_x.id()]);
3400 let after_copies = count_copy_nodes(&graph);
3401
3402 // With everything on Vulkan, no Copies should be needed —
3403 // this verifies the pass doesn't spuriously insert Copies into
3404 // the backward graph when placements are consistent.
3405 assert_eq!(
3406 after_copies, before_copies,
3407 "insert_copies should leave a uniformly-Vulkan forward+backward graph alone"
3408 );
3409 }
3410
3411 #[test]
3412 fn insert_copies_backward_inherits_forward_device() {
3413 // Forward: y = sum(x * x) with NO explicit placement.
3414 // Compute backward. Then place JUST the forward root on Vulkan
3415 // and re-run insert_copies. The Copies that get inserted should
3416 // pull x to Vulkan; the backward path should follow suit when
3417 // we ask for both roots.
3418 let x = NodeHandle::from_f32(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[4]), cpu_dev())
3419 .unwrap();
3420 let sq = x.mul(&x);
3421 let y = sq.sum_all().on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3422 let graph = y.graph().clone();
3423
3424 let grads = y.backward();
3425 let grad_x = grads.get(&x).expect("dL/dx should exist");
3426
3427 // Before: only y is tagged. The backward graph has no tags.
3428 // After insert_copies([y, grad_x]): y pulls its inputs (sq)
3429 // toward Vulkan → sq pulls x → Copies inserted.
3430 // Backward inherits device from its inputs transitively.
3431 let new_roots = insert_copies(&graph, &[y.id(), grad_x.id()]);
3432 assert_eq!(new_roots.len(), 2);
3433 // At least one Copy should have been inserted (the unplaced
3434 // forward consts need to get to Vulkan).
3435 assert!(
3436 count_copy_nodes(&graph) > 0,
3437 "expected Copies to be inserted for unplaced Const inputs"
3438 );
3439 }
3440
3441 #[test]
3442 fn lower_const_placement_single_vulkan_consumer() {
3443 // Const a → Add(a, b) placed on Vulkan. lower_const_placement
3444 // should tag a with Vulkan since Add is its only consumer.
3445 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
3446 let b = a
3447 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
3448 .unwrap();
3449 let c = a.add(&b).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3450 let graph = c.graph().clone();
3451
3452 let lowered = lower_const_placement(&graph, &[c.id()]);
3453 assert_eq!(lowered, 2); // both a and b tagged
3454 assert_eq!(
3455 graph.read().unwrap().placement(a.id()),
3456 Some(DeviceLocation::Vulkan { gpu_id: 0 })
3457 );
3458 assert_eq!(
3459 graph.read().unwrap().placement(b.id()),
3460 Some(DeviceLocation::Vulkan { gpu_id: 0 })
3461 );
3462
3463 // After lowering, insert_copies should emit NO Copies (the
3464 // Consts are now on the target device).
3465 let before_copies = count_copy_nodes(&graph);
3466 insert_copies(&graph, &[c.id()]);
3467 assert_eq!(count_copy_nodes(&graph), before_copies);
3468 }
3469
3470 #[test]
3471 fn lower_const_placement_consumers_disagree_stays_unplaced() {
3472 // Const a flows into two consumers on different devices.
3473 // Without replication support, lowering has to leave a unplaced.
3474 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
3475 let b = a
3476 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
3477 .unwrap();
3478 let cpu_sum = a.add(&b).on_device(DeviceLocation::Cpu);
3479 let vulkan_sum = a.add(&b).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3480 let graph = a.graph().clone();
3481
3482 lower_const_placement(&graph, &[cpu_sum.id(), vulkan_sum.id()]);
3483 assert_eq!(
3484 graph.read().unwrap().placement(a.id()),
3485 None,
3486 "const with disagreeing consumers stays unplaced"
3487 );
3488 assert_eq!(graph.read().unwrap().placement(b.id()), None);
3489 }
3490
3491 #[test]
3492 fn lower_const_placement_skips_already_placed() {
3493 // An explicitly-placed Const should not be overridden.
3494 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev())
3495 .unwrap()
3496 .on_device(DeviceLocation::Cpu);
3497 let b = a
3498 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
3499 .unwrap();
3500 let c = a.add(&b).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3501 let graph = c.graph().clone();
3502
3503 lower_const_placement(&graph, &[c.id()]);
3504 // a keeps its explicit Cpu placement even though its consumer is Vulkan.
3505 assert_eq!(
3506 graph.read().unwrap().placement(a.id()),
3507 Some(DeviceLocation::Cpu)
3508 );
3509 // b had no hint; it gets lowered to Vulkan.
3510 assert_eq!(
3511 graph.read().unwrap().placement(b.id()),
3512 Some(DeviceLocation::Vulkan { gpu_id: 0 })
3513 );
3514 }
3515
3516 #[test]
3517 fn insert_copies_idempotent() {
3518 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
3519 let b = a.const_f32_like(vec![2.0], Shape::from_dims(&[1])).unwrap();
3520 let c = a.add(&b).on_device(DeviceLocation::Cpu);
3521 let graph = c.graph().clone();
3522
3523 let roots1 = insert_copies(&graph, &[c.id()]);
3524 let after_first = count_copy_nodes(&graph);
3525 let _roots2 = insert_copies(&graph, &roots1);
3526 assert_eq!(
3527 count_copy_nodes(&graph),
3528 after_first,
3529 "insert_copies should be idempotent on already-reconciled graphs"
3530 );
3531 }
3532
3533 #[test]
3534 fn cse_folds_identical_add() {
3535 let (graph, a) = make_scalar_graph();
3536 let b = a.add(&a);
3537 let c = a.add(&a);
3538 let pre_len = graph.read().unwrap().len();
3539 let new_roots = optimize(&graph, &[b.id(), c.id()]);
3540 assert_eq!(
3541 new_roots[0], new_roots[1],
3542 "CSE should map both to same node"
3543 );
3544 assert!(graph.read().unwrap().len() >= pre_len);
3545 }
3546
3547 #[test]
3548 fn cse_folds_commutative() {
3549 // Build two tensors inside the same graph so `a + b` and
3550 // `b + a` share NodeIds for the inputs. Use add_scalar on `a`
3551 // as a simple way to get a second tensor handle sharing a's graph.
3552 let (_graph, a) = make_scalar_graph();
3553 let b = a.add_scalar(5.0);
3554 let ab = a.add(&b);
3555 let ba = b.add(&a);
3556 let graph = a.graph().clone();
3557 let new_roots = optimize(&graph, &[ab.id(), ba.id()]);
3558 assert_eq!(
3559 new_roots[0], new_roots[1],
3560 "commutative CSE should fold a+b and b+a to one node"
3561 );
3562 }
3563
3564 /// GAP-271: `Maximum`/`Minimum` must NOT be folded across operand order.
3565 ///
3566 /// They are commutative in VALUE and not in BITS. `chassis/binary.rs`
3567 /// returns the FIRST NaN operand -- a documented lhs-first tie-break
3568 /// matching `torch.maximum` -- so two distinct NaN payloads swap with
3569 /// operand order: `max(0x7FC00001, 0x7FC00002)` is `0x7FC00001` and the
3570 /// reverse is `0x7FC00002`. Folding the two orderings is therefore an
3571 /// invalid rewrite.
3572 ///
3573 /// A +-0 FIXTURE WOULD BE UNSOUND HERE, and not because we canonicalise:
3574 /// the +-0 answer is decided PER CALL SITE by the optimizer (we delegate
3575 /// to `f32::max`, which disclaims the tie). One binary at opt-level 3
3576 /// gives three answers -- const-folded +0/+0, `black_box` -0/-0,
3577 /// `#[inline(never)]` -0/+0. A +-0 assertion would therefore be testing
3578 /// the optimizer, not us. The NaN tie-break is explicit in our source and
3579 /// is stable in all four contexts, which is why it is the fixture.
3580 #[test]
3581 fn cse_does_not_fold_minmax_across_operand_order() {
3582 let (_graph, a) = make_scalar_graph();
3583 let b = a.add_scalar(5.0);
3584
3585 // CONTROL, and it is load-bearing: `Add` IS commutative in bits, so it
3586 // must STILL fold. Without this arm, a change that broke CSE entirely
3587 // would pass the assertion below for the wrong reason.
3588 let add_ab = a.add(&b);
3589 let add_ba = b.add(&a);
3590 let graph = a.graph().clone();
3591 let add_roots = optimize(&graph, &[add_ab.id(), add_ba.id()]);
3592 assert_eq!(
3593 add_roots[0], add_roots[1],
3594 "control: Add is bitwise commutative and must still fold -- if this fails, CSE is broken generally and the Maximum arm below proves nothing"
3595 );
3596
3597 let max_ab = a.maximum(&b);
3598 let max_ba = b.maximum(&a);
3599 let max_roots = optimize(&graph, &[max_ab.id(), max_ba.id()]);
3600 assert_ne!(
3601 max_roots[0], max_roots[1],
3602 "max(a,b) and max(b,a) were folded to one node, but they differ in BITS on distinct NaN payloads (lhs-first tie-break). See GAP-271."
3603 );
3604
3605 let min_ab = a.minimum(&b);
3606 let min_ba = b.minimum(&a);
3607 let min_roots = optimize(&graph, &[min_ab.id(), min_ba.id()]);
3608 assert_ne!(
3609 min_roots[0], min_roots[1],
3610 "min(a,b) and min(b,a) were folded to one node -- same defect as Maximum, see GAP-271"
3611 );
3612 }
3613
3614 #[test]
3615 fn simplifies_add_scalar_zero() {
3616 let (graph, a) = make_scalar_graph();
3617 let b = a.add_scalar(0.0);
3618 let new_roots = optimize(&graph, &[b.id()]);
3619 assert_eq!(new_roots[0], a.id(), "AddScalar(0) should alias to input");
3620 }
3621
3622 #[test]
3623 fn simplifies_mul_scalar_one() {
3624 let (graph, a) = make_scalar_graph();
3625 let b = a.mul_scalar(1.0);
3626 let new_roots = optimize(&graph, &[b.id()]);
3627 assert_eq!(new_roots[0], a.id(), "MulScalar(1) should alias to input");
3628 }
3629
3630 #[test]
3631 fn simplifies_identity_cast() {
3632 let (graph, a) = make_scalar_graph();
3633 // Cast to the same dtype is a no-op; the optimizer aliases it away.
3634 // (Dispatch keys casts on [src, dst] and registers no [d, d] kernel,
3635 // so this elision is what removes a same-dtype cast before realize.)
3636 let same = a.cast(a.dtype());
3637 let new_roots = optimize(&graph, &[same.id()]);
3638 assert_eq!(
3639 new_roots[0],
3640 a.id(),
3641 "Cast(d) on a dtype-d input should alias to input",
3642 );
3643 }
3644
3645 /// GAP-183: `Cast(float -> Bool)` lowers to `Ne(x, x*0)` at the GRAPH level.
3646 ///
3647 /// WHY A LOWERING AND NOT A KERNEL: CUDA already ships the `!= 0` test —
3648 /// `ne_{f32,f64,f16,bf16}_u8` in `cuda/compare.fkc.md` — but those kernels are
3649 /// UNREACHABLE from a storage-level cast, which cannot compose graph ops. So
3650 /// the fix belongs here, not in the storage layer.
3651 ///
3652 /// BORN-RED: before the rewrite this root is an `Op::Cast(Bool)`.
3653 #[test]
3654 fn lowers_float_cast_to_bool_into_ne_against_zero() {
3655 let (graph, a) = make_scalar_graph(); // F32
3656 let as_bool = a.cast(fuel_ir::DType::Bool);
3657 let new_roots = optimize(&graph, &[as_bool.id()]);
3658 let g = graph.read().unwrap();
3659 let root = g.node(new_roots[0]);
3660 assert!(
3661 matches!(root.op, Op::Ne),
3662 "float -> Bool must lower to Op::Ne, got {:?}",
3663 root.op,
3664 );
3665 assert_eq!(
3666 root.dtype,
3667 fuel_ir::DType::Bool,
3668 "the lowered root still yields Bool"
3669 );
3670 // RHS is zeros from `MulScalar(0.0)` over the SAME input — not a
3671 // materialized const, so shape and dtype match by construction.
3672 let rhs = g.node(root.inputs[1]);
3673 assert!(
3674 matches!(rhs.op, Op::MulScalar(c) if c == 0.0),
3675 "rhs must be MulScalar(0.0) (shape-preserving zeros), got {:?}",
3676 rhs.op,
3677 );
3678 assert_eq!(
3679 rhs.inputs[0], root.inputs[0],
3680 "zeros must derive from the cast's own input",
3681 );
3682 }
3683
3684 /// GAP-183 companion: the INTEGER half is deliberately NOT lowered — there is
3685 /// no CUDA integer compare kernel, so rewriting would move the same decline
3686 /// one layer out while bypassing CPU's real int->Bool cast kernels.
3687 #[test]
3688 fn does_not_lower_integer_cast_to_bool() {
3689 let (graph, a) = make_scalar_graph();
3690 let as_u8 = a.cast(fuel_ir::DType::U8);
3691 let as_bool = as_u8.cast(fuel_ir::DType::Bool);
3692 let new_roots = optimize(&graph, &[as_bool.id()]);
3693 let g = graph.read().unwrap();
3694 let root = g.node(new_roots[0]);
3695 assert!(
3696 matches!(root.op, Op::Cast(fuel_ir::DType::Bool)),
3697 "int -> Bool stays an Op::Cast (genuine decline on CUDA), got {:?}",
3698 root.op,
3699 );
3700 }
3701
3702 #[test]
3703 fn keeps_real_cast() {
3704 let (graph, a) = make_scalar_graph();
3705 // A genuine dtype change (F32→F64) is NOT elided.
3706 let cast = a.cast(fuel_ir::DType::F64);
3707 let new_roots = optimize(&graph, &[cast.id()]);
3708 assert_ne!(
3709 new_roots[0],
3710 a.id(),
3711 "a real Cast must survive optimization"
3712 );
3713 }
3714
3715 #[test]
3716 fn declarative_pattern_matches_and_fuses_relu_add() {
3717 use crate::jit::{OpAttrs, OpTag, PatternNode};
3718 use crate::registry::{
3719 BackwardKind, FusedOpEntry, FusedOpFamily, FusedOpParams, FusedOps, PatternTree,
3720 SubgraphPattern,
3721 };
3722 fn shape_rule(s: &[Shape], _: &FusedOpParams) -> Shape {
3723 s[0].clone()
3724 }
3725 fn dtype_rule(d: &[DType], _: &FusedOpParams) -> DType {
3726 d[0]
3727 }
3728 fn no_decompose(_: &mut Graph, id: NodeId, _: &FusedOpParams) -> NodeId {
3729 id
3730 }
3731 // A declaratively-registered fused op for relu(add(a, b)).
3732 let entry = FusedOpEntry {
3733 destructive_input: None,
3734 id: FusedOps::SOFTMAX_LAST_DIM, // a real parameterless id (plumbing test)
3735 name: "test_declarative_relu_add",
3736 family: FusedOpFamily::Forward,
3737 pattern: SubgraphPattern::Declarative(PatternTree {
3738 root: PatternNode::Op {
3739 op: OpTag::Relu,
3740 attrs: OpAttrs::default(),
3741 operands: vec![PatternNode::Op {
3742 op: OpTag::Add,
3743 attrs: OpAttrs::default(),
3744 operands: vec![
3745 PatternNode::Bind { index: 0 },
3746 PatternNode::Bind { index: 1 },
3747 ],
3748 }],
3749 },
3750 params: FusedOpParams::SoftmaxLastDim,
3751 }),
3752 decompose: no_decompose,
3753 backward: BackwardKind::NotDifferentiable,
3754 shape_rule,
3755 dtype_rule,
3756 output_views: None,
3757 };
3758 let rule = FusionRule::from_entry(&entry);
3759
3760 // Build relu(add(a, b)).
3761 let mut g = Graph::new();
3762 let s = Shape::from_dims(&[2]);
3763 let f32 = DType::F32;
3764 let a = g.push(Node {
3765 op: Op::Const,
3766 inputs: vec![],
3767 shape: s.clone(),
3768 dtype: f32,
3769 });
3770 let b = g.push(Node {
3771 op: Op::Const,
3772 inputs: vec![],
3773 shape: s.clone(),
3774 dtype: f32,
3775 });
3776 let sum = g.push(Node {
3777 op: Op::Add,
3778 inputs: vec![a, b],
3779 shape: s.clone(),
3780 dtype: f32,
3781 });
3782 let r = g.push(Node {
3783 op: Op::Relu,
3784 inputs: vec![sum],
3785 shape: s.clone(),
3786 dtype: f32,
3787 });
3788
3789 // The declarative rule fires at the relu sink and fuses to Op::Fused.
3790 assert!(rule.matches(&g, r), "declarative pattern matches relu(add)");
3791 let mut remap = HashMap::new();
3792 rule.rewrite(&mut g, r, &mut remap);
3793 let fused_id = remap[&r];
3794 match &g.node(fused_id).op {
3795 Op::Fused(id, FusedOpParams::SoftmaxLastDim) => {
3796 assert_eq!(*id, FusedOps::SOFTMAX_LAST_DIM)
3797 }
3798 other => panic!("expected Op::Fused(SOFTMAX_LAST_DIM, _), got {other:?}"),
3799 }
3800 assert_eq!(
3801 g.node(fused_id).inputs,
3802 vec![a, b],
3803 "fused inputs = the region's bound external inputs",
3804 );
3805 }
3806
3807 #[test]
3808 fn runtime_op_fuses_and_round_trips_through_the_pass() {
3809 use crate::jit::{OpAttrs, OpTag, PatternNode};
3810 use crate::runtime_fused::register_runtime_fused;
3811 // A region no other test registers — tanh(sub(a, b)) — so the fuse is
3812 // deterministic (only our runtime rule matches it; sub is non-commutative).
3813 let region = PatternNode::Op {
3814 op: OpTag::Tanh,
3815 attrs: OpAttrs::default(),
3816 operands: vec![PatternNode::Op {
3817 op: OpTag::Sub,
3818 attrs: OpAttrs::default(),
3819 operands: vec![
3820 PatternNode::Bind { index: 0 },
3821 PatternNode::Bind { index: 1 },
3822 ],
3823 }],
3824 };
3825 let rid = register_runtime_fused("test::tanh_sub", region).unwrap();
3826
3827 // Build tanh(sub(a, b)) on primitives (b shares a's graph).
3828 let a = NodeHandle::from_f32(
3829 vec![0.5, -0.5, 1.0, -1.0],
3830 Shape::from_dims(&[4]),
3831 cpu_dev(),
3832 )
3833 .unwrap();
3834 let b = a
3835 .const_f32_like(vec![0.1, 0.2, 0.3, 0.4], Shape::from_dims(&[4]))
3836 .unwrap();
3837 let y = a.sub(&b).tanh();
3838 let graph = y.graph().clone();
3839
3840 // default_rules: lower (no-op here) then fuse — the runtime declarative
3841 // FusionRule folds tanh(sub) → Op::Fused(rid, Runtime).
3842 let fused = RuleRegistry::default_rules().optimize_to_fixpoint(&graph, &[y.id()]);
3843 {
3844 let g = graph.read().unwrap();
3845 match &g.node(fused[0]).op {
3846 Op::Fused(fid, FusedOpParams::Runtime { scalars }) => {
3847 assert_eq!(*fid, rid, "fused to our runtime op");
3848 assert!(fid.is_runtime());
3849 assert!(scalars.is_empty(), "parameterless region");
3850 }
3851 other => panic!("expected runtime Op::Fused, got {other:?}"),
3852 }
3853 }
3854
3855 // lowering_only: the kernel-absent path — decompose the runtime op back
3856 // to its region on primitives (tanh(sub(a, b))).
3857 let lowered = RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &fused);
3858 let g = graph.read().unwrap();
3859 assert!(
3860 matches!(g.node(lowered[0]).op, Op::Tanh),
3861 "re-emitted sink is Tanh"
3862 );
3863 let sub_id = g.node(lowered[0]).inputs[0];
3864 assert!(matches!(g.node(sub_id).op, Op::Sub), "Tanh's input is Sub");
3865 assert_eq!(
3866 g.node(sub_id).inputs.len(),
3867 2,
3868 "Sub over the two bound inputs"
3869 );
3870 }
3871
3872 #[test]
3873 fn capability_gate_blocks_fusion_without_a_kernel() {
3874 use crate::jit::{OpAttrs, OpTag, PatternNode};
3875 use crate::runtime_fused::register_runtime_fused;
3876 // Unique region — sigmoid(div(a, b)) — so the gate decision is ours alone.
3877 let region = PatternNode::Op {
3878 op: OpTag::Sigmoid,
3879 attrs: OpAttrs::default(),
3880 operands: vec![PatternNode::Op {
3881 op: OpTag::Div,
3882 attrs: OpAttrs::default(),
3883 operands: vec![
3884 PatternNode::Bind { index: 0 },
3885 PatternNode::Bind { index: 1 },
3886 ],
3887 }],
3888 };
3889 let rid = register_runtime_fused("test::sigmoid_div", region).unwrap();
3890
3891 let a = NodeHandle::from_f32(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[4]), cpu_dev())
3892 .unwrap();
3893 let b = a
3894 .const_f32_like(vec![2.0, 2.0, 2.0, 2.0], Shape::from_dims(&[4]))
3895 .unwrap();
3896 let y = a.div(&b).sigmoid();
3897 let graph = y.graph().clone();
3898
3899 // No kernel for our op → it is gated out of fusion (reported) and its
3900 // region stays primitive — the miss is caught at match time, not after.
3901 let (rules, gated_out) = RuleRegistry::capability_gated_rules(|id| id != rid);
3902 assert!(
3903 gated_out.contains(&rid),
3904 "kernel-absent op is reported as a miss candidate"
3905 );
3906 let roots = rules.optimize_to_fixpoint(&graph, &[y.id()]);
3907 {
3908 let g = graph.read().unwrap();
3909 assert!(
3910 matches!(g.node(roots[0]).op, Op::Sigmoid),
3911 "kernel-absent runtime op stays primitive (Sigmoid sink), never fuses",
3912 );
3913 }
3914
3915 // With a kernel available, the same op fuses.
3916 let (rules2, _) = RuleRegistry::capability_gated_rules(|_| true);
3917 let roots2 = rules2.optimize_to_fixpoint(&graph, &[roots[0]]);
3918 let g = graph.read().unwrap();
3919 assert!(
3920 matches!(g.node(roots2[0]).op, Op::Fused(fid, _) if fid == rid),
3921 "with a kernel, the runtime op fuses",
3922 );
3923 }
3924
3925 #[test]
3926 fn cse_does_not_fold_distinct_ops() {
3927 // Add and Mul on the same inputs are not equivalent.
3928 let (graph, a) = make_scalar_graph();
3929 let sum = a.add(&a);
3930 let prod = a.mul(&a);
3931 let new_roots = optimize(&graph, &[sum.id(), prod.id()]);
3932 assert_ne!(new_roots[0], new_roots[1], "Add and Mul must stay distinct");
3933 }
3934
3935 #[test]
3936 fn cse_does_not_fold_distinct_scalars() {
3937 let (graph, a) = make_scalar_graph();
3938 let b = a.add_scalar(1.0);
3939 let c = a.add_scalar(2.0);
3940 let new_roots = optimize(&graph, &[b.id(), c.id()]);
3941 assert_ne!(
3942 new_roots[0], new_roots[1],
3943 "AddScalar with different c must stay distinct"
3944 );
3945 }
3946
3947 #[test]
3948 fn cse_nested_chain_deduplicates() {
3949 // (a + a) + a appearing twice should dedupe both subexpressions.
3950 let (graph, a) = make_scalar_graph();
3951 let p1 = a.add(&a);
3952 let p2 = a.add(&a); // duplicates p1
3953 let q1 = p1.add(&a);
3954 let q2 = p2.add(&a); // structurally identical to q1 via CSE
3955 let new_roots = optimize(&graph, &[q1.id(), q2.id()]);
3956 assert_eq!(new_roots[0], new_roots[1], "nested duplicates must fold");
3957 }
3958
3959 // ---- derive_ordering + execution_plan -----------------------------------
3960
3961 #[test]
3962 fn derive_ordering_empty_for_non_destructive_graph() {
3963 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
3964 let b = a
3965 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
3966 .unwrap();
3967 let c = a.add(&b);
3968 let ord = derive_ordering(&c.graph().read().unwrap(), &[c.id()]);
3969 assert!(
3970 ord.is_empty(),
3971 "graph without destructive ops → no ordering edges"
3972 );
3973 }
3974
3975 #[test]
3976 fn derive_ordering_release_must_run_after_sibling_readers() {
3977 // Graph:
3978 // a (producer)
3979 // b = relu(a) (non-destructive reader of a)
3980 // r = release(a) (destructive reader of a)
3981 // Expected ordering: r must run after b.
3982 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
3983 let b = a.relu();
3984 let r = a.release();
3985 let ord = derive_ordering(&a.graph().read().unwrap(), &[b.id(), r.id()]);
3986 let deps = ord.deps_of(r.id());
3987 assert_eq!(
3988 deps.len(),
3989 1,
3990 "release should have one ordering dep (the relu)"
3991 );
3992 assert_eq!(deps[0], b.id(), "release must run after relu");
3993 }
3994
3995 #[test]
3996 fn derive_ordering_follows_view_chains_for_destructive_op() {
3997 // Phase 4a of in-place ops infrastructure: a destructive op
3998 // on `x` must run after any reader of any view-of-x, because
3999 // views share `x`'s Storage Arc at realize time. Without the
4000 // alias-set walk in derive_ordering, this case would not pin
4001 // `reader(view)` before `destructive(x)`.
4002 //
4003 // Graph:
4004 // x (producer; rank-2)
4005 // v = x.transpose() (view of x)
4006 // z = v.relu() (reader of v, transitively reads x's bytes)
4007 // r = x.release() (destructive on x)
4008 // Expected: r must run after z (not just after v).
4009 let x = NodeHandle::from_f32(
4010 vec![1.0_f32, 2.0, 3.0, 4.0],
4011 Shape::from_dims(&[2, 2]),
4012 cpu_dev(),
4013 )
4014 .unwrap();
4015 let v = x.transpose();
4016 let z = v.relu();
4017 let r = x.release();
4018 let ord = derive_ordering(&x.graph().read().unwrap(), &[z.id(), r.id()]);
4019 let deps = ord.deps_of(r.id());
4020 assert!(
4021 deps.contains(&z.id()),
4022 "release(x) must be pinned after relu(transpose(x)) (view-aware alias set); got deps = {deps:?}",
4023 );
4024 }
4025
4026 #[test]
4027 fn derive_ordering_inplace_unary_through_view_chain() {
4028 // Specifically for the in-place ops Phase 4 use case:
4029 // `y = x.transpose(); z = y.relu(); x.relu_inplace()` —
4030 // ReluInplace must be pinned after the read through the
4031 // transpose view chain.
4032 let x = NodeHandle::from_f32(
4033 vec![-1.0_f32, 2.0, -3.0, 4.0],
4034 Shape::from_dims(&[2, 2]),
4035 cpu_dev(),
4036 )
4037 .unwrap();
4038 let y = x.transpose();
4039 let z = y.relu();
4040 // Capture x's shape + dtype + id BEFORE acquiring the write
4041 // lock — otherwise the args evaluate inside the locked region
4042 // and self-deadlock (RwLock doesn't grant a read lock to the
4043 // writer-holding thread).
4044 let x_shape = x.shape();
4045 let x_dtype = x.dtype();
4046 let x_id = x.id();
4047 let inplace_id = x.graph().write().unwrap().push(crate::Node {
4048 op: crate::Op::ReluInplace,
4049 inputs: vec![x_id],
4050 shape: x_shape,
4051 dtype: x_dtype,
4052 });
4053 let ord = derive_ordering(&x.graph().read().unwrap(), &[z.id(), inplace_id]);
4054 let deps = ord.deps_of(inplace_id);
4055 assert!(
4056 deps.contains(&z.id()),
4057 "ReluInplace(x) must be pinned after Relu(Transpose(x)) via view-aware alias set; got deps = {deps:?}",
4058 );
4059 }
4060
4061 // ---- Ordering-defect repros (MLA decode multi-round WriteSlice) ----
4062
4063 /// Control: a single-hop `Slice` reader of a `WriteSlice`
4064 /// destination is already correctly pinned before a SECOND
4065 /// `WriteSlice` that reuses the same destination —
4066 /// `collect_alias_set` finds the `Slice` via `is_view_op`, and its
4067 /// reader (`relu`) is not itself an alias member, so
4068 /// `derive_ordering` pins the second `WriteSlice` after it
4069 /// directly. Baseline for the Reshape-gap test below (confirms the
4070 /// gap is Reshape-specific, not a general multi-round WriteSlice
4071 /// failure).
4072 #[test]
4073 fn derive_ordering_write_slice_round2_plain_slice_reader_pinned() {
4074 let dest =
4075 NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
4076 let src1 = dest
4077 .const_f32_like(vec![1.0_f32, 2.0], Shape::from_dims(&[2]))
4078 .unwrap();
4079 let src2 = dest
4080 .const_f32_like(vec![9.0_f32, 8.0], Shape::from_dims(&[2]))
4081 .unwrap();
4082 let x = dest
4083 .write_slice(&src1, vec![(0, 2)])
4084 .expect("write_slice round 1");
4085 let s = x.slice(0, 0, 2);
4086 let k = s.relu();
4087 let y = x
4088 .write_slice(&src2, vec![(0, 2)])
4089 .expect("write_slice round 2");
4090 let ord = derive_ordering(&x.graph().read().unwrap(), &[k.id(), y.id()]);
4091 let deps = ord.deps_of(y.id());
4092 assert!(
4093 deps.contains(&k.id()),
4094 "round-2 write_slice must be pinned after the round-1 slice's \
4095 reader; got deps = {deps:?}",
4096 );
4097 }
4098
4099 /// CRITICAL SUSPECT #2 (MLA decode multi-round `WriteSlice`
4100 /// ordering defect): same shape as the control above, but the
4101 /// `Slice`'s reader is behind an `Op::Reshape` hop first.
4102 /// `Op::Reshape` is NOT in `collect_alias_set`'s alias-extending
4103 /// predicate (only `Op::is_view_op` + `Op::View`) even though its
4104 /// `WorkItemKind::ContiguizeOf` execution zero-copy ADOPTS the
4105 /// input's Storage Arc whenever the input is contiguous at offset
4106 /// 0 (`fuel-dispatch/src/pipelined.rs`'s `ContiguizeOf` arm) — so
4107 /// the alias walk stops at the `Slice`, and the Reshape's own
4108 /// consumer (`relu`) is never scanned for pinning against the
4109 /// round-2 `WriteSlice`. Born-red: fails before the fix (Reshape
4110 /// missing from the alias-extending set), green after.
4111 #[test]
4112 fn derive_ordering_write_slice_round2_reshape_reader_pinned() {
4113 let dest =
4114 NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
4115 let src1 = dest
4116 .const_f32_like(vec![1.0_f32, 2.0], Shape::from_dims(&[2]))
4117 .unwrap();
4118 let src2 = dest
4119 .const_f32_like(vec![9.0_f32, 8.0], Shape::from_dims(&[2]))
4120 .unwrap();
4121 let x = dest
4122 .write_slice(&src1, vec![(0, 2)])
4123 .expect("write_slice round 1");
4124 let s = x.slice(0, 0, 2);
4125 let r = s.reshape(Shape::from_dims(&[2]));
4126 let k = r.relu();
4127 let y = x
4128 .write_slice(&src2, vec![(0, 2)])
4129 .expect("write_slice round 2");
4130 let ord = derive_ordering(&x.graph().read().unwrap(), &[k.id(), y.id()]);
4131 let deps = ord.deps_of(y.id());
4132 assert!(
4133 deps.contains(&k.id()),
4134 "round-2 write_slice must be pinned after the reshape-adopted-arc \
4135 reader (CRITICAL SUSPECT #2 gap — Reshape excluded from \
4136 collect_alias_set's alias-extending predicate); got deps = {deps:?}",
4137 );
4138 }
4139
4140 // ---- Phase 5: insert_safety_copies ----
4141
4142 #[test]
4143 fn insert_safety_copies_residual_connection_breaks_cycle() {
4144 // Canonical residual pattern: `y = x.relu_inplace(); z = y + x`.
4145 // Before Phase 5: derive_ordering pins ReluInplace after Add
4146 // (Add reads x), but data flow pins Add after ReluInplace (Add
4147 // reads y, y depends on ReluInplace) → cycle. After Phase 5:
4148 // a Copy(x) → x_safe is inserted and Add's x input rewires to
4149 // x_safe.
4150 let x = NodeHandle::from_f32(
4151 vec![1.0_f32, -2.0, 3.0, -4.0],
4152 Shape::from_dims(&[4]),
4153 cpu_dev(),
4154 )
4155 .unwrap();
4156 let x_shape = x.shape();
4157 let x_dtype = x.dtype();
4158 let x_id = x.id();
4159
4160 // Manually build: y = ReluInplace(x); z = Add(y, x).
4161 let (y_id, z_id) = {
4162 let mut g = x.graph().write().unwrap();
4163 let y_id = g.push(crate::Node {
4164 op: crate::Op::ReluInplace,
4165 inputs: vec![x_id],
4166 shape: x_shape.clone(),
4167 dtype: x_dtype,
4168 });
4169 let z_id = g.push(crate::Node {
4170 op: crate::Op::Add,
4171 inputs: vec![y_id, x_id],
4172 shape: x_shape,
4173 dtype: x_dtype,
4174 });
4175 (y_id, z_id)
4176 };
4177
4178 // Before the pass: cycle would exist. Run insert_safety_copies.
4179 let inserted = insert_safety_copies(&mut x.graph().write().unwrap(), &[z_id]);
4180 assert_eq!(inserted, 1, "should insert exactly one safety copy");
4181
4182 // Verify Add's inputs were rewired: still [y_id, <something>],
4183 // but the second input is NOT x_id anymore — it's the new
4184 // Op::Copy node.
4185 let copy_id = {
4186 let g = x.graph().read().unwrap();
4187 let z_node = g.node(z_id);
4188 assert_eq!(z_node.inputs.len(), 2, "Add still has 2 inputs");
4189 assert_eq!(z_node.inputs[0], y_id, "Add's y input unchanged");
4190 assert_ne!(z_node.inputs[1], x_id, "Add's x input was rewired");
4191 let copy_node_id = z_node.inputs[1];
4192 let copy_node = g.node(copy_node_id);
4193 assert!(
4194 matches!(copy_node.op, crate::Op::Copy { .. }),
4195 "rewired input is Op::Copy; got {:?}",
4196 copy_node.op
4197 );
4198 assert_eq!(copy_node.inputs, vec![x_id], "Op::Copy reads x");
4199 copy_node_id
4200 };
4201
4202 // Verify execution_plan succeeds (no cycle).
4203 let plan = execution_plan(&x.graph().read().unwrap(), &[z_id]);
4204 // Plan must contain x, the copy, ReluInplace, and Add.
4205 // The copy must come before ReluInplace (it's a reader of x).
4206 let pos: HashMap<NodeId, usize> = plan.iter().enumerate().map(|(i, n)| (*n, i)).collect();
4207 let copy_pos = pos[©_id];
4208 let inplace_pos = pos[&y_id];
4209 assert!(
4210 copy_pos < inplace_pos,
4211 "Copy must run before ReluInplace; copy={copy_pos} inplace={inplace_pos}"
4212 );
4213 }
4214
4215 /// CapturedRun executor build-out (4b-ζ follow-up): when a graph has
4216 /// `target_backend` stamped (ordinary single-device `optimize_graph`
4217 /// output — the common case) but no explicit `placement` (a rarely-
4218 /// used pin), the inserted safety copy's `target_location` must be
4219 /// derived from `target_backend`, NOT default straight to `Cpu`. A
4220 /// same-device CUDA safety snapshot silently landing on `Cpu` strands
4221 /// its (unrelated) reader off-device — and, in a CUDA decode graph
4222 /// bound for `capture_decode`, turns an ordinary same-device
4223 /// snapshot into a genuinely-cross-device D2H that capture must
4224 /// reject (capture only ever accepts a same-device CUDA `Op::Copy`).
4225 /// Born-red without the `target_backend` fallback (old code:
4226 /// `.unwrap_or(DeviceLocation::Cpu)` fires immediately since
4227 /// `placement` is never populated here); green with it.
4228 #[test]
4229 fn insert_safety_copies_derives_target_location_from_target_backend_when_unplaced() {
4230 // Same residual shape as `insert_safety_copies_residual_connection_breaks_cycle`
4231 // (`y = x.relu_inplace(); z = y + x`), but every node is stamped
4232 // `target_backend = Cuda` (the ordinary optimize_graph output for a
4233 // single-device CUDA decode graph) and NO node has an explicit
4234 // `placement` — the realistic shape of a real Llama decode graph.
4235 let x = NodeHandle::from_f32(
4236 vec![1.0_f32, -2.0, 3.0, -4.0],
4237 Shape::from_dims(&[4]),
4238 cpu_dev(),
4239 )
4240 .unwrap();
4241 let x_shape = x.shape();
4242 let x_dtype = x.dtype();
4243 let x_id = x.id();
4244
4245 let (_y_id, z_id) = {
4246 let mut g = x.graph().write().unwrap();
4247 let y_id = g.push(crate::Node {
4248 op: crate::Op::ReluInplace,
4249 inputs: vec![x_id],
4250 shape: x_shape.clone(),
4251 dtype: x_dtype,
4252 });
4253 let z_id = g.push(crate::Node {
4254 op: crate::Op::Add,
4255 inputs: vec![y_id, x_id],
4256 shape: x_shape,
4257 dtype: x_dtype,
4258 });
4259 g.set_target_backend(y_id, fuel_ir::probe::BackendId::Cuda);
4260 g.set_target_backend(z_id, fuel_ir::probe::BackendId::Cuda);
4261 (y_id, z_id)
4262 };
4263 assert!(
4264 x.graph().read().unwrap().placement(x_id).is_none(),
4265 "precondition: x has no explicit placement",
4266 );
4267
4268 let inserted = insert_safety_copies(&mut x.graph().write().unwrap(), &[z_id]);
4269 assert_eq!(inserted, 1, "should insert exactly one safety copy");
4270
4271 let g = x.graph().read().unwrap();
4272 let z_node = g.node(z_id);
4273 let copy_id = z_node.inputs[1];
4274 let copy_node = g.node(copy_id);
4275 assert_eq!(
4276 copy_node.op,
4277 crate::Op::Copy {
4278 target: DeviceLocation::Cuda { gpu_id: 0 }
4279 },
4280 "same-device CUDA safety copy must target Cuda (derived from \
4281 target_backend), NOT fall back to Cpu when placement is unset",
4282 );
4283 }
4284
4285 #[test]
4286 fn insert_safety_copies_noop_when_no_destructive_conflicts() {
4287 // Pure functional graph — no in-place ops. The pass should
4288 // insert zero copies.
4289 let x = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
4290 let y = x.relu();
4291 let z = y.sum_all();
4292 let inserted = insert_safety_copies(&mut x.graph().write().unwrap(), &[z.id()]);
4293 assert_eq!(inserted, 0);
4294 }
4295
4296 #[test]
4297 fn insert_safety_copies_noop_when_inplace_target_only_consumed_via_alias_path() {
4298 // `y = x.relu_inplace(); loss = y.sum_all()` — the only
4299 // downstream consumer of x reads it through y (the in-place
4300 // node), not x directly. derive_ordering pins ReluInplace
4301 // after... only ReluInplace itself (no other readers of x).
4302 // No conflict, no copy needed.
4303 let x =
4304 NodeHandle::from_f32(vec![1.0_f32, -1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
4305 let x_shape = x.shape();
4306 let x_dtype = x.dtype();
4307 let x_id = x.id();
4308 let y_id = x.graph().write().unwrap().push(crate::Node {
4309 op: crate::Op::ReluInplace,
4310 inputs: vec![x_id],
4311 shape: x_shape,
4312 dtype: x_dtype,
4313 });
4314 // Build a chain that only reads y (not x).
4315 let inserted = insert_safety_copies(&mut x.graph().write().unwrap(), &[y_id]);
4316 assert_eq!(inserted, 0);
4317 }
4318
4319 /// Regression for the 2026-06-11 live-GPU failure: a reader with
4320 /// NO dependency relationship to a destructive `Op::Move` must
4321 /// not get a safety copy just because DFS visit order happened to
4322 /// place it after the Move.
4323 ///
4324 /// Graph: `a; b = relu(a); m = move(a)`. derive_ordering pins
4325 /// `m` after `b` (reader-before-mutator), so every execution_plan
4326 /// runs `b` before `m`'s release — no copy is needed in EITHER
4327 /// roots order. The old positional predicate inserted a spurious
4328 /// copy when roots ordering made `b` land after `m` in
4329 /// `topo_order_multi` (which visits the LAST root's subtree
4330 /// first), and that copy then inherited the Move's device.
4331 #[test]
4332 fn insert_safety_copies_no_spurious_copy_for_independent_reader_of_move() {
4333 for flip_roots in [false, true] {
4334 let a = NodeHandle::from_f32(vec![1.0_f32, -2.0], Shape::from_dims(&[2]), cpu_dev())
4335 .unwrap();
4336 let b = a.relu();
4337 let a_shape = a.shape();
4338 let a_dtype = a.dtype();
4339 let a_id = a.id();
4340 let m_id = a.graph().write().unwrap().push(crate::Node {
4341 op: crate::Op::Move {
4342 target: DeviceLocation::Cpu,
4343 },
4344 inputs: vec![a_id],
4345 shape: a_shape,
4346 dtype: a_dtype,
4347 });
4348 let roots = if flip_roots {
4349 [m_id, b.id()]
4350 } else {
4351 [b.id(), m_id]
4352 };
4353 // Sanity: in the `[b, m]` roots order, DFS visits m's
4354 // subtree first, so b lands positionally AFTER the Move —
4355 // the exact shape the old predicate misclassified.
4356 let inserted = insert_safety_copies(&mut a.graph().write().unwrap(), &roots);
4357 assert_eq!(
4358 inserted, 0,
4359 "relu(a) is pinned before move(a) by derive_ordering; \
4360 no copy regardless of roots order (flip_roots={flip_roots})",
4361 );
4362 let g = a.graph().read().unwrap();
4363 assert_eq!(
4364 g.node(b.id()).inputs,
4365 vec![a_id],
4366 "reader must keep reading `a` directly",
4367 );
4368 drop(g);
4369 // The plan must still order the reader before the Move.
4370 let plan = execution_plan(&a.graph().read().unwrap(), &roots);
4371 let b_pos = plan.iter().position(|&n| n == b.id()).unwrap();
4372 let m_pos = plan.iter().position(|&n| n == m_id).unwrap();
4373 assert!(b_pos < m_pos, "relu must precede move: {plan:?}");
4374 }
4375 }
4376
4377 /// A reader that TRANSITIVELY depends on the destructive op (not
4378 /// just via a direct input) still conflicts: the pin edge would
4379 /// close a cycle through the intermediate node. The
4380 /// dependency-based predicate must use reachability, not direct
4381 /// input inspection.
4382 ///
4383 /// Graph: `y = relu_inplace(x); w = relu(y); z = add(w, x)`.
4384 #[test]
4385 fn insert_safety_copies_transitive_descendant_reader_gets_copy() {
4386 let x = NodeHandle::from_f32(
4387 vec![1.0_f32, -2.0, 3.0, -4.0],
4388 Shape::from_dims(&[4]),
4389 cpu_dev(),
4390 )
4391 .unwrap();
4392 let x_shape = x.shape();
4393 let x_dtype = x.dtype();
4394 let x_id = x.id();
4395 let (y_id, z_id) = {
4396 let mut g = x.graph().write().unwrap();
4397 let y_id = g.push(crate::Node {
4398 op: crate::Op::ReluInplace,
4399 inputs: vec![x_id],
4400 shape: x_shape.clone(),
4401 dtype: x_dtype,
4402 });
4403 let w_id = g.push(crate::Node {
4404 op: crate::Op::Relu,
4405 inputs: vec![y_id],
4406 shape: x_shape.clone(),
4407 dtype: x_dtype,
4408 });
4409 let z_id = g.push(crate::Node {
4410 op: crate::Op::Add,
4411 inputs: vec![w_id, x_id],
4412 shape: x_shape,
4413 dtype: x_dtype,
4414 });
4415 (y_id, z_id)
4416 };
4417 let inserted = insert_safety_copies(&mut x.graph().write().unwrap(), &[z_id]);
4418 assert_eq!(inserted, 1, "transitive residual cycle needs one copy");
4419 let g = x.graph().read().unwrap();
4420 let z_node = g.node(z_id);
4421 assert_ne!(z_node.inputs[1], x_id, "z's x input must be rewired");
4422 assert!(matches!(
4423 g.node(z_node.inputs[1]).op,
4424 crate::Op::Copy { .. }
4425 ));
4426 drop(g);
4427 let plan = execution_plan(&x.graph().read().unwrap(), &[z_id]);
4428 assert!(plan.contains(&y_id), "plan still contains the in-place op");
4429 }
4430
4431 /// A genuinely-parallel reader — no ordering guarantee in either
4432 /// direction — keeps its safety copy (conservative default).
4433 ///
4434 /// The only readers derive_ordering does NOT pin before the
4435 /// mutator are alias-set members (view ops of the target). A view
4436 /// with consumers is transitively forced before the mutator via
4437 /// its pinned consumers; a view that is itself a realize root has
4438 /// no ordering guarantee at all. Safety cannot be proven, so the
4439 /// pass must copy. Note the old positional predicate got this
4440 /// case WRONG in the `[m, v]` roots order (v lands positionally
4441 /// before m → no copy; only the plan's stable tiebreak saved it).
4442 #[test]
4443 fn insert_safety_copies_parallel_view_root_reader_keeps_copy() {
4444 let x = NodeHandle::from_f32(
4445 vec![1.0_f32, 2.0, 3.0, 4.0],
4446 Shape::from_dims(&[2, 2]),
4447 cpu_dev(),
4448 )
4449 .unwrap();
4450 let v = x.transpose();
4451 let x_shape = x.shape();
4452 let x_dtype = x.dtype();
4453 let x_id = x.id();
4454 let m_id = x.graph().write().unwrap().push(crate::Node {
4455 op: crate::Op::Move {
4456 target: DeviceLocation::Cpu,
4457 },
4458 inputs: vec![x_id],
4459 shape: x_shape,
4460 dtype: x_dtype,
4461 });
4462 // Roots [m, v]: DFS visits v's subtree first, so v sits
4463 // positionally BEFORE the Move — the shape the positional
4464 // predicate silently skipped.
4465 let inserted = insert_safety_copies(&mut x.graph().write().unwrap(), &[m_id, v.id()]);
4466 assert_eq!(
4467 inserted, 1,
4468 "unpinned view-root reader has no ordering guarantee → copy",
4469 );
4470 let g = x.graph().read().unwrap();
4471 let v_node = g.node(v.id());
4472 assert_ne!(
4473 v_node.inputs[0], x_id,
4474 "view must be rewired to the snapshot"
4475 );
4476 assert!(matches!(
4477 g.node(v_node.inputs[0]).op,
4478 crate::Op::Copy { .. }
4479 ));
4480 }
4481
4482 /// Cycles through ANOTHER destructive op's ordering edge are
4483 /// still conflicts — the predicate must walk the combined
4484 /// (data + ordering) graph, not just data edges.
4485 ///
4486 /// Graph:
4487 /// m1 = move(t1); m2 = move(t2)
4488 /// x = add(m1, t2) (pin x→m2; data m1→x)
4489 /// r = add(m2, t1) (pin r→m1; data m2→r)
4490 /// Combined cycle: m1 → x → m2 → r → m1. Neither x nor r is a
4491 /// pure-data descendant of the op whose target it reads, yet
4492 /// both pins are unsatisfiable. Both need copies; afterwards
4493 /// execution_plan must succeed.
4494 #[test]
4495 fn insert_safety_copies_breaks_cycle_through_other_ordering_edges() {
4496 let t1 =
4497 NodeHandle::from_f32(vec![1.0_f32, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
4498 let t2 = t1
4499 .const_f32_like(vec![3.0_f32, 4.0], Shape::from_dims(&[2]))
4500 .unwrap();
4501 let shape = t1.shape();
4502 let dtype = t1.dtype();
4503 let (t1_id, t2_id) = (t1.id(), t2.id());
4504 let (x_id, r_id) = {
4505 let mut g = t1.graph().write().unwrap();
4506 let m1 = g.push(crate::Node {
4507 op: crate::Op::Move {
4508 target: DeviceLocation::Cpu,
4509 },
4510 inputs: vec![t1_id],
4511 shape: shape.clone(),
4512 dtype,
4513 });
4514 let m2 = g.push(crate::Node {
4515 op: crate::Op::Move {
4516 target: DeviceLocation::Cpu,
4517 },
4518 inputs: vec![t2_id],
4519 shape: shape.clone(),
4520 dtype,
4521 });
4522 let x = g.push(crate::Node {
4523 op: crate::Op::Add,
4524 inputs: vec![m1, t2_id],
4525 shape: shape.clone(),
4526 dtype,
4527 });
4528 let r = g.push(crate::Node {
4529 op: crate::Op::Add,
4530 inputs: vec![m2, t1_id],
4531 shape,
4532 dtype,
4533 });
4534 (x, r)
4535 };
4536 let inserted = insert_safety_copies(&mut t1.graph().write().unwrap(), &[x_id, r_id]);
4537 assert_eq!(inserted, 2, "both cross-readers sit on the combined cycle");
4538 // The rewritten graph must be plannable (no cycle panic).
4539 let plan = execution_plan(&t1.graph().read().unwrap(), &[x_id, r_id]);
4540 assert!(plan.contains(&x_id) && plan.contains(&r_id));
4541 }
4542
4543 /// Idempotence under the dependency-based predicate: a second run
4544 /// sees the inserted Copy as a pinned, acyclic reader of the
4545 /// target and inserts nothing new.
4546 #[test]
4547 fn insert_safety_copies_idempotent_after_rewrite() {
4548 let x =
4549 NodeHandle::from_f32(vec![1.0_f32, -2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
4550 let x_shape = x.shape();
4551 let x_dtype = x.dtype();
4552 let x_id = x.id();
4553 let z_id = {
4554 let mut g = x.graph().write().unwrap();
4555 let y_id = g.push(crate::Node {
4556 op: crate::Op::ReluInplace,
4557 inputs: vec![x_id],
4558 shape: x_shape.clone(),
4559 dtype: x_dtype,
4560 });
4561 g.push(crate::Node {
4562 op: crate::Op::Add,
4563 inputs: vec![y_id, x_id],
4564 shape: x_shape,
4565 dtype: x_dtype,
4566 })
4567 };
4568 let first = insert_safety_copies(&mut x.graph().write().unwrap(), &[z_id]);
4569 assert_eq!(first, 1);
4570 let second = insert_safety_copies(&mut x.graph().write().unwrap(), &[z_id]);
4571 assert_eq!(second, 0, "second run must be a no-op");
4572 }
4573
4574 /// Performance regression: a destructive op whose target has NO other
4575 /// reader is the COMMON case in a real decode graph (KV-cache writes,
4576 /// release markers). Two INDEPENDENT quadratic costs used to fire on
4577 /// every one of the `N` destructive ops regardless: (1)
4578 /// `insert_safety_copies`' own pair of `reach()` graph walks plus an
4579 /// `order.len()`-sized linear readers-scan, and (2) `derive_ordering`'s
4580 /// `collect_alias_set` (now `alias_groups`), which re-walked the ENTIRE
4581 /// `order` per destructive op to find alias members. `N` independent
4582 /// 2-node chains (a `Const` leaf read ONLY by its own `ReluInplace`)
4583 /// make BOTH scale as `N * order.len()` under the old code. Measured on
4584 /// this box: unpatched (both costs present), `N=4000` took 18.2s;
4585 /// patched (both fixed — the `succ`-map pre-check here, plus
4586 /// `alias_groups`' single O(order.len()) pass shared across every
4587 /// destructive op instead of one pass each), `N=4000` takes ~62ms —
4588 /// a ~294x improvement. The bound below is generous in the PATCHED
4589 /// direction (keeps the test fast and non-flaky under shared-box
4590 /// contention) while still being far below what either quadratic old
4591 /// path could ever hit at this `N` — born red reverting either fix.
4592 #[test]
4593 fn insert_safety_copies_skips_reach_when_target_has_no_other_reader() {
4594 const N: usize = 4000;
4595 let shape = Shape::from_dims(&[4]);
4596 let mut g = crate::Graph::new();
4597 let mut roots: Vec<NodeId> = Vec::with_capacity(N);
4598 for _ in 0..N {
4599 let leaf = g.push(crate::Node {
4600 op: crate::Op::Const,
4601 inputs: vec![],
4602 shape: shape.clone(),
4603 dtype: DType::F32,
4604 });
4605 let relu = g.push(crate::Node {
4606 op: crate::Op::ReluInplace,
4607 inputs: vec![leaf],
4608 shape: shape.clone(),
4609 dtype: DType::F32,
4610 });
4611 roots.push(relu);
4612 }
4613
4614 let start = std::time::Instant::now();
4615 let inserted = insert_safety_copies(&mut g, &roots);
4616 let elapsed = start.elapsed();
4617
4618 assert_eq!(
4619 inserted, 0,
4620 "no leaf has a reader besides its own ReluInplace; nothing to copy"
4621 );
4622 assert!(
4623 elapsed < std::time::Duration::from_millis(500),
4624 "insert_safety_copies({N} independent no-reader chains) took {elapsed:?} — \
4625 the no-other-reader pre-check should make this O(N), not O(N^2)"
4626 );
4627 }
4628
4629 // ===== Differential safety-analysis harness (docs/design/incremental-consumer-index.md
4630 // §4 step 1) =====
4631 //
4632 // Step 1 of the staged redesign plan: build the comparison machinery and a
4633 // corpus of representative graphs BEFORE any new incremental-index
4634 // production code exists (that's step 2). The "new" side below calls the
4635 // SAME old pass on an INDEPENDENTLY-constructed graph instance (not a
4636 // clone of the old one -- `Graph` deliberately isn't `Clone`, and this
4637 // harness doesn't need it to be: it never touches production code to get
4638 // there). That makes today's differential assertion validate the thing
4639 // step 1 actually needs validated — the comparison logic itself, and that
4640 // every corpus factory is deterministic (same NodeId assignments on every
4641 // call, since NodeId is push-order, not globally counted) — ready for
4642 // step 2 to swap `run_new_safety_analysis` for the real incremental index
4643 // without touching this file again.
4644 //
4645 // NOT done here (tracked, not silently skipped): the design doc's step 1
4646 // also calls for the live decode harness's ACTUAL graph in the corpus.
4647 // That needs a graph-capture hook in the live CUDA harness; out of scope
4648 // for this PR, which is corpus-of-unit-test-shapes + harness plumbing
4649 // only. Also not done: porting ALL nine existing insert_safety_copies/
4650 // derive_ordering tests into the corpus (design doc open item #2) — five
4651 // representative shapes are ported below; full porting is tracked for
4652 // the step-4 PR (view/alias resolution), where open item #2 is due.
4653
4654 /// One differential-corpus entry: builds a FRESH graph + its realize
4655 /// roots. Called twice per comparison (once per side) rather than
4656 /// cloned, so the harness never needs `Graph: Clone`.
4657 type SafetyCorpusFactory = fn() -> (SharedGraph, Vec<NodeId>);
4658
4659 /// A snapshotted, comparable view of "what insert_safety_copies (which
4660 /// internally calls derive_ordering) did to this graph" — the
4661 /// observable contract the differential test checks. `nodes` compares
4662 /// the WHOLE resulting graph structurally (op + inputs, Debug-formatted
4663 /// since `Op` has no blanket `PartialEq`) rather than just the inserted
4664 /// count, so a divergence that inserts the SAME NUMBER of copies in a
4665 /// DIFFERENT place is still caught.
4666 #[derive(Debug, PartialEq)]
4667 struct SafetyAnalysisResult {
4668 inserted: usize,
4669 node_count: usize,
4670 nodes: Vec<(String, Vec<NodeId>)>,
4671 }
4672
4673 fn run_old_safety_analysis(graph: &SharedGraph, roots: &[NodeId]) -> SafetyAnalysisResult {
4674 let inserted = insert_safety_copies(&mut graph.write().unwrap(), roots);
4675 let g = graph.read().unwrap();
4676 let nodes = (0..g.len())
4677 .map(|i| {
4678 let n = g.node(NodeId(i));
4679 (format!("{:?}", n.op), n.inputs.clone())
4680 })
4681 .collect();
4682 SafetyAnalysisResult {
4683 inserted,
4684 node_count: g.len(),
4685 nodes,
4686 }
4687 }
4688
4689 /// STEP 1 PLACEHOLDER — see the module note above. Step 2 (`consumers`
4690 /// side-table, push-only) replaces this body with the real incremental
4691 /// logic; nothing else in this harness needs to change when it does.
4692 fn run_new_safety_analysis(graph: &SharedGraph, roots: &[NodeId]) -> SafetyAnalysisResult {
4693 run_old_safety_analysis(graph, roots)
4694 }
4695
4696 fn assert_safety_analysis_matches(name: &str, factory: SafetyCorpusFactory) {
4697 let (old_graph, old_roots) = factory();
4698 let (new_graph, new_roots) = factory();
4699 assert_eq!(
4700 old_roots, new_roots,
4701 "{name}: factory produced different roots across two calls -- corpus factory \
4702 must be deterministic (same pushes, same order) or this harness can't compare"
4703 );
4704 let old = run_old_safety_analysis(&old_graph, &old_roots);
4705 let new = run_new_safety_analysis(&new_graph, &new_roots);
4706 assert_eq!(old, new, "{name}: old vs new safety analysis diverged");
4707 }
4708
4709 fn corpus_no_destructive_conflicts() -> (SharedGraph, Vec<NodeId>) {
4710 // a + b, no in-place op anywhere -- insert_safety_copies must be a
4711 // pure no-op (mirrors insert_safety_copies_noop_when_no_destructive_conflicts).
4712 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
4713 let b = a
4714 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
4715 .unwrap();
4716 let c = a.add(&b);
4717 (c.graph().clone(), vec![c.id()])
4718 }
4719
4720 fn corpus_residual_connection() -> (SharedGraph, Vec<NodeId>) {
4721 // y = x.relu_inplace(); z = y + x -- the canonical cycle-breaking
4722 // case (mirrors insert_safety_copies_residual_connection_breaks_cycle).
4723 let x = NodeHandle::from_f32(
4724 vec![1.0_f32, -2.0, 3.0, -4.0],
4725 Shape::from_dims(&[4]),
4726 cpu_dev(),
4727 )
4728 .unwrap();
4729 let x_shape = x.shape();
4730 let x_dtype = x.dtype();
4731 let x_id = x.id();
4732 let z_id = {
4733 let mut g = x.graph().write().unwrap();
4734 let y_id = g.push(crate::Node {
4735 op: crate::Op::ReluInplace,
4736 inputs: vec![x_id],
4737 shape: x_shape.clone(),
4738 dtype: x_dtype,
4739 });
4740 g.push(crate::Node {
4741 op: crate::Op::Add,
4742 inputs: vec![y_id, x_id],
4743 shape: x_shape,
4744 dtype: x_dtype,
4745 })
4746 };
4747 (x.graph().clone(), vec![z_id])
4748 }
4749
4750 fn corpus_independent_reader_of_move_needs_no_copy() -> (SharedGraph, Vec<NodeId>) {
4751 // relu(a) pinned before move(a); an unrelated reader needs no copy
4752 // (mirrors insert_safety_copies_no_spurious_copy_for_independent_reader_of_move,
4753 // flip_roots=false arm: roots=[b, m], DFS visits m's subtree first
4754 // so b lands positionally after the Move).
4755 let a =
4756 NodeHandle::from_f32(vec![1.0_f32, -2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
4757 let b = a.relu();
4758 let a_shape = a.shape();
4759 let a_dtype = a.dtype();
4760 let a_id = a.id();
4761 let m_id = a.graph().write().unwrap().push(crate::Node {
4762 op: crate::Op::Move {
4763 target: DeviceLocation::Cpu,
4764 },
4765 inputs: vec![a_id],
4766 shape: a_shape,
4767 dtype: a_dtype,
4768 });
4769 (a.graph().clone(), vec![b.id(), m_id])
4770 }
4771
4772 fn corpus_many_independent_no_reader_chains() -> (SharedGraph, Vec<NodeId>) {
4773 // A small-N version of the perf regression shape above: many
4774 // independent 2-node chains, none with an extra reader. Exercises
4775 // the common case (most destructive ops in a real decode graph have
4776 // no other reader at all) at a size small enough that the
4777 // differential comparison's O(graph) structural equality check
4778 // stays cheap in a correctness-focused test, not a perf one.
4779 const N: usize = 25;
4780 let shape = Shape::from_dims(&[4]);
4781 let mut g = crate::Graph::new();
4782 let mut roots: Vec<NodeId> = Vec::with_capacity(N);
4783 for _ in 0..N {
4784 let leaf = g.push(crate::Node {
4785 op: crate::Op::Const,
4786 inputs: vec![],
4787 shape: shape.clone(),
4788 dtype: DType::F32,
4789 });
4790 let relu = g.push(crate::Node {
4791 op: crate::Op::ReluInplace,
4792 inputs: vec![leaf],
4793 shape: shape.clone(),
4794 dtype: DType::F32,
4795 });
4796 roots.push(relu);
4797 }
4798 (Arc::new(std::sync::RwLock::new(g)), roots)
4799 }
4800
4801 const SAFETY_CORPUS: &[(&str, SafetyCorpusFactory)] = &[
4802 ("no_destructive_conflicts", corpus_no_destructive_conflicts),
4803 ("residual_connection", corpus_residual_connection),
4804 (
4805 "independent_reader_of_move_needs_no_copy",
4806 corpus_independent_reader_of_move_needs_no_copy,
4807 ),
4808 (
4809 "many_independent_no_reader_chains",
4810 corpus_many_independent_no_reader_chains,
4811 ),
4812 ];
4813
4814 #[test]
4815 fn differential_safety_analysis_matches_on_corpus() {
4816 for &(name, factory) in SAFETY_CORPUS {
4817 assert_safety_analysis_matches(name, factory);
4818 }
4819 }
4820
4821 #[test]
4822 fn derive_ordering_release_of_multi_reader_input() {
4823 // a read by relu AND neg, then released. Both relu and neg
4824 // must precede the release.
4825 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
4826 let b = a.relu();
4827 let c = a.neg();
4828 let r = a.release();
4829 let ord = derive_ordering(&a.graph().read().unwrap(), &[b.id(), c.id(), r.id()]);
4830 let mut deps = ord.deps_of(r.id()).to_vec();
4831 deps.sort_by_key(|n| n.0);
4832 let mut expected = vec![b.id(), c.id()];
4833 expected.sort_by_key(|n| n.0);
4834 assert_eq!(deps, expected);
4835 }
4836
4837 #[test]
4838 fn execution_plan_matches_topo_when_no_destructive_ops() {
4839 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
4840 let b = a
4841 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
4842 .unwrap();
4843 let c = a.add(&b);
4844 let graph = c.graph().read().unwrap();
4845 let plan = execution_plan(&graph, &[c.id()]);
4846 let topo = topo_order_multi(&graph, &[c.id()]);
4847 assert_eq!(plan, topo);
4848 }
4849
4850 #[test]
4851 fn execution_plan_pins_release_after_sibling_reader() {
4852 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
4853 let b = a.relu();
4854 let r = a.release();
4855 let plan = execution_plan(&a.graph().read().unwrap(), &[b.id(), r.id()]);
4856 let b_pos = plan.iter().position(|&n| n == b.id()).unwrap();
4857 let r_pos = plan.iter().position(|&n| n == r.id()).unwrap();
4858 assert!(
4859 b_pos < r_pos,
4860 "expected relu@{b_pos} to precede release@{r_pos}: {plan:?}"
4861 );
4862 }
4863
4864 #[test]
4865 fn execution_plan_handles_chain_of_destructive_ops() {
4866 // a -> relu -> b
4867 // a -> neg -> c
4868 // a -> release
4869 // b and c must come before release.
4870 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
4871 let b = a.relu();
4872 let c = a.neg();
4873 let r = a.release();
4874 let plan = execution_plan(&a.graph().read().unwrap(), &[b.id(), c.id(), r.id()]);
4875 let b_pos = plan.iter().position(|&n| n == b.id()).unwrap();
4876 let c_pos = plan.iter().position(|&n| n == c.id()).unwrap();
4877 let r_pos = plan.iter().position(|&n| n == r.id()).unwrap();
4878 assert!(
4879 b_pos < r_pos,
4880 "relu@{b_pos} must precede release@{r_pos}: {plan:?}"
4881 );
4882 assert!(
4883 c_pos < r_pos,
4884 "neg@{c_pos} must precede release@{r_pos}: {plan:?}"
4885 );
4886 }
4887
4888 #[test]
4889 fn insert_evict_reload_creates_expected_chain() {
4890 // Graph:
4891 // a (producer, device=Cpu default)
4892 // b = relu(a) (pre-gap consumer — stays wired to a)
4893 // c = neg(a) (post-gap consumer — should be rewired to reload)
4894 // After insert_evict_reload(a, Cpu, &[c]):
4895 // - 2 new nodes (move, reload) appended
4896 // - c's input list now has `reload_id` instead of `a.id()`
4897 // - b's input list STILL has `a.id()` (unchanged)
4898 let a =
4899 NodeHandle::from_f32(vec![1.0_f32, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
4900 let b = a.relu();
4901 let c = a.neg();
4902
4903 let (move_id, reload_id) =
4904 insert_evict_reload(a.graph(), a.id(), DeviceLocation::Cpu, &[c.id()]);
4905
4906 let g = a.graph().read().unwrap();
4907 // mv is an Op::Move{Cpu} reading a — the fused stage-to-host +
4908 // destructive release of a's device storage.
4909 match &g.node(move_id).op {
4910 Op::Move {
4911 target: DeviceLocation::Cpu,
4912 } => {}
4913 other => panic!("expected Op::Move{{Cpu}}, got {other:?}"),
4914 }
4915 assert_eq!(g.node(move_id).inputs, vec![a.id()]);
4916 assert_eq!(
4917 g.node(move_id).op.destructive_input(),
4918 Some(0),
4919 "Move must destroy its source so the device storage frees",
4920 );
4921 // reload is an Op::Copy{Cpu} (src_device passed in) reading mv
4922 assert!(matches!(g.node(reload_id).op, Op::Copy { .. }));
4923 assert_eq!(g.node(reload_id).inputs, vec![move_id]);
4924 // c's input was rewired
4925 assert_eq!(
4926 g.node(c.id()).inputs,
4927 vec![reload_id],
4928 "post-gap consumer should read from reload, not candidate directly"
4929 );
4930 // b's input stays
4931 assert_eq!(
4932 g.node(b.id()).inputs,
4933 vec![a.id()],
4934 "pre-gap consumer should still read candidate directly"
4935 );
4936 }
4937
4938 #[test]
4939 fn execution_plan_respects_transitive_data_deps_after_release() {
4940 // Graph:
4941 // a
4942 // b = relu(a)
4943 // r = release(a) (destructive; runs after b)
4944 // sum = sum_all(b) (data-dependent on b, not on r)
4945 // Plan must have: b before r, b before sum; b before both is enough.
4946 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
4947 let b = a.relu();
4948 let sum = b.sum_all();
4949 let r = a.release();
4950 let plan = execution_plan(&a.graph().read().unwrap(), &[sum.id(), r.id()]);
4951 let b_pos = plan.iter().position(|&n| n == b.id()).unwrap();
4952 let sum_pos = plan.iter().position(|&n| n == sum.id()).unwrap();
4953 let r_pos = plan.iter().position(|&n| n == r.id()).unwrap();
4954 assert!(b_pos < sum_pos);
4955 assert!(b_pos < r_pos);
4956 }
4957
4958 #[test]
4959 fn fuse_linear_collapses_matmul_plus_rank1_bias() {
4960 // Build [batch=1, m=2, k=3] @ [k=3, n=4] + bias[4].
4961 let a = crate::NodeHandle::from_f32(
4962 vec![1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0],
4963 crate::Shape::from_dims(&[2, 3]),
4964 cpu_dev(),
4965 )
4966 .unwrap();
4967 let b = a
4968 .const_f32_like(
4969 (0..12).map(|i| (i as f32) * 0.1).collect::<Vec<f32>>(),
4970 crate::Shape::from_dims(&[3, 4]),
4971 )
4972 .unwrap();
4973 let bias = a.const_f32_like(
4974 vec![0.5_f32, -0.5, 1.0, -1.0],
4975 crate::Shape::from_dims(&[4]),
4976 );
4977 let mm = a.matmul(&b);
4978 let bias_b = bias.unwrap().broadcast_to(crate::Shape::from_dims(&[2, 4]));
4979 let out = mm.add(&bias_b);
4980 // Note: real users would call broadcast_to first, then Add.
4981 // The fusion pass looks for `Add(MatMul, Const-shape-1-N)`
4982 // so we need to update it to also recognize the
4983 // BroadcastTo-then-Add pattern.
4984 let n_fused = fuse_linear(out.graph(), &[out.id()]);
4985 assert_eq!(n_fused, 1, "exactly one MatMul→Add(bias[N]) should fuse");
4986
4987 // The fused node should now be reachable as the canonical
4988 // root after remap. Its op is FusedLinear with three inputs.
4989 let g = out.graph().read().unwrap();
4990 // Walk consumers of the original Add: any leftover Add should
4991 // be unreferenced; the new FusedLinear should be present.
4992 // Phase 7.6 step 4: emission is the registry-extended shape.
4993 let any_fused = g.nodes.iter().any(|n| {
4994 matches!(
4995 n.op,
4996 Op::Fused(fid, _) if fid == crate::registry::FusedOps::FUSED_LINEAR,
4997 )
4998 });
4999 assert!(
5000 any_fused,
5001 "graph should contain an Op::Fused(FUSED_LINEAR) node"
5002 );
5003 }
5004
5005 #[test]
5006 fn fuse_linear_skips_when_matmul_has_other_consumers() {
5007 // If the matmul is consumed by both Add and something else,
5008 // fusing would duplicate the matmul. Pass should skip.
5009 let a = crate::NodeHandle::from_f32(
5010 vec![1.0_f32; 6],
5011 crate::Shape::from_dims(&[2, 3]),
5012 cpu_dev(),
5013 )
5014 .unwrap();
5015 let b = a
5016 .const_f32_like(vec![1.0_f32; 12], crate::Shape::from_dims(&[3, 4]))
5017 .unwrap();
5018 let bias = a
5019 .const_f32_like(vec![1.0_f32; 4], crate::Shape::from_dims(&[4]))
5020 .unwrap();
5021 let mm = a.matmul(&b);
5022 let bias_b = bias.broadcast_to(crate::Shape::from_dims(&[2, 4]));
5023 let with_bias = mm.add(&bias_b);
5024 let also_used = mm.relu(); // second consumer of mm
5025 // Both with_bias and also_used are roots.
5026 let n_fused = fuse_linear(a.graph(), &[with_bias.id(), also_used.id()]);
5027 assert_eq!(
5028 n_fused, 0,
5029 "MatMul has 2 consumers — fusion would duplicate work"
5030 );
5031 }
5032
5033 // ---- Rule registry: SoftmaxLastDim lower / fuse / round-trip ------------
5034
5035 fn count_op_in_reachable<F: Fn(&Op) -> bool>(
5036 graph: &SharedGraph,
5037 roots: &[NodeId],
5038 pred: F,
5039 ) -> usize {
5040 let g = graph.read().unwrap();
5041 topo_order_multi(&g, roots)
5042 .into_iter()
5043 .filter(|id| pred(&g.node(*id).op))
5044 .count()
5045 }
5046
5047 /// The lower rule, applied to a graph with one fused softmax,
5048 /// produces the canonical primitive subgraph reachable from the
5049 /// rewritten root, with auto-populated layout entries on the
5050 /// inserted BroadcastTo nodes.
5051 ///
5052 /// T5 (Increment C slice 1): the lowered spelling is the RECIPE's
5053 /// 9-node shrink-via-swap form — `MaxDim`/`SumDim` at the last axis +
5054 /// `Unsqueeze` append restoring keepdim, with the `e = Exp(..)`
5055 /// interior SHARED (identity-share) between the denominator reduce and
5056 /// the final Div — replacing the legacy 7-node
5057 /// `ReduceMaxTo`/`ReduceSumTo` form.
5058 #[test]
5059 fn softmax_last_dim_lower_rule_produces_canonical_subgraph() {
5060 let x = NodeHandle::from_f32(vec![1.0_f32; 12], Shape::from_dims(&[2, 3, 2]), cpu_dev())
5061 .unwrap();
5062 let sm = x.softmax_last_dim();
5063 let graph = sm.graph().clone();
5064
5065 let registry = RuleRegistry::lowering_only();
5066 let new_roots = registry.optimize_to_fixpoint(&graph, &[sm.id()]);
5067 assert_eq!(new_roots.len(), 1);
5068 let new_root = new_roots[0];
5069
5070 // Reachable subgraph from the new root should contain exactly
5071 // the 9 lowered nodes (plus the `x` Const leaf — that's 10).
5072 // Op composition: 1 MaxDim, 2 Unsqueeze, 2 BroadcastTo, 1 Sub,
5073 // 1 Exp, 1 SumDim, 1 Div, 1 Const = 10 reachable.
5074 let g = graph.read().unwrap();
5075 let reachable = topo_order_multi(&g, &[new_root]);
5076 assert_eq!(
5077 reachable.len(),
5078 10,
5079 "lowered subgraph: 9 ops + 1 Const = 10 reachable nodes"
5080 );
5081 drop(g);
5082
5083 // Op-shape sanity checks.
5084 let n_reduce_max =
5085 count_op_in_reachable(&graph, &[new_root], |op| matches!(op, Op::ReduceMaxTo(_)));
5086 let n_max_dim =
5087 count_op_in_reachable(&graph, &[new_root], |op| matches!(op, Op::MaxDim(_)));
5088 let n_sum_dim =
5089 count_op_in_reachable(&graph, &[new_root], |op| matches!(op, Op::SumDim(_)));
5090 let n_unsqueeze =
5091 count_op_in_reachable(&graph, &[new_root], |op| matches!(op, Op::Unsqueeze { .. }));
5092 let n_reshape =
5093 count_op_in_reachable(&graph, &[new_root], |op| matches!(op, Op::Reshape(_)));
5094 let n_broadcast =
5095 count_op_in_reachable(&graph, &[new_root], |op| matches!(op, Op::BroadcastTo(_)));
5096 let n_sub = count_op_in_reachable(&graph, &[new_root], |op| matches!(op, Op::Sub));
5097 let n_exp = count_op_in_reachable(&graph, &[new_root], |op| matches!(op, Op::Exp));
5098 let n_reduce_sum =
5099 count_op_in_reachable(&graph, &[new_root], |op| matches!(op, Op::ReduceSumTo(_)));
5100 let n_div = count_op_in_reachable(&graph, &[new_root], |op| matches!(op, Op::Div));
5101 // Phase 7.6 step 5: post-migration the builder emits
5102 // `Op::Fused(SOFTMAX_LAST_DIM, _)` only — the legacy
5103 // `Op::SoftmaxLastDim` variant was retired.
5104 let n_softmax = count_op_in_reachable(
5105 &graph,
5106 &[new_root],
5107 |op| matches!(op, Op::Fused(fid, _) if *fid == FusedOps::SOFTMAX_LAST_DIM),
5108 );
5109 assert_eq!(
5110 n_max_dim, 1,
5111 "T5 max side = MaxDim(last) + Unsqueeze append"
5112 );
5113 assert_eq!(
5114 n_sum_dim, 1,
5115 "T5 sum side = SumDim(last) + Unsqueeze append"
5116 );
5117 assert_eq!(n_unsqueeze, 2, "one keepdim-restore per reduce");
5118 assert_eq!(
5119 n_reduce_max, 0,
5120 "the legacy ReduceMaxTo spelling is retired from the lowering"
5121 );
5122 assert_eq!(
5123 n_reduce_sum, 0,
5124 "the legacy ReduceSumTo spelling is retired from the lowering"
5125 );
5126 assert_eq!(n_reshape, 0, "keepdim restores via Unsqueeze, not Reshape");
5127 assert_eq!(n_broadcast, 2);
5128 assert_eq!(n_sub, 1);
5129 assert_eq!(
5130 n_exp, 1,
5131 "the shared `e` interior emits ONCE (identity-share), not per consumer"
5132 );
5133 assert_eq!(n_div, 1);
5134 assert_eq!(
5135 n_softmax, 0,
5136 "no SoftmaxLastDim/Fused(SOFTMAX_LAST_DIM) should remain reachable post-lowering"
5137 );
5138
5139 // Layout side-table entries on the inserted BroadcastTo nodes
5140 // must be populated and have the expected broadcast strides.
5141 let g = graph.read().unwrap();
5142 for id in topo_order_multi(&g, &[new_root]) {
5143 if let Op::BroadcastTo(_) = g.node(id).op {
5144 assert!(
5145 g.has_explicit_layout(id),
5146 "lowered BroadcastTo at {id:?} missing explicit Layout entry — \
5147 Graph::push auto-populate should have set it",
5148 );
5149 // The inserted BroadcastTo broadcasts shape [2,3,1] -> [2,3,2]
5150 // with last-dim stride 0.
5151 let l = g.layout(id);
5152 assert_eq!(l.shape().dims(), &[2, 3, 2]);
5153 assert_eq!(
5154 l.stride().last().copied(),
5155 Some(0),
5156 "BroadcastTo from [2,3,1] to [2,3,2] should have stride 0 on last dim"
5157 );
5158 }
5159 }
5160 }
5161
5162 /// The fuse rule, applied to the canonical 7-node lowered subgraph,
5163 /// collapses it back to a single `Op::SoftmaxLastDim` reachable
5164 /// from the rewritten root.
5165 #[test]
5166 fn softmax_last_dim_fuse_rule_collapses_canonical_subgraph() {
5167 // Build the canonical subgraph by-hand — start from a Const
5168 // and apply the same op sequence the lower rule would emit.
5169 let x =
5170 NodeHandle::from_f32(vec![1.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
5171 let m = x.reduce_max_to(Shape::from_dims(&[2, 1]));
5172 let mb = m.broadcast_to(Shape::from_dims(&[2, 3]));
5173 let s = x.sub(&mb);
5174 let e = s.exp();
5175 let d = e.reduce_sum_to(Shape::from_dims(&[2, 1]));
5176 let db = d.broadcast_to(Shape::from_dims(&[2, 3]));
5177 let out = e.div(&db);
5178 let graph = out.graph().clone();
5179
5180 // Phase 7.6 step 3: fuse rule comes from the registry entry.
5181 let registry = RuleRegistry::new().with_rule(Box::new(FusionRule::from_entry(
5182 &crate::registry::softmax_last_dim::entry(),
5183 )));
5184 let new_roots = registry.optimize_to_fixpoint(&graph, &[out.id()]);
5185 assert_eq!(new_roots.len(), 1);
5186 let new_root = new_roots[0];
5187
5188 // Reachable from the new root: 1 fused-softmax + 1 Const x = 2.
5189 let g = graph.read().unwrap();
5190 let reachable = topo_order_multi(&g, &[new_root]);
5191 assert_eq!(
5192 reachable.len(),
5193 2,
5194 "fused subgraph: 1 Fused(SOFTMAX_LAST_DIM) + 1 Const = 2 reachable nodes"
5195 );
5196 assert!(
5197 matches!(
5198 g.node(new_root).op,
5199 Op::Fused(fid, _) if fid == FusedOps::SOFTMAX_LAST_DIM
5200 ),
5201 "post-migration fusion produces Op::Fused(SOFTMAX_LAST_DIM, _)",
5202 );
5203 // Fused-softmax's input should be the original Const x.
5204 assert_eq!(g.node(new_root).inputs, vec![x.id()]);
5205 }
5206
5207 /// Lower then fuse to fixpoint: a graph with one `Op::SoftmaxLastDim`
5208 /// returns to a graph that's structurally identical to the input
5209 /// (modulo a re-canonicalized root NodeId — the original
5210 /// SoftmaxLastDim node remains in the arena but is unreachable
5211 /// from the rewritten root).
5212 #[test]
5213 fn softmax_last_dim_lower_then_fuse_round_trips() {
5214 let x =
5215 NodeHandle::from_f32(vec![1.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
5216 let sm = x.softmax_last_dim();
5217 let graph = sm.graph().clone();
5218 let original_root = sm.id();
5219
5220 let registry = RuleRegistry::default_rules();
5221 let new_roots = registry.optimize_to_fixpoint(&graph, &[original_root]);
5222 assert_eq!(new_roots.len(), 1);
5223 let new_root = new_roots[0];
5224
5225 // Reachable from the new root must look like the original
5226 // graph: one fused-softmax consuming one Const. Phase 7.6
5227 // step 3: the post-migration builder + fuse cycle produces
5228 // `Op::Fused(SOFTMAX_LAST_DIM, _)`, not `Op::SoftmaxLastDim`.
5229 let g = graph.read().unwrap();
5230 let reachable = topo_order_multi(&g, &[new_root]);
5231 assert_eq!(
5232 reachable.len(),
5233 2,
5234 "round-tripped graph: 1 Fused(SOFTMAX_LAST_DIM) + 1 Const = 2 reachable nodes"
5235 );
5236 assert!(
5237 matches!(
5238 g.node(new_root).op,
5239 Op::Fused(fid, _) if fid == FusedOps::SOFTMAX_LAST_DIM
5240 ),
5241 "round-tripped node should be Op::Fused(SOFTMAX_LAST_DIM, _)",
5242 );
5243 assert_eq!(
5244 g.node(new_root).inputs,
5245 vec![x.id()],
5246 "round-tripped Fused(SOFTMAX_LAST_DIM) should consume the original input"
5247 );
5248 // Shape and dtype preserved.
5249 assert_eq!(g.node(new_root).shape, g.node(original_root).shape);
5250 assert_eq!(g.node(new_root).dtype, g.node(original_root).dtype);
5251 }
5252
5253 /// Empty registry is a no-op: roots come back unchanged.
5254 #[test]
5255 fn empty_registry_is_noop() {
5256 let x = NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
5257 let y = x.add(&x);
5258 let graph = y.graph().clone();
5259 let pre_len = graph.read().unwrap().len();
5260 let new_roots = RuleRegistry::new().optimize_to_fixpoint(&graph, &[y.id()]);
5261 assert_eq!(new_roots, vec![y.id()]);
5262 assert_eq!(
5263 graph.read().unwrap().len(),
5264 pre_len,
5265 "empty registry should add no nodes"
5266 );
5267 }
5268
5269 /// Lowering rule does not fire on a graph that has no
5270 /// SoftmaxLastDim nodes — the registry returns the input
5271 /// roots unchanged.
5272 #[test]
5273 fn lower_rule_does_not_fire_without_softmax() {
5274 let x = NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
5275 let y = x.relu();
5276 let graph = y.graph().clone();
5277 let pre_len = graph.read().unwrap().len();
5278 let new_roots = RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[y.id()]);
5279 assert_eq!(new_roots, vec![y.id()]);
5280 assert_eq!(graph.read().unwrap().len(), pre_len);
5281 }
5282
5283 /// `lower_to_base_map` is a named wrapper over
5284 /// `RuleRegistry::lowering_only().optimize_to_fixpoint` — a fused ROPE
5285 /// node dissolves to its primitive base map; no `Op::Fused(ROPE, _)`
5286 /// remains reachable from the (possibly-remapped) roots.
5287 #[test]
5288 fn lower_to_base_map_dissolves_a_fused_op() {
5289 use std::sync::RwLock;
5290 // Build a graph: three Const leaves (x, cos, sin) + one Op::Fused(ROPE).
5291 let graph = Arc::new(RwLock::new(Graph::new()));
5292 let sink = {
5293 let mut g = graph.write().unwrap();
5294 let shape = Shape::from_dims(&[1, 4, 8]); // (batch, seq, head_dim=8, even)
5295 let x = g.push(Node {
5296 op: Op::Const,
5297 inputs: vec![],
5298 shape: shape.clone(),
5299 dtype: DType::F32,
5300 });
5301 let cshape = Shape::from_dims(&[4, 8]);
5302 let cos = g.push(Node {
5303 op: Op::Const,
5304 inputs: vec![],
5305 shape: cshape.clone(),
5306 dtype: DType::F32,
5307 });
5308 let sin = g.push(Node {
5309 op: Op::Const,
5310 inputs: vec![],
5311 shape: cshape,
5312 dtype: DType::F32,
5313 });
5314 g.push(Node {
5315 op: Op::Fused(FusedOps::ROPE, FusedOpParams::Rope),
5316 inputs: vec![x, cos, sin],
5317 shape,
5318 dtype: DType::F32,
5319 })
5320 };
5321 let roots = lower_to_base_map(&graph, &[sink]);
5322 let g = graph.read().unwrap();
5323 // No Op::Fused(ROPE) remains reachable; the base map is primitives.
5324 let reachable = topo_order_multi(&g, &roots);
5325 let has_rope = reachable
5326 .iter()
5327 .any(|&n| matches!(g.node(n).op, Op::Fused(fid, _) if fid == FusedOps::ROPE));
5328 assert!(!has_rope, "ROPE must be lowered to its primitive base map");
5329 }
5330
5331 /// `base_map_hash` canonicalizes commutative-operand order: two
5332 /// independently-built graphs computing `a + b` and `b + a` (same
5333 /// consts, swapped operand order on the `Add`) hash equal.
5334 #[test]
5335 fn base_map_hash_commutative_reorder_is_equal() {
5336 let mk = |swap: bool| {
5337 let mut g = Graph::new();
5338 let s = Shape::from_dims(&[4]);
5339 let a = g.push(Node {
5340 op: Op::Const,
5341 inputs: vec![],
5342 shape: s.clone(),
5343 dtype: DType::F32,
5344 });
5345 let b = g.push(Node {
5346 op: Op::Const,
5347 inputs: vec![],
5348 shape: s.clone(),
5349 dtype: DType::F32,
5350 });
5351 let ins = if swap { vec![b, a] } else { vec![a, b] };
5352 let sink = g.push(Node {
5353 op: Op::Add,
5354 inputs: ins,
5355 shape: s,
5356 dtype: DType::F32,
5357 });
5358 (g, sink)
5359 };
5360 let (g0, r0) = mk(false);
5361 let (g1, r1) = mk(true);
5362 assert_eq!(base_map_hash(&g0, r0), base_map_hash(&g1, r1), "a+b == b+a");
5363 }
5364
5365 /// `base_map_hash` distinguishes distinct ops over the same operands:
5366 /// `Add(a, b)` and `Mul(a, b)` must hash differently.
5367 #[test]
5368 fn base_map_hash_distinct_ops_differ() {
5369 let mk = |op: Op| {
5370 let mut g = Graph::new();
5371 let s = Shape::from_dims(&[4]);
5372 let a = g.push(Node {
5373 op: Op::Const,
5374 inputs: vec![],
5375 shape: s.clone(),
5376 dtype: DType::F32,
5377 });
5378 let b = g.push(Node {
5379 op: Op::Const,
5380 inputs: vec![],
5381 shape: s.clone(),
5382 dtype: DType::F32,
5383 });
5384 let sink = g.push(Node {
5385 op,
5386 inputs: vec![a, b],
5387 shape: s,
5388 dtype: DType::F32,
5389 });
5390 (g, sink)
5391 };
5392 let (ga, ra) = mk(Op::Add);
5393 let (gm, rm) = mk(Op::Mul);
5394 assert_ne!(base_map_hash(&ga, ra), base_map_hash(&gm, rm), "add != mul");
5395 }
5396
5397 /// `op_key` already carries explicit arms for `Op::Slice` and
5398 /// `Op::Concat` (tags 81/80) — the two ops rope's rotate-half base map
5399 /// relies on. This test forces that path: a tiny `Slice`-then-`Concat`
5400 /// fragment (the first half of rope's rotate-half idiom) hashes
5401 /// deterministically across two independently-built, structurally
5402 /// identical copies.
5403 #[test]
5404 fn base_map_hash_slice_concat_fragment_is_deterministic() {
5405 let mk = || {
5406 let mut g = Graph::new();
5407 let s = Shape::from_dims(&[4, 8]);
5408 let half = Shape::from_dims(&[4, 4]);
5409 let x = g.push(Node {
5410 op: Op::Const,
5411 inputs: vec![],
5412 shape: s.clone(),
5413 dtype: DType::F32,
5414 });
5415 let lo = g.push(Node {
5416 op: Op::Slice {
5417 dim: 1,
5418 start: 0,
5419 len: 4,
5420 },
5421 inputs: vec![x],
5422 shape: half.clone(),
5423 dtype: DType::F32,
5424 });
5425 let hi = g.push(Node {
5426 op: Op::Slice {
5427 dim: 1,
5428 start: 4,
5429 len: 4,
5430 },
5431 inputs: vec![x],
5432 shape: half,
5433 dtype: DType::F32,
5434 });
5435 let sink = g.push(Node {
5436 op: Op::Concat { dim: 1 },
5437 inputs: vec![hi, lo],
5438 shape: s,
5439 dtype: DType::F32,
5440 });
5441 (g, sink)
5442 };
5443 let (g0, r0) = mk();
5444 let (g1, r1) = mk();
5445 assert_eq!(
5446 base_map_hash(&g0, r0),
5447 base_map_hash(&g1, r1),
5448 "two independently-built Slice->Concat fragments must hash equal"
5449 );
5450 }
5451
5452 /// `base_map_hash` folds a `Const`'s real bytes when its storage slot
5453 /// is populated (unlike the bare `Node { op: Op::Const, .. }` pushes
5454 /// used above, `NodeHandle::from_f32` populates real storage via
5455 /// `set_storage`). Two consts with equal bytes hash equal; two consts
5456 /// of the same shape/dtype but different bytes hash differently — this
5457 /// is the behavior that distinguishes real recipe identity from the
5458 /// shape/dtype-only fallback (documented on `fold_const_bytes`).
5459 #[test]
5460 fn base_map_hash_folds_real_const_bytes() {
5461 let shape = Shape::from_dims(&[4]);
5462 let a = NodeHandle::from_f32(vec![1.0, 2.0, 3.0, 4.0], shape.clone(), cpu_dev()).unwrap();
5463 let b = NodeHandle::from_f32(vec![1.0, 2.0, 3.0, 4.0], shape.clone(), cpu_dev()).unwrap();
5464 let c = NodeHandle::from_f32(vec![9.0, 9.0, 9.0, 9.0], shape, cpu_dev()).unwrap();
5465 let ga = a.graph().read().unwrap();
5466 let gb = b.graph().read().unwrap();
5467 let gc = c.graph().read().unwrap();
5468 assert_eq!(
5469 base_map_hash(&ga, a.id()),
5470 base_map_hash(&gb, b.id()),
5471 "identical const bytes must hash equal across independently-built graphs"
5472 );
5473 assert_ne!(
5474 base_map_hash(&ga, a.id()),
5475 base_map_hash(&gc, c.id()),
5476 "different const bytes (same shape/dtype) must hash differently"
5477 );
5478 }
5479
5480 #[test]
5481 fn scan_base_map_hash_differs_for_different_bodies() {
5482 use crate::{Graph, Node, Op, ScanEmit, ScanRole};
5483 use fuel_ir::{DType, Shape};
5484 // Two scans, IDENTICAL carry shape / n_xs / bound / emit, but STRUCTURALLY
5485 // DIFFERENT bodies: body A = carry*2 (MulScalar), body B = carry+1
5486 // (AddScalar). Without a dedicated op_key arm they fall to the None branch
5487 // (discriminant+shape+dtype only) and collide -> silent CSE / recipe-identity
5488 // corruption. THIS red run is the evidence the trap is real.
5489 let mk = |mul: bool| {
5490 let mut g = Graph::new();
5491 let s = Shape::from_dims(&[1]);
5492 let carry = g.push(Node {
5493 op: Op::Const,
5494 inputs: vec![],
5495 shape: s.clone(),
5496 dtype: DType::F32,
5497 });
5498 let hole = g.push(Node {
5499 op: Op::ScanPlaceholder {
5500 role: ScanRole::Carry,
5501 index: 0,
5502 },
5503 inputs: vec![],
5504 shape: s.clone(),
5505 dtype: DType::F32,
5506 });
5507 let new_carry = g.push(Node {
5508 op: if mul {
5509 Op::MulScalar(2.0)
5510 } else {
5511 Op::AddScalar(1.0)
5512 },
5513 inputs: vec![hole],
5514 shape: s.clone(),
5515 dtype: DType::F32,
5516 });
5517 // inputs = [init_carry, body_new_carry, body_y] (n_xs = 0, no consts)
5518 let scan = g.push(Node {
5519 op: Op::Scan {
5520 n_carries: 1,
5521 n_xs: 0,
5522 bound: 3,
5523 emit: ScanEmit::All,
5524 early_exit: None,
5525 },
5526 inputs: vec![carry, new_carry, new_carry],
5527 shape: s,
5528 dtype: DType::F32,
5529 });
5530 (g, scan)
5531 };
5532 let (ga, ra) = mk(true);
5533 let (gb, rb) = mk(false);
5534 assert_ne!(
5535 base_map_hash(&ga, ra),
5536 base_map_hash(&gb, rb),
5537 "scans with structurally different bodies must hash differently",
5538 );
5539 }
5540
5541 #[test]
5542 fn scan_base_map_hash_equal_for_same_body_cross_graph() {
5543 use crate::{Graph, Node, Op, ScanEmit, ScanRole};
5544 use fuel_ir::{DType, Shape};
5545 // Same body built independently in two graphs -> equal hash (the
5546 // recipe-identity positive case). base_map_hash is NodeId-independent.
5547 let mk = || {
5548 let mut g = Graph::new();
5549 let s = Shape::from_dims(&[1]);
5550 let carry = g.push(Node {
5551 op: Op::Const,
5552 inputs: vec![],
5553 shape: s.clone(),
5554 dtype: DType::F32,
5555 });
5556 let hole = g.push(Node {
5557 op: Op::ScanPlaceholder {
5558 role: ScanRole::Carry,
5559 index: 0,
5560 },
5561 inputs: vec![],
5562 shape: s.clone(),
5563 dtype: DType::F32,
5564 });
5565 let new_carry = g.push(Node {
5566 op: Op::MulScalar(2.0),
5567 inputs: vec![hole],
5568 shape: s.clone(),
5569 dtype: DType::F32,
5570 });
5571 let scan = g.push(Node {
5572 op: Op::Scan {
5573 n_carries: 1,
5574 n_xs: 0,
5575 bound: 3,
5576 emit: ScanEmit::All,
5577 early_exit: None,
5578 },
5579 inputs: vec![carry, new_carry, new_carry],
5580 shape: s,
5581 dtype: DType::F32,
5582 });
5583 (g, scan)
5584 };
5585 let (g0, r0) = mk();
5586 let (g1, r1) = mk();
5587 assert_eq!(
5588 base_map_hash(&g0, r0),
5589 base_map_hash(&g1, r1),
5590 "same body -> equal hash"
5591 );
5592 }
5593
5594 /// GAP-303 DISCRIMINATING FIXTURE for the `n_carries` fold in `op_key`.
5595 ///
5596 /// ⚠️ WITHOUT THIS TEST THE FIX IS INVISIBLE IN ITS OWN METRIC. Every other
5597 /// scan test in this workspace uses ONE carry, and `NodeHandle::scan` pins
5598 /// `n_carries: 1`, so folding the field or not folding it produces identical
5599 /// hashes across the entire suite. Ask "if this became a no-op, which number
5600 /// moves?" — before this test, none.
5601 ///
5602 /// What it protects: `op_key` is Fuel's own recipe identity. Two scans that
5603 /// differ ONLY in carry count must not key the same, or cover-finding and the
5604 /// plan cache treat a 1-carry and a 3-carry scan as one recipe. Same defect
5605 /// class as KISS-OPS-6.19, where an arm reading too few attrs made
5606 /// Gather-on-axis-2 and Gather-on-axis-0 emit IDENTICAL bytes.
5607 #[test]
5608 fn gap303_n_carries_participates_in_op_key() {
5609 use crate::{Op, ScanEmit, ScanRole};
5610 // Every other field held EQUAL — n_carries is the only axis that moves.
5611 let mk = |n_carries: usize| {
5612 op_key(&Op::Scan {
5613 n_carries,
5614 n_xs: 2,
5615 bound: 3,
5616 emit: ScanEmit::All,
5617 early_exit: None,
5618 })
5619 };
5620 let one = mk(1);
5621 assert!(one.is_some(), "Op::Scan must produce an op_key, not None");
5622 for n in [2usize, 3, 7] {
5623 assert_ne!(
5624 mk(n),
5625 one,
5626 "n_carries={n} must not key identically to n_carries=1 (all other fields held equal)"
5627 );
5628 }
5629 // ...and distinct counts stay distinct from each OTHER, not merely from 1.
5630 assert_ne!(mk(2), mk(3), "distinct carry counts must key distinctly");
5631
5632 // The SIBLING claim, asserted rather than only commented: the placeholder
5633 // arm's own doc says "Carry/0, Elem/0, Carry/1 are all distinct in the
5634 // body hash". It had no test. It does now.
5635 let c0 = op_key(&Op::ScanPlaceholder {
5636 role: ScanRole::Carry,
5637 index: 0,
5638 });
5639 let c1 = op_key(&Op::ScanPlaceholder {
5640 role: ScanRole::Carry,
5641 index: 1,
5642 });
5643 let e0 = op_key(&Op::ScanPlaceholder {
5644 role: ScanRole::Elem,
5645 index: 0,
5646 });
5647 assert!(c0.is_some(), "ScanPlaceholder must produce an op_key");
5648 assert_ne!(c0, c1, "Carry/0 vs Carry/1 must differ in the body hash");
5649 assert_ne!(c0, e0, "Carry/0 vs Elem/0 must differ in the body hash");
5650 }
5651
5652 #[test]
5653 fn scan_emit_and_placeholder_role_participate_in_op_key() {
5654 use crate::{Op, ScanEmit, ScanRole};
5655 // emit=All vs emit=Final differ.
5656 let all = op_key(&Op::Scan {
5657 n_carries: 1,
5658 n_xs: 0,
5659 bound: 3,
5660 emit: ScanEmit::All,
5661 early_exit: None,
5662 });
5663 let fin = op_key(&Op::Scan {
5664 n_carries: 1,
5665 n_xs: 0,
5666 bound: 3,
5667 emit: ScanEmit::Final,
5668 early_exit: None,
5669 });
5670 assert!(
5671 all.is_some() && fin.is_some(),
5672 "Op::Scan must produce an op_key, not None"
5673 );
5674 assert_ne!(all, fin, "emit=All vs emit=Final must differ in op_key");
5675 // n_xs / bound participate.
5676 assert_ne!(
5677 op_key(&Op::Scan {
5678 n_carries: 1,
5679 n_xs: 1,
5680 bound: 3,
5681 emit: ScanEmit::All,
5682 early_exit: None
5683 }),
5684 all
5685 );
5686 assert_ne!(
5687 op_key(&Op::Scan {
5688 n_carries: 1,
5689 n_xs: 0,
5690 bound: 4,
5691 emit: ScanEmit::All,
5692 early_exit: None
5693 }),
5694 all
5695 );
5696 // ScanPlaceholder Carry/0 vs Elem/0 vs Carry/1 all differ.
5697 let c0 = op_key(&Op::ScanPlaceholder {
5698 role: ScanRole::Carry,
5699 index: 0,
5700 });
5701 let e0 = op_key(&Op::ScanPlaceholder {
5702 role: ScanRole::Elem,
5703 index: 0,
5704 });
5705 let c1 = op_key(&Op::ScanPlaceholder {
5706 role: ScanRole::Carry,
5707 index: 1,
5708 });
5709 assert!(c0.is_some());
5710 assert_ne!(c0, e0, "Carry vs Elem must differ");
5711 assert_ne!(c0, c1, "index must participate");
5712 }
5713
5714 /// G2 (2026-06-20): FlashAttn IS decomposable — the vanilla (non-causal,
5715 /// MHA) case lowers to its materialized scaled-dot-product-attention
5716 /// subgraph. Born-red before the fix (`flash_attn::decompose` panicked).
5717 #[test]
5718 fn flash_attn_vanilla_decomposes_to_sdpa() {
5719 let s = Shape::from_dims(&[1, 1, 1, 1]);
5720 let q = NodeHandle::from_f32(vec![0.0_f32; 1], s.clone(), cpu_dev()).unwrap();
5721 let k = q.const_f32_like(vec![0.0_f32; 1], s.clone()).unwrap();
5722 let v = q.const_f32_like(vec![0.0_f32; 1], s.clone()).unwrap();
5723 // Vanilla: non-causal, Hq==Hkv==1, no alibi/window/softcap.
5724 let attn = q.flash_attn(&k, &v, None, 1.0_f32, false, None, None, None);
5725 let graph = attn.graph().clone();
5726
5727 let new_roots = RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[attn.id()]);
5728 assert_eq!(new_roots.len(), 1);
5729 let root = new_roots[0];
5730 let g = graph.read().unwrap();
5731 // The fused FlashAttn is gone from the root, replaced by the SDPA
5732 // subgraph — which contains MatMul nodes.
5733 assert!(
5734 !matches!(g.node(root).op, Op::Fused(fid, _) if fid == crate::registry::FusedOps::FLASH_ATTN),
5735 "vanilla FlashAttn must decompose, not stay fused",
5736 );
5737 let has_matmul = (0..g.len()).any(|i| matches!(g.node(NodeId(i)).op, Op::MatMul));
5738 assert!(has_matmul, "decomposed FlashAttn must contain a MatMul");
5739 }
5740
5741 /// G2: causal FlashAttn decomposes too — the causal mask is a `Ge` predicate (built from `Iota` alone) under a
5742 /// `MaskedFill(-inf)` SELECT, never an additive band (PIP #715 M1: `score + -inf` turns a masked-out NaN or
5743 /// +inf score into NaN), so the node lowers rather than staying fused. (The decomposed *numerics* are
5744 /// verified separately by a parity test vs. the reference attention and by the masked-out non-finite cases.)
5745 #[test]
5746 fn flash_attn_causal_decomposes_with_a_select_mask() {
5747 let s = Shape::from_dims(&[1, 1, 2, 1]); // Sq=Sk=2 so the mask is non-trivial
5748 let q = NodeHandle::from_f32(vec![0.0_f32; 2], s.clone(), cpu_dev()).unwrap();
5749 let k = q.const_f32_like(vec![0.0_f32; 2], s.clone()).unwrap();
5750 let v = q.const_f32_like(vec![0.0_f32; 2], s.clone()).unwrap();
5751 let attn = q.flash_attn(&k, &v, None, 1.0_f32, true, None, None, None); // causal
5752 let graph = attn.graph().clone();
5753
5754 let new_roots = RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[attn.id()]);
5755 assert_eq!(new_roots.len(), 1);
5756 let root = new_roots[0];
5757 let g = graph.read().unwrap();
5758 assert!(
5759 !matches!(g.node(root).op, Op::Fused(fid, _) if fid == crate::registry::FusedOps::FLASH_ATTN),
5760 "causal FlashAttn must decompose (select mask), not stay fused",
5761 );
5762 let has = |pred: &dyn Fn(&Op) -> bool| (0..g.len()).any(|i| pred(&g.node(NodeId(i)).op));
5763 assert!(
5764 has(&|o| matches!(o, Op::Ge)),
5765 "causal decomposition must contain a Ge mask predicate"
5766 );
5767 assert!(
5768 has(&|o| matches!(o, Op::MaskedFill { .. })),
5769 "causal decomposition must contain a MaskedFill select"
5770 );
5771 // The retired additive form: a Triu band summed into the scores.
5772 assert!(
5773 !has(&|o| matches!(o, Op::Triu { .. })),
5774 "the mask must not be an additive Triu band (a masked-out NaN/inf score would reach the softmax)"
5775 );
5776 }
5777
5778 /// Fuse rule does not fire on a non-canonical Div pattern (e.g.,
5779 /// a plain `a / b` with no upstream softmax structure).
5780 #[test]
5781 fn fuse_rule_does_not_fire_on_plain_div() {
5782 let a = NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
5783 let b = a
5784 .const_f32_like(vec![2.0_f32; 4], Shape::from_dims(&[4]))
5785 .unwrap();
5786 let c = a.div(&b);
5787 let graph = c.graph().clone();
5788 let pre_len = graph.read().unwrap().len();
5789 let new_roots = RuleRegistry::new()
5790 .with_rule(Box::new(FusionRule::from_entry(
5791 &crate::registry::softmax_last_dim::entry(),
5792 )))
5793 .optimize_to_fixpoint(&graph, &[c.id()]);
5794 assert_eq!(new_roots, vec![c.id()]);
5795 assert_eq!(graph.read().unwrap().len(), pre_len);
5796 }
5797
5798 // -------- Cast-fusion rule -------------------------------------------
5799
5800 /// Build a "yes to everything" capability predicate. Useful when
5801 /// the test wants to confirm the matcher/rewriter mechanics work;
5802 /// orthogonal tests cover the predicate-says-no path.
5803 fn allow_all_predicate() -> CapabilityPredicate {
5804 Arc::new(|_op: &Op, _dtypes: &[fuel_ir::DType]| true)
5805 }
5806
5807 /// Predicate that says no for everything. Useful for confirming
5808 /// the rule respects the capability gate.
5809 fn deny_all_predicate() -> CapabilityPredicate {
5810 Arc::new(|_op: &Op, _dtypes: &[fuel_ir::DType]| false)
5811 }
5812
5813 /// Happy path: `x:f32 → Cast(BF16) → Neg(BF16)` collapses to
5814 /// `x:f32 → Neg(f32)` when the predicate says Neg supports f32.
5815 #[test]
5816 fn cast_fusion_drops_cast_when_consumer_supports_source_dtype() {
5817 let x = NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
5818 let xc = x.cast(fuel_ir::DType::BF16);
5819 let y = xc.neg();
5820 let graph = y.graph().clone();
5821 let pre_len = graph.read().unwrap().len();
5822
5823 let registry =
5824 RuleRegistry::new().with_rule(Box::new(CastFusionRule::new(allow_all_predicate())));
5825 let new_roots = registry.optimize_to_fixpoint(&graph, &[y.id()]);
5826 assert_eq!(new_roots.len(), 1);
5827 let new_root = new_roots[0];
5828
5829 let g = graph.read().unwrap();
5830 // The new root is a fresh Neg whose input is the original
5831 // f32 Const x, not the Cast.
5832 assert!(matches!(g.node(new_root).op, Op::Neg));
5833 assert_eq!(g.node(new_root).inputs, vec![x.id()]);
5834 // Cast node remains in the arena but is no longer reachable
5835 // from the new root.
5836 let reachable = topo_order_multi(&g, &[new_root]);
5837 assert!(
5838 !reachable
5839 .iter()
5840 .any(|&n| matches!(g.node(n).op, Op::Cast(_))),
5841 "no Cast node should be reachable post-fusion"
5842 );
5843 // One new Neg node was appended; the original Neg + Cast are
5844 // unreachable but still in the arena.
5845 assert!(g.len() > pre_len);
5846 }
5847
5848 /// Capability gate: when the predicate says no, the rule must
5849 /// not fire. Graph structure is unchanged.
5850 #[test]
5851 fn cast_fusion_no_fire_when_predicate_denies() {
5852 let x = NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
5853 let xc = x.cast(fuel_ir::DType::BF16);
5854 let y = xc.neg();
5855 let graph = y.graph().clone();
5856 let pre_len = graph.read().unwrap().len();
5857
5858 let registry =
5859 RuleRegistry::new().with_rule(Box::new(CastFusionRule::new(deny_all_predicate())));
5860 let new_roots = registry.optimize_to_fixpoint(&graph, &[y.id()]);
5861 assert_eq!(new_roots, vec![y.id()]);
5862 assert_eq!(
5863 graph.read().unwrap().len(),
5864 pre_len,
5865 "predicate-says-no should append no nodes"
5866 );
5867 // The original Cast → Neg chain is intact.
5868 let g = graph.read().unwrap();
5869 assert!(matches!(g.node(y.id()).op, Op::Neg));
5870 assert_eq!(g.node(y.id()).inputs, vec![xc.id()]);
5871 assert!(matches!(g.node(xc.id()).op, Op::Cast(_)));
5872 }
5873
5874 /// Single-consumer constraint: if the Cast feeds two consumers,
5875 /// the rule must not fire (eliminating the cast for one consumer
5876 /// would orphan it for the other).
5877 #[test]
5878 fn cast_fusion_no_fire_when_cast_has_multiple_consumers() {
5879 let x = NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
5880 let xc = x.cast(fuel_ir::DType::BF16);
5881 // Two consumers of the same Cast.
5882 let y1 = xc.neg();
5883 let y2 = xc.relu();
5884 let graph = y1.graph().clone();
5885 let pre_len = graph.read().unwrap().len();
5886
5887 let registry =
5888 RuleRegistry::new().with_rule(Box::new(CastFusionRule::new(allow_all_predicate())));
5889 let new_roots = registry.optimize_to_fixpoint(&graph, &[y1.id(), y2.id()]);
5890 // Roots unchanged; cast survives because rule didn't fire.
5891 assert_eq!(new_roots, vec![y1.id(), y2.id()]);
5892 assert_eq!(graph.read().unwrap().len(), pre_len);
5893 let g = graph.read().unwrap();
5894 assert!(matches!(g.node(xc.id()).op, Op::Cast(_)));
5895 }
5896
5897 /// Output dtype tracks the new input: in aggressive mode the
5898 /// rewritten consumer's output dtype is the cast-source dtype,
5899 /// not the original consumer's output dtype. Downstream
5900 /// consumers reading from the rewritten node will see the new
5901 /// dtype — by design (see module docstring's
5902 /// aggressive-semantics caveat).
5903 #[test]
5904 fn cast_fusion_rewrites_output_dtype_to_source_dtype() {
5905 let x = NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
5906 let xc = x.cast(fuel_ir::DType::BF16);
5907 let y = xc.neg();
5908 // Pre-fusion the original Neg produces BF16.
5909 assert_eq!(y.dtype(), fuel_ir::DType::BF16);
5910
5911 let graph = y.graph().clone();
5912 let registry =
5913 RuleRegistry::new().with_rule(Box::new(CastFusionRule::new(allow_all_predicate())));
5914 let new_roots = registry.optimize_to_fixpoint(&graph, &[y.id()]);
5915 let new_root = new_roots[0];
5916
5917 let g = graph.read().unwrap();
5918 // The rewritten Neg consumes the F32 source directly and
5919 // produces F32. This differs from the original BF16
5920 // output; the rule's aggressive semantics commit to this.
5921 assert_eq!(g.node(new_root).dtype, fuel_ir::DType::F32);
5922 }
5923
5924 /// Multi-input op: only the qualifying input fuses; the others
5925 /// are left alone.
5926 #[test]
5927 fn cast_fusion_multi_input_op_fuses_only_qualifying_edge() {
5928 let a = NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
5929 // a:f32 → Cast(BF16) → Add(bf16, b:bf16) where b is already bf16.
5930 let ac = a.cast(fuel_ir::DType::BF16);
5931 let b = a
5932 .const_bf16_like(vec![half::bf16::from_f32(2.0); 4], Shape::from_dims(&[4]))
5933 .unwrap();
5934 let sum = ac.add(&b);
5935 let graph = sum.graph().clone();
5936
5937 // Build a predicate that says yes only for Add[f32, bf16, bf16].
5938 // (Realistic kernels typically wouldn't have mixed-dtype Add;
5939 // this isolates the matcher's per-input behavior. If the
5940 // predicate said no, the rule wouldn't fire and `b` would
5941 // stay paired with the Cast.)
5942 let predicate: CapabilityPredicate =
5943 Arc::new(|op: &Op, _dtypes: &[fuel_ir::DType]| matches!(op, Op::Add));
5944
5945 let registry = RuleRegistry::new().with_rule(Box::new(CastFusionRule::new(predicate)));
5946 let new_roots = registry.optimize_to_fixpoint(&graph, &[sum.id()]);
5947 let new_root = new_roots[0];
5948
5949 let g = graph.read().unwrap();
5950 assert!(matches!(g.node(new_root).op, Op::Add));
5951 // First input of new Add: the original f32 const (cast eliminated).
5952 // Second input: still `b` (a bf16 const, no cast was there).
5953 assert_eq!(g.node(new_root).inputs, vec![a.id(), b.id()]);
5954 }
5955
5956 /// Chained casts: `x:f32 → Cast(BF16) → Cast(F32) → Op` should
5957 /// reduce to `x:f32 → Op` via the fixpoint loop firing the rule
5958 /// twice (once per consumer-side cast).
5959 #[test]
5960 fn cast_fusion_handles_chained_casts_via_fixpoint() {
5961 let x = NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
5962 let x_bf16 = x.cast(fuel_ir::DType::BF16);
5963 let x_f32 = x_bf16.cast(fuel_ir::DType::F32);
5964 let y = x_f32.neg();
5965 let graph = y.graph().clone();
5966
5967 let registry =
5968 RuleRegistry::new().with_rule(Box::new(CastFusionRule::new(allow_all_predicate())));
5969 let new_roots = registry.optimize_to_fixpoint(&graph, &[y.id()]);
5970 let new_root = new_roots[0];
5971
5972 let g = graph.read().unwrap();
5973 // After two iterations: the outer Cast is gone (Neg consumes
5974 // x_bf16 directly), then the inner Cast is gone (Neg consumes
5975 // x directly). No Cast nodes are reachable.
5976 let reachable = topo_order_multi(&g, &[new_root]);
5977 let cast_count = reachable
5978 .iter()
5979 .filter(|&&n| matches!(g.node(n).op, Op::Cast(_)))
5980 .count();
5981 assert_eq!(
5982 cast_count, 0,
5983 "fixpoint should eliminate both casts in the chain"
5984 );
5985 assert!(matches!(g.node(new_root).op, Op::Neg));
5986 assert_eq!(g.node(new_root).inputs, vec![x.id()]);
5987 }
5988
5989 /// The rule must not fire on the Cast node itself — only on the
5990 /// consumer of a Cast.
5991 #[test]
5992 fn cast_fusion_does_not_fire_on_cast_node_itself() {
5993 let x = NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
5994 let xc = x.cast(fuel_ir::DType::BF16);
5995 let graph = xc.graph().clone();
5996 let pre_len = graph.read().unwrap().len();
5997
5998 let registry =
5999 RuleRegistry::new().with_rule(Box::new(CastFusionRule::new(allow_all_predicate())));
6000 // Root the optimizer at the Cast itself. The rule should look
6001 // at the Cast and decline (it's not the consumer's role).
6002 let new_roots = registry.optimize_to_fixpoint(&graph, &[xc.id()]);
6003 assert_eq!(new_roots, vec![xc.id()]);
6004 assert_eq!(graph.read().unwrap().len(), pre_len);
6005 }
6006
6007 // ===== Phase 2.1: insert_cross_device_copies tests =====
6008
6009 use std::collections::HashMap as StdHashMap;
6010
6011 fn add_node(g: &mut Graph, op: Op, inputs: Vec<NodeId>) -> NodeId {
6012 g.push(Node {
6013 op,
6014 inputs,
6015 shape: Shape::from_dims(&[4]),
6016 dtype: DType::F32,
6017 })
6018 }
6019
6020 /// Snapshot every node's `Graph::placement` into an external
6021 /// map. Needed because `&mut Graph` and `|id| g.placement(id)`
6022 /// closure can't co-exist (overlapping borrows). The closure-
6023 /// based oracle is the production shape (the picker hands in a
6024 /// `Fn(NodeId) -> Option<DeviceLocation>` derived from its own
6025 /// commit map); tests just precompute the snapshot from the
6026 /// graph.
6027 fn snapshot_placements(g: &Graph) -> StdHashMap<NodeId, DeviceLocation> {
6028 let mut m = StdHashMap::new();
6029 for id in 0..g.len() {
6030 let nid = NodeId(id);
6031 if let Some(loc) = g.placement(nid) {
6032 m.insert(nid, loc);
6033 }
6034 }
6035 m
6036 }
6037
6038 fn build_two_node_graph_with_placements(
6039 a: DeviceLocation,
6040 b: DeviceLocation,
6041 ) -> (Graph, NodeId, NodeId) {
6042 let mut g = Graph::new();
6043 let n1 = add_node(&mut g, Op::Const, vec![]);
6044 let n2 = add_node(&mut g, Op::Neg, vec![n1]);
6045 g.set_placement(n1, a);
6046 g.set_placement(n2, b);
6047 (g, n1, n2)
6048 }
6049
6050 fn shares_storage_cpu_devices_only(a: DeviceLocation, b: DeviceLocation) -> bool {
6051 // Test stub topology: CPU shares with CPU only (the AOCL/MKL/
6052 // portable-CPU substrate story). CUDA shares with same-gpu_id
6053 // CUDA. Vulkan shares with same-gpu_id Vulkan. Cross device
6054 // is never shared.
6055 match (a, b) {
6056 (DeviceLocation::Cpu, DeviceLocation::Cpu) => true,
6057 (DeviceLocation::Cuda { gpu_id: x }, DeviceLocation::Cuda { gpu_id: y }) => x == y,
6058 (DeviceLocation::Vulkan { gpu_id: x }, DeviceLocation::Vulkan { gpu_id: y }) => x == y,
6059 (DeviceLocation::Metal { gpu_id: x }, DeviceLocation::Metal { gpu_id: y }) => x == y,
6060 _ => false,
6061 }
6062 }
6063
6064 /// Single-hop everywhere: the pre-two-hop behavior. Every bridged
6065 /// edge gets exactly one `Op::Copy`. Used by the legacy single-hop
6066 /// tests so they stay byte-identical to before the two-hop param.
6067 fn no_host_staging(_a: DeviceLocation, _b: DeviceLocation) -> bool {
6068 false
6069 }
6070
6071 /// Realistic topology predicate: a cross-VENDOR GPU↔GPU pair (CUDA↔
6072 /// Vulkan, or any two distinct GPU substrates) needs host staging
6073 /// (two hops). Any edge touching CPU, or a same-vendor pair, is a
6074 /// single hop.
6075 fn host_staging_cross_vendor_gpu(a: DeviceLocation, b: DeviceLocation) -> bool {
6076 use DeviceLocation::*;
6077 match (a, b) {
6078 // CPU on either end → single hop.
6079 (Cpu, _) | (_, Cpu) => false,
6080 // Same vendor (both CUDA, both Vulkan, both Metal) → single
6081 // hop (the topology can copy directly / shares_storage may
6082 // even short-circuit it first).
6083 (Cuda { .. }, Cuda { .. }) => false,
6084 (Vulkan { .. }, Vulkan { .. }) => false,
6085 (Metal { .. }, Metal { .. }) => false,
6086 // Cross-vendor GPU↔GPU → two hops through host.
6087 _ => true,
6088 }
6089 }
6090
6091 /// No cross-device edges → no copies inserted.
6092 #[test]
6093 fn insert_copies_noop_when_all_same_device() {
6094 let (mut g, _n1, n2) =
6095 build_two_node_graph_with_placements(DeviceLocation::Cpu, DeviceLocation::Cpu);
6096 let pre_len = g.len();
6097 let placements = snapshot_placements(&g);
6098 let inserted = insert_cross_device_copies(
6099 &mut g,
6100 &[n2],
6101 |id| placements.get(&id).copied(),
6102 shares_storage_cpu_devices_only,
6103 no_host_staging,
6104 );
6105 assert_eq!(inserted.len(), 0, "same-device edge → no copy needed");
6106 assert_eq!(g.len(), pre_len, "graph unchanged");
6107 }
6108
6109 /// Cross-device edge (CPU → CUDA) → one `Op::Copy { target: Cuda }`
6110 /// inserted; consumer's input rewired to point at it.
6111 #[test]
6112 fn insert_copies_cuda_consumer_of_cpu_input() {
6113 let cuda = DeviceLocation::Cuda { gpu_id: 0 };
6114 let (mut g, n1, n2) = build_two_node_graph_with_placements(DeviceLocation::Cpu, cuda);
6115 let pre_len = g.len();
6116 let placements = snapshot_placements(&g);
6117 let inserted = insert_cross_device_copies(
6118 &mut g,
6119 &[n2],
6120 |id| placements.get(&id).copied(),
6121 shares_storage_cpu_devices_only,
6122 no_host_staging,
6123 );
6124 assert_eq!(inserted.len(), 1);
6125 assert_eq!(g.len(), pre_len + 1, "one new Op::Copy node appended");
6126 // Consumer's input now points at the new Op::Copy (not n1).
6127 let consumer_inputs = &g.node(n2).inputs;
6128 assert_eq!(consumer_inputs.len(), 1);
6129 let copy_id = consumer_inputs[0];
6130 assert_ne!(copy_id, n1, "consumer's input was rewired");
6131 let copy_node = g.node(copy_id);
6132 assert!(
6133 matches!(copy_node.op, Op::Copy { target } if target == cuda),
6134 "rewired input is Op::Copy targeting CUDA; got {:?}",
6135 copy_node.op,
6136 );
6137 assert_eq!(copy_node.inputs, vec![n1], "Op::Copy reads from n1");
6138 assert_eq!(g.placement(copy_id), Some(cuda), "Op::Copy lands on CUDA");
6139 }
6140
6141 /// Two consumers share an input AND both need it on the same target
6142 /// device → ONE Op::Copy serves both (CSE on inserted copies).
6143 #[test]
6144 fn insert_copies_dedupes_when_two_consumers_share_input_and_target() {
6145 let cuda = DeviceLocation::Cuda { gpu_id: 0 };
6146 let mut g = Graph::new();
6147 let cpu_src = add_node(&mut g, Op::Const, vec![]);
6148 g.set_placement(cpu_src, DeviceLocation::Cpu);
6149 let cuda_a = add_node(&mut g, Op::Neg, vec![cpu_src]);
6150 let cuda_b = add_node(&mut g, Op::Sqr, vec![cpu_src]);
6151 g.set_placement(cuda_a, cuda);
6152 g.set_placement(cuda_b, cuda);
6153
6154 let pre_len = g.len();
6155 let placements = snapshot_placements(&g);
6156 let inserted = insert_cross_device_copies(
6157 &mut g,
6158 &[cuda_a, cuda_b],
6159 |id| placements.get(&id).copied(),
6160 shares_storage_cpu_devices_only,
6161 no_host_staging,
6162 );
6163 assert_eq!(
6164 inserted.len(),
6165 1,
6166 "CSE — one Op::Copy serves both consumers"
6167 );
6168 assert_eq!(g.len(), pre_len + 1);
6169 // Both consumers point at the SAME Op::Copy node.
6170 let a_input = g.node(cuda_a).inputs[0];
6171 let b_input = g.node(cuda_b).inputs[0];
6172 assert_eq!(a_input, b_input, "both consumers share the rewired input");
6173 }
6174
6175 /// Two consumers share an input but want it on DIFFERENT target
6176 /// devices → TWO distinct Op::Copy nodes inserted.
6177 #[test]
6178 fn insert_copies_does_not_dedupe_across_distinct_targets() {
6179 let cuda = DeviceLocation::Cuda { gpu_id: 0 };
6180 let vulkan = DeviceLocation::Vulkan { gpu_id: 0 };
6181 let mut g = Graph::new();
6182 let cpu_src = add_node(&mut g, Op::Const, vec![]);
6183 g.set_placement(cpu_src, DeviceLocation::Cpu);
6184 let cuda_c = add_node(&mut g, Op::Neg, vec![cpu_src]);
6185 let vk_c = add_node(&mut g, Op::Sqr, vec![cpu_src]);
6186 g.set_placement(cuda_c, cuda);
6187 g.set_placement(vk_c, vulkan);
6188
6189 let placements = snapshot_placements(&g);
6190
6191 let inserted = insert_cross_device_copies(
6192 &mut g,
6193 &[cuda_c, vk_c],
6194 |id| placements.get(&id).copied(),
6195 shares_storage_cpu_devices_only,
6196 no_host_staging,
6197 );
6198 assert_eq!(inserted.len(), 2, "distinct targets → distinct copies");
6199 let cuda_input = g.node(cuda_c).inputs[0];
6200 let vk_input = g.node(vk_c).inputs[0];
6201 assert_ne!(cuda_input, vk_input);
6202 }
6203
6204 /// Producer with no placement → pass leaves the edge alone (the
6205 /// executor handles via fallback). Same for consumer with no
6206 /// placement.
6207 #[test]
6208 fn insert_copies_skips_when_placement_absent() {
6209 let mut g = Graph::new();
6210 let n1 = add_node(&mut g, Op::Const, vec![]);
6211 let n2 = add_node(&mut g, Op::Neg, vec![n1]);
6212 // Only consumer has placement; producer doesn't.
6213 g.set_placement(n2, DeviceLocation::Cuda { gpu_id: 0 });
6214 let placements = snapshot_placements(&g);
6215 let inserted = insert_cross_device_copies(
6216 &mut g,
6217 &[n2],
6218 |id| placements.get(&id).copied(),
6219 shares_storage_cpu_devices_only,
6220 no_host_staging,
6221 );
6222 assert_eq!(inserted.len(), 0, "producer with no placement → skip");
6223 }
6224
6225 /// `Op::Copy` and `Op::Move` are themselves transfers — the pass
6226 /// must not try to insert ANOTHER copy on their inputs (would
6227 /// infinite-regress).
6228 #[test]
6229 fn insert_copies_skips_transfer_ops_themselves() {
6230 let cuda = DeviceLocation::Cuda { gpu_id: 0 };
6231 let mut g = Graph::new();
6232 let cpu_src = add_node(&mut g, Op::Const, vec![]);
6233 g.set_placement(cpu_src, DeviceLocation::Cpu);
6234 // A user-authored Op::Copy from CPU to CUDA. Should not be
6235 // re-wrapped.
6236 let copy = g.push(Node {
6237 op: Op::Copy { target: cuda },
6238 inputs: vec![cpu_src],
6239 shape: Shape::from_dims(&[4]),
6240 dtype: DType::F32,
6241 });
6242 g.set_placement(copy, cuda);
6243
6244 let pre_len = g.len();
6245 let placements = snapshot_placements(&g);
6246 let inserted = insert_cross_device_copies(
6247 &mut g,
6248 &[copy],
6249 |id| placements.get(&id).copied(),
6250 shares_storage_cpu_devices_only,
6251 no_host_staging,
6252 );
6253 assert_eq!(inserted.len(), 0, "the existing Op::Copy is not re-wrapped");
6254 assert_eq!(g.len(), pre_len);
6255 }
6256
6257 /// Pass is idempotent — re-running on a graph already rewritten
6258 /// adds zero new copies. Phase 2.1 variant.
6259 #[test]
6260 fn insert_cross_device_copies_idempotent() {
6261 let cuda = DeviceLocation::Cuda { gpu_id: 0 };
6262 let (mut g, _n1, n2) = build_two_node_graph_with_placements(DeviceLocation::Cpu, cuda);
6263 let placements_before = snapshot_placements(&g);
6264 let first = insert_cross_device_copies(
6265 &mut g,
6266 &[n2],
6267 |id| placements_before.get(&id).copied(),
6268 shares_storage_cpu_devices_only,
6269 no_host_staging,
6270 );
6271 let placements_after = snapshot_placements(&g);
6272 let second = insert_cross_device_copies(
6273 &mut g,
6274 &[n2],
6275 |id| placements_after.get(&id).copied(),
6276 shares_storage_cpu_devices_only,
6277 no_host_staging,
6278 );
6279 assert_eq!(first.len(), 1);
6280 assert_eq!(
6281 second.len(),
6282 0,
6283 "re-run sees inserted-Copy as on-target; no new copies"
6284 );
6285 }
6286
6287 /// Cross-GPU edge (CUDA gpu_id 0 → CUDA gpu_id 1) → copy inserted
6288 /// (devices don't share storage even though both are CUDA).
6289 #[test]
6290 fn insert_copies_across_gpu_ids_within_one_backend() {
6291 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
6292 let cuda1 = DeviceLocation::Cuda { gpu_id: 1 };
6293 let (mut g, _n1, n2) = build_two_node_graph_with_placements(cuda0, cuda1);
6294 let placements = snapshot_placements(&g);
6295 let inserted = insert_cross_device_copies(
6296 &mut g,
6297 &[n2],
6298 |id| placements.get(&id).copied(),
6299 shares_storage_cpu_devices_only,
6300 no_host_staging,
6301 );
6302 assert_eq!(inserted.len(), 1, "cross-gpu_id is cross-device too");
6303 let copy_id = g.node(n2).inputs[0];
6304 let copy_node = g.node(copy_id);
6305 assert!(matches!(copy_node.op, Op::Copy { target } if target == cuda1));
6306 }
6307
6308 /// Cross-VENDOR GPU↔GPU edge (Vulkan → CUDA) with `needs_host_staging`
6309 /// returning true → TWO `Op::Copy` hops through a CPU intermediate:
6310 /// the consumer reads `Op::Copy{target:Cuda}`, which reads
6311 /// `Op::Copy{target:Cpu}`, which reads the Vulkan producer.
6312 #[test]
6313 fn insert_copies_cross_vendor_gpu_inserts_two_hops_through_cpu() {
6314 let cuda = DeviceLocation::Cuda { gpu_id: 0 };
6315 let vulkan = DeviceLocation::Vulkan { gpu_id: 0 };
6316 let (mut g, vk_src, cuda_consumer) = build_two_node_graph_with_placements(vulkan, cuda);
6317 let pre_len = g.len();
6318 let placements = snapshot_placements(&g);
6319 let inserted = insert_cross_device_copies(
6320 &mut g,
6321 &[cuda_consumer],
6322 |id| placements.get(&id).copied(),
6323 shares_storage_cpu_devices_only,
6324 host_staging_cross_vendor_gpu,
6325 );
6326 assert_eq!(inserted.len(), 2, "cross-vendor GPU↔GPU → two hops");
6327 assert_eq!(g.len(), pre_len + 2, "two new Op::Copy nodes appended");
6328
6329 // Consumer reads the consumer-side hop (Copy → Cuda).
6330 let hop2 = g.node(cuda_consumer).inputs[0];
6331 let hop2_node = g.node(hop2);
6332 assert!(
6333 matches!(hop2_node.op, Op::Copy { target } if target == cuda),
6334 "consumer-side hop targets CUDA; got {:?}",
6335 hop2_node.op,
6336 );
6337 assert_eq!(
6338 g.placement(hop2),
6339 Some(cuda),
6340 "consumer-side hop lands on CUDA"
6341 );
6342
6343 // The consumer-side hop reads the CPU intermediate (Copy → Cpu).
6344 let hop1 = hop2_node.inputs[0];
6345 let hop1_node = g.node(hop1);
6346 assert!(
6347 matches!(hop1_node.op, Op::Copy { target } if target == DeviceLocation::Cpu),
6348 "CPU-intermediate hop targets Cpu; got {:?}",
6349 hop1_node.op,
6350 );
6351 assert_eq!(
6352 g.placement(hop1),
6353 Some(DeviceLocation::Cpu),
6354 "CPU intermediate is placed on CPU",
6355 );
6356
6357 // The CPU intermediate reads the original Vulkan producer.
6358 assert_eq!(
6359 hop1_node.inputs,
6360 vec![vk_src],
6361 "CPU hop reads the Vulkan producer"
6362 );
6363 }
6364
6365 /// Two-hop edge is idempotent: re-running adds zero new copies. The
6366 /// consumer now reads a same-device `Op::Copy`; the CPU intermediate's
6367 /// consumer is also an `Op::Copy` (skipped as a transfer op).
6368 #[test]
6369 fn insert_copies_cross_vendor_two_hop_idempotent() {
6370 let cuda = DeviceLocation::Cuda { gpu_id: 0 };
6371 let vulkan = DeviceLocation::Vulkan { gpu_id: 0 };
6372 let (mut g, _vk_src, cuda_consumer) = build_two_node_graph_with_placements(vulkan, cuda);
6373 let p1 = snapshot_placements(&g);
6374 let first = insert_cross_device_copies(
6375 &mut g,
6376 &[cuda_consumer],
6377 |id| p1.get(&id).copied(),
6378 shares_storage_cpu_devices_only,
6379 host_staging_cross_vendor_gpu,
6380 );
6381 let p2 = snapshot_placements(&g);
6382 let second = insert_cross_device_copies(
6383 &mut g,
6384 &[cuda_consumer],
6385 |id| p2.get(&id).copied(),
6386 shares_storage_cpu_devices_only,
6387 host_staging_cross_vendor_gpu,
6388 );
6389 assert_eq!(first.len(), 2, "two hops on first run");
6390 assert_eq!(second.len(), 0, "re-run adds no new copies");
6391 }
6392
6393 /// CSE on a two-hop edge: one Vulkan producer feeding TWO CUDA
6394 /// consumers stages to CPU exactly once (one CPU intermediate), then
6395 /// one consumer-side CUDA hop shared by both → 2 inserted copies
6396 /// total, not 4.
6397 #[test]
6398 fn insert_copies_cross_vendor_two_hop_cse_shares_cpu_intermediate() {
6399 let cuda = DeviceLocation::Cuda { gpu_id: 0 };
6400 let vulkan = DeviceLocation::Vulkan { gpu_id: 0 };
6401 let mut g = Graph::new();
6402 let vk_src = add_node(&mut g, Op::Const, vec![]);
6403 g.set_placement(vk_src, vulkan);
6404 let cuda_a = add_node(&mut g, Op::Neg, vec![vk_src]);
6405 let cuda_b = add_node(&mut g, Op::Sqr, vec![vk_src]);
6406 g.set_placement(cuda_a, cuda);
6407 g.set_placement(cuda_b, cuda);
6408
6409 let placements = snapshot_placements(&g);
6410 let inserted = insert_cross_device_copies(
6411 &mut g,
6412 &[cuda_a, cuda_b],
6413 |id| placements.get(&id).copied(),
6414 shares_storage_cpu_devices_only,
6415 host_staging_cross_vendor_gpu,
6416 );
6417 // One CPU intermediate + one shared CUDA hop = 2.
6418 assert_eq!(
6419 inserted.len(),
6420 2,
6421 "CSE — one CPU intermediate + one CUDA hop"
6422 );
6423 let a_input = g.node(cuda_a).inputs[0];
6424 let b_input = g.node(cuda_b).inputs[0];
6425 assert_eq!(
6426 a_input, b_input,
6427 "both CUDA consumers share the consumer-side hop"
6428 );
6429 // That shared hop reads the single CPU intermediate.
6430 let cpu_hop = g.node(a_input).inputs[0];
6431 assert!(matches!(
6432 g.node(cpu_hop).op,
6433 Op::Copy {
6434 target: DeviceLocation::Cpu
6435 }
6436 ));
6437 assert_eq!(g.node(cpu_hop).inputs, vec![vk_src]);
6438 }
6439
6440 /// A CPU↔GPU edge stays SINGLE hop even when the host-staging
6441 /// predicate is the realistic cross-vendor one (which returns false
6442 /// for any CPU-touching edge) — byte-identical to the legacy path.
6443 #[test]
6444 fn insert_copies_cpu_gpu_edge_stays_single_hop_under_cross_vendor_predicate() {
6445 let cuda = DeviceLocation::Cuda { gpu_id: 0 };
6446 let (mut g, n1, n2) = build_two_node_graph_with_placements(DeviceLocation::Cpu, cuda);
6447 let pre_len = g.len();
6448 let placements = snapshot_placements(&g);
6449 let inserted = insert_cross_device_copies(
6450 &mut g,
6451 &[n2],
6452 |id| placements.get(&id).copied(),
6453 shares_storage_cpu_devices_only,
6454 host_staging_cross_vendor_gpu,
6455 );
6456 assert_eq!(inserted.len(), 1, "CPU↔CUDA is a single hop");
6457 assert_eq!(g.len(), pre_len + 1);
6458 let copy_id = g.node(n2).inputs[0];
6459 assert!(matches!(g.node(copy_id).op, Op::Copy { target } if target == cuda));
6460 assert_eq!(g.node(copy_id).inputs, vec![n1]);
6461 }
6462
6463 /// Per-node `placement_for` can be backed by an external map, not
6464 /// just `Graph::placement`. Smoke test of the closure shape.
6465 #[test]
6466 fn insert_copies_takes_external_placement_oracle() {
6467 let cuda = DeviceLocation::Cuda { gpu_id: 0 };
6468 let (mut g, n1, n2) = build_two_node_graph_with_placements(DeviceLocation::Cpu, cuda);
6469 // Clear graph-side placements; back the oracle with an
6470 // external map instead.
6471 let mut external: StdHashMap<NodeId, DeviceLocation> = StdHashMap::new();
6472 external.insert(n1, DeviceLocation::Cpu);
6473 external.insert(n2, cuda);
6474 // Strip graph-side placements so we PROVE the closure is the
6475 // authoritative source.
6476 // (No public setter to clear; instead override by leaving
6477 // graph.placement untouched and using only the external map.)
6478 let _placements = snapshot_placements(&g);
6479 let inserted = insert_cross_device_copies(
6480 &mut g,
6481 &[n2],
6482 |id| external.get(&id).copied(),
6483 shares_storage_cpu_devices_only,
6484 no_host_staging,
6485 );
6486 assert_eq!(inserted.len(), 1);
6487 }
6488
6489 // ===== Phase 2.2 — insert_layout_fixups =====
6490
6491 fn count_contiguize_nodes(graph: &SharedGraph) -> usize {
6492 let g = graph.read().unwrap();
6493 (0..g.len())
6494 .filter(|i| matches!(g.node(NodeId(*i)).op, Op::Contiguize))
6495 .count()
6496 }
6497
6498 /// All-contiguous-input graph: pass adds nothing regardless of
6499 /// the kernel_accepts_strided predicate.
6500 #[test]
6501 fn insert_fixups_no_strided_inputs_no_fixups() {
6502 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
6503 let b = a
6504 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
6505 .unwrap();
6506 let c = a.add(&b);
6507 let graph = c.graph().clone();
6508
6509 let before = count_contiguize_nodes(&graph);
6510 let inserted = {
6511 let mut g = graph.write().unwrap();
6512 insert_layout_fixups(&mut g, &[c.id()], |_| false)
6513 };
6514 assert_eq!(inserted, 0);
6515 assert_eq!(count_contiguize_nodes(&graph), before);
6516 }
6517
6518 /// Strided input (Transpose) feeding a kernel that rejects
6519 /// strided: one Contiguize gets inserted between them and the
6520 /// consumer's input gets rewired.
6521 #[test]
6522 fn insert_fixups_strided_input_rejecting_kernel_inserts_contiguize() {
6523 // 2x3 const, transpose to 3x2, then "consumer" reads the
6524 // transposed view. The consumer kernel claims it can't
6525 // handle strided.
6526 let a = NodeHandle::from_f32(
6527 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
6528 Shape::from_dims(&[2, 3]),
6529 cpu_dev(),
6530 )
6531 .unwrap();
6532 // Transpose produces a strided view via the layout side-table.
6533 let at = a.transpose();
6534 // A binary op as our "consumer" (Op::Add is kernel-bearing,
6535 // not a view op).
6536 let b = at
6537 .const_f32_like(vec![0.0; 6], Shape::from_dims(&[3, 2]))
6538 .unwrap();
6539 let c = at.add(&b);
6540 let graph = c.graph().clone();
6541
6542 let before = count_contiguize_nodes(&graph);
6543 let inserted = {
6544 let mut g = graph.write().unwrap();
6545 // Kernel rejects strided for every node.
6546 insert_layout_fixups(&mut g, &[c.id()], |_| false)
6547 };
6548 // One Contiguize for the transposed input of `c`. (`b` is a
6549 // contiguous Const → no fixup.)
6550 assert_eq!(inserted, 1);
6551 assert_eq!(count_contiguize_nodes(&graph) - before, 1);
6552
6553 // c's first input was `at`; after rewrite it should point
6554 // to the new Op::Contiguize node.
6555 let g = graph.read().unwrap();
6556 let c_node = g.node(c.id());
6557 let new_input = g.node(c_node.inputs[0]);
6558 assert!(
6559 matches!(new_input.op, Op::Contiguize),
6560 "consumer's strided input must be rewired through Op::Contiguize, \
6561 got {:?}",
6562 new_input.op,
6563 );
6564 // The Contiguize's input is the original transposed view.
6565 assert_eq!(new_input.inputs, vec![at.id()]);
6566 }
6567
6568 /// Strided input feeding a kernel that accepts strided: pass
6569 /// skips the input, no Contiguize inserted.
6570 #[test]
6571 fn insert_fixups_strided_input_accepting_kernel_no_fixup() {
6572 let a = NodeHandle::from_f32(
6573 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
6574 Shape::from_dims(&[2, 3]),
6575 cpu_dev(),
6576 )
6577 .unwrap();
6578 let at = a.transpose();
6579 let b = at
6580 .const_f32_like(vec![0.0; 6], Shape::from_dims(&[3, 2]))
6581 .unwrap();
6582 let c = at.add(&b);
6583 let graph = c.graph().clone();
6584
6585 let before = count_contiguize_nodes(&graph);
6586 let inserted = {
6587 let mut g = graph.write().unwrap();
6588 // Every kernel accepts strided — no fixup.
6589 insert_layout_fixups(&mut g, &[c.id()], |_| true)
6590 };
6591 assert_eq!(inserted, 0);
6592 assert_eq!(count_contiguize_nodes(&graph), before);
6593 }
6594
6595 /// CSE: two non-strided-tolerant consumers reading the same
6596 /// transposed view share one inserted Contiguize node.
6597 #[test]
6598 fn insert_fixups_cse_dedupes_shared_strided_input() {
6599 let a = NodeHandle::from_f32(
6600 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
6601 Shape::from_dims(&[2, 3]),
6602 cpu_dev(),
6603 )
6604 .unwrap();
6605 let at = a.transpose();
6606 // Two consumers of the same transposed view.
6607 let b = at
6608 .const_f32_like(vec![0.0; 6], Shape::from_dims(&[3, 2]))
6609 .unwrap();
6610 let c1 = at.add(&b);
6611 let c2 = at.mul(&b);
6612 let graph = c1.graph().clone();
6613
6614 let inserted = {
6615 let mut g = graph.write().unwrap();
6616 insert_layout_fixups(&mut g, &[c1.id(), c2.id()], |_| false)
6617 };
6618 // Exactly ONE Contiguize, shared between the two consumers.
6619 assert_eq!(inserted, 1);
6620
6621 let g = graph.read().unwrap();
6622 let c1_input = g.node(c1.id()).inputs[0];
6623 let c2_input = g.node(c2.id()).inputs[0];
6624 assert_eq!(
6625 c1_input, c2_input,
6626 "CSE: both consumers must share the same Contiguize node",
6627 );
6628 assert!(matches!(g.node(c1_input).op, Op::Contiguize));
6629 }
6630
6631 /// Idempotency: running the pass twice on the same graph adds
6632 /// 0 new nodes the second time.
6633 #[test]
6634 fn insert_fixups_idempotent() {
6635 let a = NodeHandle::from_f32(
6636 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
6637 Shape::from_dims(&[2, 3]),
6638 cpu_dev(),
6639 )
6640 .unwrap();
6641 let at = a.transpose();
6642 let b = at
6643 .const_f32_like(vec![0.0; 6], Shape::from_dims(&[3, 2]))
6644 .unwrap();
6645 let c = at.add(&b);
6646 let graph = c.graph().clone();
6647
6648 let first = {
6649 let mut g = graph.write().unwrap();
6650 insert_layout_fixups(&mut g, &[c.id()], |_| false)
6651 };
6652 assert_eq!(first, 1, "first run inserts one Contiguize");
6653
6654 let second = {
6655 let mut g = graph.write().unwrap();
6656 insert_layout_fixups(&mut g, &[c.id()], |_| false)
6657 };
6658 assert_eq!(second, 0, "second run is a no-op");
6659 }
6660
6661 /// View ops in the consumer position do NOT get Contiguize
6662 /// inserted before them — they preserve strided layouts
6663 /// intentionally as part of their semantics.
6664 #[test]
6665 fn insert_fixups_skips_view_op_consumers() {
6666 let a = NodeHandle::from_f32(
6667 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
6668 Shape::from_dims(&[2, 3]),
6669 cpu_dev(),
6670 )
6671 .unwrap();
6672 let at = a.transpose();
6673 // Permute on a transposed view: both are view ops, the
6674 // strided layout flows through unchanged.
6675 let ap = at.permute(&[1, 0]);
6676 let graph = ap.graph().clone();
6677
6678 let inserted = {
6679 let mut g = graph.write().unwrap();
6680 insert_layout_fixups(&mut g, &[ap.id()], |_| false)
6681 };
6682 assert_eq!(
6683 inserted, 0,
6684 "view ops preserve strided layouts; no Contiguize should be inserted",
6685 );
6686 }
6687}
6688
6689#[cfg(test)]
6690mod lower_selected_tests {
6691 use super::*;
6692 use crate::registry::{FusedOpParams, FusedOps};
6693 use fuel_ir::Shape;
6694
6695 /// `[q, k_cache, v_cache, block_table, context_lens]` consts, one fused PAGED_ATTN over them and
6696 /// one `Contiguize` consumer. Returns `(graph, fused, consumer)`.
6697 fn graph_with_paged_attn() -> (Graph, NodeId, NodeId) {
6698 let mut g = Graph::new();
6699 let mut leaf = |dims: &[usize], dtype: DType| {
6700 g.push(Node {
6701 op: Op::Const,
6702 inputs: vec![],
6703 shape: Shape::from_dims(dims),
6704 dtype,
6705 })
6706 };
6707 let q = leaf(&[1, 2, 1, 4], DType::F32);
6708 let kc = leaf(&[3, 2, 2, 4], DType::F32);
6709 let vc = leaf(&[3, 2, 2, 4], DType::F32);
6710 let bt = leaf(&[1, 2], DType::U32);
6711 let cl = leaf(&[1], DType::U32);
6712 let fused = g.push(Node {
6713 op: Op::Fused(
6714 FusedOps::PAGED_ATTN,
6715 FusedOpParams::PagedAttn {
6716 softmax_scale: 0.5,
6717 block_size: 2,
6718 softcap: None,
6719 },
6720 ),
6721 inputs: vec![q, kc, vc, bt, cl],
6722 shape: Shape::from_dims(&[1, 2, 1, 4]),
6723 dtype: DType::F32,
6724 });
6725 let consumer = g.push(Node {
6726 op: Op::Contiguize,
6727 inputs: vec![fused],
6728 shape: Shape::from_dims(&[1, 2, 1, 4]),
6729 dtype: DType::F32,
6730 });
6731 (g, fused, consumer)
6732 }
6733
6734 fn reachable_fused(g: &Graph, roots: &[NodeId]) -> usize {
6735 topo_order_multi(g, roots)
6736 .into_iter()
6737 .filter(|&n| matches!(g.node(n).op, Op::Fused(FusedOps::PAGED_ATTN, _)))
6738 .count()
6739 }
6740
6741 #[test]
6742 fn a_selected_fused_node_is_lowered_and_its_consumer_rewired() {
6743 let (mut g, fused, consumer) = graph_with_paged_attn();
6744 assert_eq!(
6745 reachable_fused(&g, &[consumer]),
6746 1,
6747 "PRECONDITION: one fused node"
6748 );
6749 let n = lower_selected_fused(&mut g, &[consumer], &|_, _| true);
6750 assert_eq!(n, 1);
6751 assert_eq!(
6752 reachable_fused(&g, &[consumer]),
6753 0,
6754 "no fused PAGED_ATTN stays reachable"
6755 );
6756 let new_in = g.node(consumer).inputs[0];
6757 assert_ne!(new_in, fused, "the consumer reads the lowered output");
6758 assert_eq!(
6759 g.node(new_in).shape,
6760 g.node(fused).shape,
6761 "lowering preserves shape"
6762 );
6763 assert_eq!(
6764 g.node(new_in).dtype,
6765 g.node(fused).dtype,
6766 "lowering preserves dtype"
6767 );
6768 }
6769
6770 /// Sabotage sibling: the same call with a predicate that picks nothing changes nothing, so the
6771 /// test above cannot pass because the pass lowers everything unconditionally.
6772 #[test]
6773 fn an_unselected_fused_node_is_left_alone() {
6774 let (mut g, fused, consumer) = graph_with_paged_attn();
6775 let n = lower_selected_fused(&mut g, &[consumer], &|_, _| false);
6776 assert_eq!(n, 0);
6777 assert_eq!(g.node(consumer).inputs[0], fused);
6778 assert_eq!(reachable_fused(&g, &[consumer]), 1);
6779 }
6780
6781 /// Roots are not remapped, so a selected root is skipped rather than lowered into a node the
6782 /// caller does not know about.
6783 #[test]
6784 fn a_selected_root_is_skipped() {
6785 let (mut g, fused, _consumer) = graph_with_paged_attn();
6786 let before = g.len();
6787 let n = lower_selected_fused(&mut g, &[fused], &|_, _| true);
6788 assert_eq!(n, 0);
6789 assert_eq!(g.len(), before, "nothing was pushed");
6790 }
6791}