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