1use std::collections::HashMap;
31
32use fuel_graph::{Graph, NodeId};
33use fuel_ir::dispatch::{OpKind, SizeClass};
34use fuel_ir::probe::BackendId;
35use fuel_ir::{DType, DeviceLocation, Error, Result, Shape};
36
37use smallvec::SmallVec;
38
39use crate::kernel::KernelBindingTable;
40use crate::pipelined::{build_lookup_dtypes, op_to_op_kind};
41use crate::ranker::{
42 AlternativeSet, CapabilitiesLookup, ChainInput, DecisionContext, FilterContext, JudgeOracle,
43 KEEP_PER_DEVICE, PlacementDp, PrecisionRequirement, TransferEstimator, apply_filter_chain,
44 apply_inbound_transfer_costs, composite_ns, compute_static_costs, default_backend_rates,
45 default_chain, enumerate_candidates,
46};
47
48#[derive(Debug)]
57pub struct ExecutionPlan {
58 pub order: Vec<NodeId>,
60 pub alternatives: HashMap<NodeId, AlternativeSet>,
62 pub generation: u64,
73}
74
75impl ExecutionPlan {
76 pub fn empty() -> Self {
78 Self {
79 order: Vec::new(),
80 alternatives: HashMap::new(),
81 generation: 0,
82 }
83 }
84
85 pub fn alternatives(&self, node: NodeId) -> Option<&AlternativeSet> {
88 self.alternatives.get(&node)
89 }
90
91 pub fn alternatives_mut(&mut self, node: NodeId) -> Option<&mut AlternativeSet> {
95 self.alternatives.get_mut(&node)
96 }
97}
98
99pub fn default_device_for(backend: BackendId) -> DeviceLocation {
104 backend.default_location()
105}
106
107pub(crate) fn decision_device_for(
117 graph: &Graph,
118 options: &PlanOptions<'_>,
119 id: NodeId,
120) -> Option<DeviceLocation> {
121 graph
122 .placement(id)
123 .or(options.pinned_device)
124 .or_else(|| graph.target_backend(id).map(default_device_for))
125}
126
127pub(crate) fn candidate_backends_for(
147 graph: &Graph,
148 options: &PlanOptions<'_>,
149 id: NodeId,
150 node: &fuel_graph::Node,
151) -> Vec<BackendId> {
152 let Some(target_device) = decision_device_for(graph, options, id) else {
153 return Vec::new();
154 };
155 let mut backends: Vec<BackendId> = match options.placements_for_device {
156 Some(f) => f(target_device),
157 None => vec![
158 graph
159 .target_backend(id)
160 .unwrap_or_else(|| backend_for_device(target_device)),
161 ],
162 };
163 if node.op.destructive_input().is_none()
168 && let Some(fallback) = options.fallback_placements_for
169 {
170 backends.extend(fallback(target_device).into_iter().map(|(b, _)| b));
171 }
172 let mut unique: Vec<BackendId> = Vec::with_capacity(backends.len());
174 for b in backends {
175 if !unique.contains(&b) {
176 unique.push(b);
177 }
178 }
179 unique
180}
181
182pub fn backend_for_device(loc: DeviceLocation) -> BackendId {
187 loc.backend()
188}
189
190pub struct PlanOptions<'env> {
281 pub precision_requirement: PrecisionRequirement,
284 pub populate_costs: bool,
288 pub placements_for_device: Option<&'env (dyn Fn(DeviceLocation) -> Vec<BackendId> + 'env)>,
291 pub pinned_device: Option<DeviceLocation>,
294 pub fallback_placements_for:
297 Option<&'env (dyn Fn(DeviceLocation) -> Vec<(BackendId, DeviceLocation)> + 'env)>,
298 pub capabilities_for: Option<&'env CapabilitiesLookup<'env>>,
301 pub judge: Option<&'env dyn JudgeOracle>,
307 pub transfer_estimator: Option<&'env dyn TransferEstimator>,
328 pub require_transfer_pricing: bool,
345 pub input_residency: Option<&'env (dyn Fn(NodeId) -> Option<DeviceLocation> + 'env)>,
357 pub reuse_plan: Option<&'env ExecutionPlan>,
374 pub allow_cost_placement: bool,
393 pub device_budget_bytes: Option<usize>,
401 pub device_budget_source: Option<crate::device_budget::BudgetSource>,
405 #[cfg(feature = "telemetry")]
413 pub telemetry: Option<&'env crate::telemetry::TelemetryHooks<'env>>,
414}
415
416impl Default for PlanOptions<'_> {
417 fn default() -> Self {
418 Self {
419 precision_requirement: PrecisionRequirement::default(),
420 populate_costs: true,
421 placements_for_device: None,
422 pinned_device: None,
423 fallback_placements_for: None,
424 capabilities_for: None,
425 judge: None,
426 transfer_estimator: None,
427 require_transfer_pricing: false,
428 input_residency: None,
429 reuse_plan: None,
430 allow_cost_placement: true,
431 device_budget_bytes: None,
432 device_budget_source: None,
433 #[cfg(feature = "telemetry")]
434 telemetry: None,
435 }
436 }
437}
438
439impl<'env> PlanOptions<'env> {
440 pub fn new() -> Self {
442 Self::default()
443 }
444
445 pub fn with_device_budget_bytes(mut self, budget_bytes: usize) -> Self {
447 self.device_budget_bytes = Some(budget_bytes);
448 self
449 }
450
451 pub fn with_resolved_device_budget(
454 mut self,
455 budget: crate::device_budget::ResolvedBudget,
456 ) -> Self {
457 self.device_budget_bytes = Some(budget.bytes);
458 self.device_budget_source = Some(budget.source);
459 self
460 }
461
462 pub fn with_precision_requirement(mut self, req: PrecisionRequirement) -> Self {
464 self.precision_requirement = req;
465 self
466 }
467
468 pub fn without_cost_population(mut self) -> Self {
472 self.populate_costs = false;
473 self
474 }
475
476 pub fn with_placements_for_device(
479 mut self,
480 f: &'env (dyn Fn(DeviceLocation) -> Vec<BackendId> + 'env),
481 ) -> Self {
482 self.placements_for_device = Some(f);
483 self
484 }
485
486 pub fn with_pinned_device(mut self, device: DeviceLocation) -> Self {
491 self.pinned_device = Some(device);
492 self
493 }
494
495 pub fn without_cost_placement(mut self) -> Self {
500 self.allow_cost_placement = false;
501 self
502 }
503
504 pub fn require_transfer_pricing(mut self) -> Self {
512 self.require_transfer_pricing = true;
513 self
514 }
515
516 pub fn with_fallback_placements_for(
525 mut self,
526 f: &'env (dyn Fn(DeviceLocation) -> Vec<(BackendId, DeviceLocation)> + 'env),
527 ) -> Self {
528 self.fallback_placements_for = Some(f);
529 self
530 }
531
532 pub fn with_capabilities_for(mut self, f: &'env CapabilitiesLookup<'env>) -> Self {
535 self.capabilities_for = Some(f);
536 self
537 }
538
539 pub fn with_judge(mut self, judge: &'env dyn JudgeOracle) -> Self {
543 self.judge = Some(judge);
544 self
545 }
546
547 pub fn with_transfer_estimator(mut self, est: &'env dyn TransferEstimator) -> Self {
553 self.transfer_estimator = Some(est);
554 self
555 }
556
557 pub fn with_input_residency(
561 mut self,
562 f: &'env (dyn Fn(NodeId) -> Option<DeviceLocation> + 'env),
563 ) -> Self {
564 self.input_residency = Some(f);
565 self
566 }
567
568 pub fn with_reuse_plan(mut self, base: &'env ExecutionPlan) -> Self {
571 self.reuse_plan = Some(base);
572 self
573 }
574
575 #[cfg(feature = "telemetry")]
581 pub fn with_telemetry(mut self, hooks: &'env crate::telemetry::TelemetryHooks<'env>) -> Self {
582 self.telemetry = Some(hooks);
583 self
584 }
585}
586
587pub fn compile_plan(
670 graph: &Graph,
671 order: &[NodeId],
672 bindings_table: &KernelBindingTable,
673 options: &PlanOptions<'_>,
674) -> Result<ExecutionPlan> {
675 if options.require_transfer_pricing && options.transfer_estimator.is_none() {
683 return Err(Error::Msg(
684 "compile_plan: require_transfer_pricing is set but no transfer \
685 estimator is wired — placement would silently price transfers at \
686 zero (latency-greedy). Wire PlanOptions::with_transfer_estimator(..) \
687 or drop the pricing requirement."
688 .into(),
689 )
690 .bt());
691 }
692
693 let generation = crate::dispatch::topology_generation();
699 let mut alternatives_map = HashMap::with_capacity(order.len());
700
701 let mut residency: HashMap<NodeId, DeviceLocation> = HashMap::with_capacity(order.len());
705
706 let mut dp = PlacementDp::new();
709 let mut dp_drafts: HashMap<NodeId, NodeDraft> = HashMap::new();
710
711 for &id in order {
712 let node = graph.node(id);
713
714 if let Some(base) = options.reuse_plan
720 && let Some(set) = base.alternatives(id)
721 {
722 let resident = early_residency(graph, options, id, node)
723 .or_else(|| set.winner().map(|w| w.device));
724 if let Some(loc) = resident {
725 residency.insert(id, loc);
726 }
727 alternatives_map.insert(id, set.clone());
728 continue;
729 }
730
731 let early = early_residency(graph, options, id, node);
734
735 let mut dp_row_opened = false;
736 let winner_device = match build_node_draft(graph, id, node, bindings_table, options)? {
737 Some(draft) => {
738 let devices = distinct_devices(&draft.set);
739 let dp_estimator = options
740 .transfer_estimator
741 .filter(|_| draft.relaxed && early.is_none() && devices.len() >= 2);
742 if let Some(est) = dp_estimator {
743 open_dp_row(
747 &mut dp,
748 graph,
749 id,
750 node,
751 &draft.set,
752 &devices,
753 &residency,
754 est,
755 options.capabilities_for,
756 );
757 dp_drafts.insert(id, draft);
758 dp_row_opened = true;
759 None
760 } else {
761 if let Some(est) = options.transfer_estimator
768 && let [single] = devices.as_slice()
769 {
770 close_open_inputs(&mut dp, graph, node, *single, est, &mut residency);
771 }
772 let set = finalize_node_greedy(
773 graph,
774 node,
775 draft,
776 bindings_table,
777 options,
778 &residency,
779 )?;
780 let dev = set.winner().map(|w| w.device);
781 if devices.len() > 1
785 && let (Some(est), Some(wd)) = (options.transfer_estimator, dev)
786 {
787 close_open_inputs(&mut dp, graph, node, wd, est, &mut residency);
788 }
789 alternatives_map.insert(id, set);
790 dev
791 }
792 }
793 None => {
794 if let fuel_graph::Op::Copy { target } | fuel_graph::Op::Move { target } = node.op
800 && let Some(est) = options.transfer_estimator
801 {
802 close_open_inputs(&mut dp, graph, node, target, est, &mut residency);
803 }
804 None
805 }
806 };
807
808 if dp_row_opened {
809 continue;
813 }
814
815 let resident = early
817 .or(winner_device)
818 .or_else(|| {
819 graph.target_backend(id).map(|b| {
824 options
825 .pinned_device
826 .unwrap_or_else(|| default_device_for(b))
827 })
828 })
829 .or_else(|| {
830 if is_passthrough(node) {
835 node.inputs.first().and_then(|i| residency.get(i)).copied()
836 } else {
837 None
838 }
839 });
840 if let Some(loc) = resident {
841 residency.insert(id, loc);
842 } else if is_passthrough(node) {
843 if let Some(&input) = node.inputs.first() {
849 let root = dp.resolve(input);
850 if let Some(dev) = dp.committed_device(root) {
851 residency.insert(id, dev);
852 } else {
853 dp.add_alias(id, root);
854 }
855 }
856 }
857 }
858
859 if !dp_drafts.is_empty() {
862 let Some(est) = options.transfer_estimator else {
863 return Err(Error::Msg(
866 "compile_plan: placement DP rows exist without a transfer \
867 estimator — internal invariant violated"
868 .into(),
869 )
870 .bt());
871 };
872 let commits = dp.finish(options.pinned_device, |nid| node_bytes(graph, nid), est);
873 for (n, d) in commits {
874 residency.insert(n, d);
875 }
876 for &id in order {
880 if residency.contains_key(&id) {
881 continue;
882 }
883 let node = graph.node(id);
884 if is_passthrough(node)
885 && let Some(&loc) = node.inputs.first().and_then(|i| residency.get(i))
886 {
887 residency.insert(id, loc);
888 }
889 }
890 for &id in order {
895 let Some(draft) = dp_drafts.remove(&id) else {
896 continue;
897 };
898 let chosen = dp.committed_device(id).ok_or_else(|| {
899 Error::Msg(format!(
900 "compile_plan: placement DP left node {:?} uncommitted — \
901 internal invariant violated",
902 id,
903 ))
904 .bt()
905 })?;
906 let node = graph.node(id);
907 let mut set = draft.set;
908 let inputs = priced_inputs_for(graph, node, &residency);
909 apply_inbound_transfer_costs(&mut set, &inputs, est);
910 set.rank_by_composite_cost();
911 let keep: Vec<usize> = set
912 .alternatives()
913 .iter()
914 .enumerate()
915 .filter_map(|(i, c)| (c.device == chosen).then_some(i))
916 .collect();
917 if keep.len() < set.len() {
918 set.retain_indices(&keep);
919 }
920 set.retain_per_device_frontier(KEEP_PER_DEVICE);
926 if set.is_empty() {
927 return Err(missing_binding_error(
930 bindings_table,
931 draft.op_kind,
932 &draft.dtypes,
933 draft.diag_backend,
934 ));
935 }
936 alternatives_map.insert(id, set);
937 }
938 }
939
940 #[cfg(feature = "telemetry")]
945 emit_plan_telemetry(graph, &alternatives_map, bindings_table, options);
946
947 Ok(ExecutionPlan {
948 order: order.to_vec(),
949 alternatives: alternatives_map,
950 generation,
951 })
952}
953
954#[cfg(feature = "telemetry")]
979fn emit_plan_telemetry(
980 graph: &Graph,
981 alternatives: &HashMap<NodeId, AlternativeSet>,
982 bindings_table: &KernelBindingTable,
983 options: &PlanOptions<'_>,
984) {
985 use crate::telemetry::{
986 DispatchRecord, FdxOperandDesc, ImplId, TELEMETRY_SCHEMA_VERSION, detect_miss_precomputed,
987 };
988
989 let Some(hooks) = options.telemetry else {
991 return;
992 };
993 if !hooks.config.is_enabled() {
994 return;
995 }
996 let arch = hooks.arch_tag();
997 let want_candidates = hooks.config.mode.wants_candidates();
998
999 for (&id, set) in alternatives {
1000 let Some(winner) = set.winner() else {
1001 continue;
1002 };
1003 let node = graph.node(id);
1004 let Some(op_kind) = op_to_op_kind(&node.op) else {
1005 continue;
1006 };
1007 let dtypes = build_lookup_dtypes(graph, node);
1008
1009 let winner_ptr = winner.kernel as *const () as usize;
1014 let winner_entry = bindings_table
1015 .lookup_alternatives(op_kind, &dtypes, winner.backend)
1016 .iter()
1017 .find(|e| e.kernel as *const () as usize == winner_ptr)
1018 .copied();
1019 let is_generic = winner_entry.is_some_and(|e| e.is_generic);
1020 let winner_revision = winner_entry.map_or(0, |e| e.kernel_revision_hash);
1021
1022 let mut operands: Vec<FdxOperandDesc> = node
1028 .inputs
1029 .iter()
1030 .map(|&input_id| {
1031 FdxOperandDesc::from_layout(&graph.layout(input_id), graph.node(input_id).dtype)
1032 })
1033 .collect();
1034 operands.push(FdxOperandDesc::from_layout(&graph.layout(id), node.dtype));
1035 let op_class = format!("{op_kind:?}");
1036
1037 let structure_key = hooks.provider.structure_key(&op_class, &operands, &arch);
1041
1042 let chosen = ImplId {
1044 backend: winner.backend,
1045 op: op_kind,
1046 dtypes: dtypes.to_vec(),
1047 kernel_source: winner.kernel_source.to_string(),
1048 kernel_revision_hash: winner_revision,
1049 };
1050
1051 let candidates = if want_candidates {
1054 build_candidates(set, op_kind, &dtypes, bindings_table, options.judge)
1055 } else {
1056 Vec::new()
1057 };
1058
1059 let dispatch = DispatchRecord {
1061 schema: TELEMETRY_SCHEMA_VERSION,
1062 structure_key,
1063 chosen: chosen.clone(),
1064 candidates,
1065 count: 1,
1066 hw: hooks.hw.clone(),
1067 };
1068 if let Ok(mut sink) = hooks.sink.lock() {
1069 sink.record_dispatch(dispatch);
1070 }
1071
1072 if let Some(miss) = detect_miss_precomputed(
1076 is_generic,
1077 chosen,
1078 &op_class,
1079 &operands,
1080 &arch,
1081 hooks.provider,
1082 hooks.hw.clone(),
1083 ) {
1084 if let Ok(mut sink) = hooks.sink.lock() {
1087 sink.record_miss(miss);
1088 }
1089 }
1090 }
1091}
1092
1093#[cfg(feature = "telemetry")]
1102fn build_candidates(
1103 set: &AlternativeSet,
1104 op_kind: OpKind,
1105 dtypes: &[DType],
1106 bindings_table: &KernelBindingTable,
1107 judge: Option<&dyn JudgeOracle>,
1108) -> Vec<crate::telemetry::Candidate> {
1109 use crate::telemetry::{Candidate as TeleCandidate, ImplId};
1110
1111 let ctx = set.context();
1114 set.alternatives()
1115 .iter()
1116 .map(|cand| {
1117 let ptr = cand.kernel as *const () as usize;
1118 let revision = bindings_table
1119 .lookup_alternatives(op_kind, dtypes, cand.backend)
1120 .iter()
1121 .find(|e| e.kernel as *const () as usize == ptr)
1122 .map_or(0, |e| e.kernel_revision_hash);
1123 let impl_id = ImplId {
1124 backend: cand.backend,
1125 op: op_kind,
1126 dtypes: dtypes.to_vec(),
1127 kernel_source: cand.kernel_source.to_string(),
1128 kernel_revision_hash: revision,
1129 };
1130 let latency_ns = match (judge, ctx) {
1131 (Some(j), Some(ctx)) => j.measured_latency_ns(
1132 ctx.op,
1133 ctx.principal_dtype,
1134 ctx.size_class,
1135 cand.backend,
1136 cand.kernel_source,
1137 revision,
1143 ),
1144 _ => None,
1145 };
1146 TeleCandidate {
1147 impl_id,
1148 latency_ns,
1149 }
1150 })
1151 .collect()
1152}
1153
1154pub fn node_needs_plan_entry(op: &fuel_graph::Op) -> bool {
1162 op_to_op_kind(op).is_some()
1163 && !matches!(
1164 op,
1165 fuel_graph::Op::Copy { .. } | fuel_graph::Op::Move { .. }
1166 )
1167}
1168
1169fn is_passthrough(node: &fuel_graph::Node) -> bool {
1173 node.op.is_view_op()
1174 || matches!(
1175 node.op,
1176 fuel_graph::Op::Reshape(_) | fuel_graph::Op::Contiguize
1177 )
1178}
1179
1180fn distinct_devices(set: &AlternativeSet) -> SmallVec<[DeviceLocation; 4]> {
1184 let mut out: SmallVec<[DeviceLocation; 4]> = SmallVec::new();
1185 for c in set.alternatives() {
1186 if !out.contains(&c.device) {
1187 out.push(c.device);
1188 }
1189 }
1190 out
1191}
1192
1193fn node_bytes(graph: &Graph, id: NodeId) -> u64 {
1197 let n = graph.node(id);
1198 (n.shape.elem_count() as u64).saturating_mul(n.dtype.size_in_bytes() as u64)
1199}
1200
1201fn open_dp_row(
1206 dp: &mut PlacementDp,
1207 graph: &Graph,
1208 id: NodeId,
1209 node: &fuel_graph::Node,
1210 set: &AlternativeSet,
1211 devices: &[DeviceLocation],
1212 residency: &HashMap<NodeId, DeviceLocation>,
1213 est: &dyn TransferEstimator,
1214 caps_for: Option<&CapabilitiesLookup<'_>>,
1215) {
1216 let rates_for = |backend: BackendId| -> (f64, f64) {
1225 caps_for
1226 .and_then(|f| f(backend))
1227 .map(|caps| {
1228 (
1229 caps.compute_throughput_flops_per_ns,
1230 caps.mem_bandwidth_bytes_per_ns,
1231 )
1232 })
1233 .unwrap_or_else(|| default_backend_rates(backend))
1234 };
1235 let device_costs: Vec<(DeviceLocation, u64)> = devices
1236 .iter()
1237 .map(|&d| {
1238 let min = set
1239 .alternatives()
1240 .iter()
1241 .filter(|c| c.device == d)
1242 .map(|c| {
1243 let (cr, bw) = rates_for(c.backend);
1244 composite_ns(&c.static_cost, cr, bw)
1245 })
1246 .min()
1247 .unwrap_or(u64::MAX);
1248 (d, min)
1249 })
1250 .collect();
1251
1252 let mut fixed: Vec<(DeviceLocation, u64)> = Vec::new();
1253 let mut chains: Vec<ChainInput> = Vec::new();
1254 for &input in &node.inputs {
1255 let bytes = node_bytes(graph, input);
1256 if let Some(&src) = residency.get(&input) {
1257 fixed.push((src, bytes));
1258 continue;
1259 }
1260 let root = dp.resolve(input);
1261 if dp.is_open(root) {
1262 match chains.iter_mut().find(|ci| ci.producer == root) {
1263 Some(ci) => ci.edge_bytes.push(bytes),
1264 None => chains.push(ChainInput {
1265 producer: root,
1266 edge_bytes: smallvec::smallvec![bytes],
1267 }),
1268 }
1269 } else if let Some(dev) = dp.committed_device(root) {
1270 fixed.push((dev, bytes));
1273 }
1274 }
1277 dp.push_row(id, &device_costs, &fixed, &chains, est);
1278}
1279
1280fn close_open_inputs(
1286 dp: &mut PlacementDp,
1287 graph: &Graph,
1288 node: &fuel_graph::Node,
1289 toward: DeviceLocation,
1290 est: &dyn TransferEstimator,
1291 residency: &mut HashMap<NodeId, DeviceLocation>,
1292) {
1293 for &input in &node.inputs {
1294 if residency.contains_key(&input) {
1295 continue;
1296 }
1297 let root = dp.resolve(input);
1298 if dp.is_open(root) {
1299 let commits = dp.close_toward(root, toward, &[node_bytes(graph, input)], est);
1300 for (n, d) in commits {
1301 residency.insert(n, d);
1302 }
1303 }
1304 if !residency.contains_key(&input)
1305 && let Some(d) = dp.committed_device(root)
1306 {
1307 residency.insert(input, d);
1308 }
1309 }
1310}
1311
1312fn early_residency(
1321 graph: &Graph,
1322 options: &PlanOptions<'_>,
1323 id: NodeId,
1324 node: &fuel_graph::Node,
1325) -> Option<DeviceLocation> {
1326 match node.op {
1327 fuel_graph::Op::Copy { target }
1328 | fuel_graph::Op::Move { target }
1329 | fuel_graph::Op::Alloc { target } => return Some(target),
1330 _ => {}
1331 }
1332 if let Some(loc) = graph.placement(id) {
1333 return Some(loc);
1334 }
1335 options.input_residency.and_then(|f| f(id))
1336}
1337
1338fn priced_inputs_for(
1344 graph: &Graph,
1345 node: &fuel_graph::Node,
1346 residency: &HashMap<NodeId, DeviceLocation>,
1347) -> Vec<(DeviceLocation, u64)> {
1348 node.inputs
1349 .iter()
1350 .filter_map(|&input_id| {
1351 let src = residency.get(&input_id).copied()?;
1352 let in_node = graph.node(input_id);
1353 let bytes = (in_node.shape.elem_count() as u64)
1354 .saturating_mul(in_node.dtype.size_in_bytes() as u64);
1355 Some((src, bytes))
1356 })
1357 .collect()
1358}
1359
1360struct NodeDraft {
1366 set: AlternativeSet,
1367 relaxed: bool,
1370 from_fallback: bool,
1373 costed: bool,
1377 op_kind: OpKind,
1378 dtypes: Vec<DType>,
1379 diag_backend: BackendId,
1380}
1381
1382fn build_node_draft(
1389 graph: &Graph,
1390 id: NodeId,
1391 node: &fuel_graph::Node,
1392 bindings_table: &KernelBindingTable,
1393 options: &PlanOptions<'_>,
1394) -> Result<Option<NodeDraft>> {
1395 if !node_needs_plan_entry(&node.op) {
1411 return Ok(None);
1412 }
1413 let Some(op_kind) = op_to_op_kind(&node.op) else {
1414 return Ok(None);
1416 };
1417
1418 let explicit_backend = graph.target_backend(id);
1422 let target_device = decision_device_for(graph, options, id).ok_or_else(|| {
1423 Error::Msg(format!(
1424 "compile_plan: node {:?} ({:?}) has no device context — \
1425 set PlanOptions::pinned_device, a graph placement, or \
1426 the node's target_backend",
1427 id, node.op,
1428 ))
1429 .bt()
1430 })?;
1431 let diag_backend = explicit_backend.unwrap_or_else(|| backend_for_device(target_device));
1435 let dtypes = build_lookup_dtypes(graph, node);
1436
1437 let placements: Vec<(BackendId, DeviceLocation)> = match options.placements_for_device {
1441 Some(f) => f(target_device)
1442 .into_iter()
1443 .map(|backend| (backend, target_device))
1444 .collect(),
1445 None => vec![(diag_backend, target_device)],
1446 };
1447
1448 let op_params = candidate_default_op_params(graph, node);
1449
1450 let pricing_active = options.transfer_estimator.is_some()
1468 && options.populate_costs
1469 && options.capabilities_for.is_some();
1470 let fallback_allowed =
1471 node.op.destructive_input().is_none() && options.fallback_placements_for.is_some();
1472 let relaxed = options.allow_cost_placement
1473 && pricing_active
1474 && fallback_allowed
1475 && graph.placement(id).is_none();
1476
1477 let mut set;
1478 let mut from_fallback = false;
1479 if relaxed {
1480 let mut merged = placements.clone();
1485 if let Some(fallback) = options.fallback_placements_for {
1486 merged.extend(fallback(target_device));
1487 }
1488 set = enumerate_candidates(op_kind, &dtypes, &merged, &op_params, bindings_table);
1489 } else {
1490 set = enumerate_candidates(op_kind, &dtypes, &placements, &op_params, bindings_table);
1491
1492 if set.is_empty()
1500 && fallback_allowed
1501 && let Some(fallback) = options.fallback_placements_for
1502 {
1503 let fb_placements = fallback(target_device);
1504 if !fb_placements.is_empty() {
1505 set = enumerate_candidates(
1506 op_kind,
1507 &dtypes,
1508 &fb_placements,
1509 &op_params,
1510 bindings_table,
1511 );
1512 from_fallback = !set.is_empty();
1513 }
1514 }
1515 }
1516
1517 if set.is_empty() {
1522 return Err(missing_binding_error(
1523 bindings_table,
1524 op_kind,
1525 &dtypes,
1526 diag_backend,
1527 ));
1528 }
1529
1530 let input_layouts: Vec<fuel_ir::Layout> = node
1532 .inputs
1533 .iter()
1534 .map(|&input_id| graph.layout(input_id))
1535 .collect();
1536 let ctx = FilterContext::new(op_kind, &dtypes, &input_layouts);
1537 let chain = default_chain(options.precision_requirement);
1538 if let Err(err) = apply_filter_chain(&mut set, &chain, &ctx) {
1539 if relaxed || from_fallback || !fallback_allowed {
1548 return Err(err);
1549 }
1550 let Some(fallback) = options.fallback_placements_for else {
1551 return Err(err);
1552 };
1553 let fb_placements = fallback(target_device);
1554 if fb_placements.is_empty() {
1555 return Err(err);
1556 }
1557 let mut fb_set =
1558 enumerate_candidates(op_kind, &dtypes, &fb_placements, &op_params, bindings_table);
1559 if fb_set.is_empty() {
1560 return Err(err);
1561 }
1562 apply_filter_chain(&mut fb_set, &chain, &ctx)?;
1565 set = fb_set;
1566 from_fallback = true;
1567 }
1568
1569 if let Some(&principal_dtype) = dtypes.first() {
1580 let input_shapes: Vec<Shape> = node
1581 .inputs
1582 .iter()
1583 .map(|&input_id| graph.node(input_id).shape.clone())
1584 .collect();
1585 let size_class = SizeClass::for_op(op_kind, &input_shapes);
1586 set.set_context(DecisionContext {
1587 op: op_kind,
1588 principal_dtype,
1589 size_class,
1590 });
1591 }
1592
1593 let costed = if options.populate_costs {
1597 if let Some(caps_for) = options.capabilities_for {
1598 let input_shapes: Vec<Shape> = node
1599 .inputs
1600 .iter()
1601 .map(|&input_id| graph.node(input_id).shape.clone())
1602 .collect();
1603 compute_static_costs(
1604 &mut set,
1605 op_kind,
1606 &dtypes,
1607 &input_shapes,
1608 bindings_table,
1609 caps_for,
1610 options.judge,
1611 );
1612 true
1613 } else {
1614 false
1615 }
1616 } else {
1617 false
1618 };
1619
1620 Ok(Some(NodeDraft {
1621 set,
1622 relaxed,
1623 from_fallback,
1624 costed,
1625 op_kind,
1626 dtypes,
1627 diag_backend,
1628 }))
1629}
1630
1631fn finalize_node_greedy(
1638 graph: &Graph,
1639 node: &fuel_graph::Node,
1640 draft: NodeDraft,
1641 bindings_table: &KernelBindingTable,
1642 options: &PlanOptions<'_>,
1643 residency: &HashMap<NodeId, DeviceLocation>,
1644) -> Result<AlternativeSet> {
1645 let NodeDraft {
1646 mut set,
1647 relaxed,
1648 from_fallback,
1649 costed,
1650 op_kind,
1651 dtypes,
1652 diag_backend,
1653 } = draft;
1654
1655 if costed {
1656 if let Some(estimator) = options.transfer_estimator {
1662 let inputs = priced_inputs_for(graph, node, residency);
1663 apply_inbound_transfer_costs(&mut set, &inputs, estimator);
1664 }
1665 set.rank_by_composite_cost();
1666 }
1667
1668 if relaxed && let Some(winner_device) = set.winner().map(|c| c.device) {
1679 let keep: Vec<usize> = set
1680 .alternatives()
1681 .iter()
1682 .enumerate()
1683 .filter_map(|(i, c)| (c.device == winner_device).then_some(i))
1684 .collect();
1685 if keep.len() < set.len() {
1686 set.retain_indices(&keep);
1687 }
1688 }
1689
1690 set.retain_per_device_frontier(KEEP_PER_DEVICE);
1698
1699 if from_fallback && set.len() > 1 {
1706 set.retain_indices(&[0]);
1707 }
1708
1709 if set.is_empty() {
1716 return Err(missing_binding_error(
1717 bindings_table,
1718 op_kind,
1719 &dtypes,
1720 diag_backend,
1721 ));
1722 }
1723
1724 Ok(set)
1725}
1726
1727fn missing_binding_error(
1733 table: &KernelBindingTable,
1734 op: OpKind,
1735 dtypes: &[DType],
1736 backend: BackendId,
1737) -> Error {
1738 let _ = backend;
1743 let (available_backends, supported_combinations) = table.coverage_diagnostic();
1744 Error::NoBackendForOp {
1745 op,
1746 dtypes: dtypes.to_vec(),
1747 available_backends,
1748 supported_combinations,
1749 }
1750 .bt()
1751}
1752
1753fn candidate_default_op_params(
1761 _graph: &Graph,
1762 _node: &fuel_graph::Node,
1763) -> crate::kernel::OpParams {
1764 crate::kernel::OpParams::None
1765}
1766
1767#[cfg(test)]
1768mod tests {
1769 use super::*;
1770 use crate::fused::PrecisionGuarantee;
1771 use crate::kernel::{KernelCaps, OpParams, unknown_cost};
1772 use fuel_graph::{Node, Op, topo_order};
1773 use fuel_ir::backend::{BackendCapabilities, SubstrateClass, TransferPath};
1774 use fuel_ir::{DType, Layout, Result as FuelResult, Shape, StrideVec};
1775 use fuel_memory::Storage;
1776 use smallvec::smallvec;
1777 use std::collections::HashSet;
1778 use std::sync::{Arc, RwLock};
1779
1780 fn noop_kernel(
1781 _i: &[Arc<RwLock<Storage>>],
1782 _o: &mut [Arc<RwLock<Storage>>],
1783 _l: &[Layout],
1784 _p: &OpParams,
1785 ) -> FuelResult<()> {
1786 Ok(())
1787 }
1788
1789 fn noop_kernel_b(
1790 _i: &[Arc<RwLock<Storage>>],
1791 _o: &mut [Arc<RwLock<Storage>>],
1792 _l: &[Layout],
1793 _p: &OpParams,
1794 ) -> FuelResult<()> {
1795 Ok(())
1796 }
1797
1798 fn noop_kernel_c(
1799 _i: &[Arc<RwLock<Storage>>],
1800 _o: &mut [Arc<RwLock<Storage>>],
1801 _l: &[Layout],
1802 _p: &OpParams,
1803 ) -> FuelResult<()> {
1804 Ok(())
1805 }
1806
1807 fn register_add_f32(
1808 table: &mut KernelBindingTable,
1809 backend: BackendId,
1810 kernel: crate::kernel::KernelRef,
1811 precision: PrecisionGuarantee,
1812 ) {
1813 table.register_full(
1814 OpKind::AddElementwise,
1815 &[DType::F32, DType::F32, DType::F32],
1816 backend,
1817 kernel,
1818 KernelCaps::empty(),
1819 precision,
1820 unknown_cost,
1821 );
1822 }
1823
1824 fn build_add_graph() -> (Graph, NodeId) {
1825 let mut g = Graph::new();
1826 let lhs = g.push(Node {
1827 op: Op::Const,
1828 inputs: vec![],
1829 shape: Shape::from_dims(&[3]),
1830 dtype: DType::F32,
1831 });
1832 let rhs = g.push(Node {
1833 op: Op::Const,
1834 inputs: vec![],
1835 shape: Shape::from_dims(&[3]),
1836 dtype: DType::F32,
1837 });
1838 let add = g.push(Node {
1839 op: Op::Add,
1840 inputs: vec![lhs, rhs],
1841 shape: Shape::from_dims(&[3]),
1842 dtype: DType::F32,
1843 });
1844 g.set_target_backend(add, BackendId::Cpu);
1845 (g, add)
1846 }
1847
1848 fn cpu_caps() -> BackendCapabilities {
1849 BackendCapabilities {
1850 backend_id: BackendId::Cpu,
1851 device_location: DeviceLocation::Cpu,
1852 op_dtype_support: HashSet::new(),
1853 required_alignment: 64,
1854 access_granularity_bits: 8,
1855 transfer_paths: vec![(DeviceLocation::Cpu, TransferPath::SameDevice)],
1856 storage_substrate: SubstrateClass::HostBytes,
1857 compute_throughput_flops_per_ns: 1.0,
1858 mem_bandwidth_bytes_per_ns: 4.0,
1859 }
1860 }
1861
1862 #[test]
1863 fn empty_plan_has_no_alternatives() {
1864 let p = ExecutionPlan::empty();
1865 assert!(p.order.is_empty());
1866 assert!(p.alternatives.is_empty());
1867 assert!(p.alternatives(NodeId(0)).is_none());
1868 }
1869
1870 #[test]
1871 fn default_device_per_backend_matches_router_convention() {
1872 assert_eq!(default_device_for(BackendId::Cpu), DeviceLocation::Cpu);
1873 assert_eq!(
1874 default_device_for(BackendId::Cuda),
1875 DeviceLocation::Cuda { gpu_id: 0 },
1876 );
1877 assert_eq!(
1878 default_device_for(BackendId::Vulkan),
1879 DeviceLocation::Vulkan { gpu_id: 0 },
1880 );
1881 }
1882
1883 #[test]
1884 fn compile_plan_skips_view_and_const_nodes() {
1885 let mut table = KernelBindingTable::new();
1886 register_add_f32(
1887 &mut table,
1888 BackendId::Cpu,
1889 noop_kernel,
1890 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1891 );
1892
1893 let mut g = Graph::new();
1894 let lhs = g.push(Node {
1895 op: Op::Const,
1896 inputs: vec![],
1897 shape: Shape::from_dims(&[6]),
1898 dtype: DType::F32,
1899 });
1900 let rhs = g.push(Node {
1901 op: Op::Const,
1902 inputs: vec![],
1903 shape: Shape::from_dims(&[6]),
1904 dtype: DType::F32,
1905 });
1906 let add = g.push(Node {
1907 op: Op::Add,
1908 inputs: vec![lhs, rhs],
1909 shape: Shape::from_dims(&[6]),
1910 dtype: DType::F32,
1911 });
1912 let reshape = g.push(Node {
1913 op: Op::Reshape(Shape::from_dims(&[2, 3])),
1914 inputs: vec![add],
1915 shape: Shape::from_dims(&[2, 3]),
1916 dtype: DType::F32,
1917 });
1918 g.set_target_backend(add, BackendId::Cpu);
1919 g.set_target_backend(reshape, BackendId::Cpu);
1920
1921 let order = topo_order(&g, reshape);
1922 let opts = PlanOptions::new().without_cost_population();
1923 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
1924
1925 assert_eq!(plan.order.len(), 4);
1926 assert_eq!(
1927 plan.alternatives.len(),
1928 1,
1929 "only Add carries an alternative set",
1930 );
1931 let alts = plan.alternatives(add).expect("Add alternatives present");
1932 assert_eq!(alts.len(), 1);
1933 assert!(plan.alternatives(lhs).is_none());
1934 assert!(plan.alternatives(rhs).is_none());
1935 assert!(plan.alternatives(reshape).is_none());
1936 }
1937
1938 #[test]
1939 fn compile_plan_fails_fast_on_missing_binding() {
1940 let table = KernelBindingTable::new();
1941 let mut g = Graph::new();
1942 let lhs = g.push(Node {
1943 op: Op::Const,
1944 inputs: vec![],
1945 shape: Shape::from_dims(&[2, 3]),
1946 dtype: DType::F32,
1947 });
1948 let rhs = g.push(Node {
1949 op: Op::Const,
1950 inputs: vec![],
1951 shape: Shape::from_dims(&[3, 2]),
1952 dtype: DType::F32,
1953 });
1954 let mm = g.push(Node {
1955 op: Op::MatMul,
1956 inputs: vec![lhs, rhs],
1957 shape: Shape::from_dims(&[2, 2]),
1958 dtype: DType::F32,
1959 });
1960 g.set_target_backend(mm, BackendId::Cpu);
1961
1962 let order = topo_order(&g, mm);
1963 let opts = PlanOptions::new().without_cost_population();
1964 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
1965 match err {
1966 Error::NoBackendForOp { op, dtypes, .. } => {
1967 assert_eq!(op, OpKind::MatMul);
1968 assert_eq!(dtypes, vec![DType::F32, DType::F32, DType::F32]);
1969 }
1970 other => panic!("expected NoBackendForOp, got {other:?}"),
1971 }
1972 }
1973
1974 #[test]
1987 fn plan_time_miss_reports_real_coverage_not_empty() {
1988 let bindings = crate::dispatch::global_bindings(); let mut g = Graph::new();
1990 let lhs = g.push(Node {
1991 op: Op::Const,
1992 inputs: vec![],
1993 shape: Shape::from_dims(&[2, 3]),
1994 dtype: DType::F32,
1995 });
1996 let rhs = g.push(Node {
1999 op: Op::Const,
2000 inputs: vec![],
2001 shape: Shape::from_dims(&[3, 2]),
2002 dtype: DType::F64,
2003 });
2004 let mm = g.push(Node {
2005 op: Op::MatMul,
2006 inputs: vec![lhs, rhs],
2007 shape: Shape::from_dims(&[2, 2]),
2008 dtype: DType::F32,
2009 });
2010 g.set_target_backend(mm, BackendId::Cpu);
2011
2012 let order = topo_order(&g, mm);
2013 let opts = PlanOptions::new().without_cost_population();
2014 let err = compile_plan(&g, &order, &bindings, &opts).unwrap_err();
2015 match err {
2016 Error::NoBackendForOp {
2017 op,
2018 dtypes,
2019 available_backends,
2020 supported_combinations,
2021 } => {
2022 assert_eq!(op, OpKind::MatMul);
2023 assert_eq!(
2024 dtypes,
2025 vec![DType::F32, DType::F64, DType::F32],
2026 "the mixed-precision key (F32 activation, F64 weight)",
2027 );
2028 assert!(
2030 available_backends.contains(&BackendId::Cpu),
2031 "a populated table must report Cpu, never []: {available_backends:?}",
2032 );
2033 assert!(
2034 supported_combinations
2035 .iter()
2036 .any(|(b, o, d)| *b == BackendId::Cpu
2037 && *o == OpKind::MatMul
2038 && *d == vec![DType::F32, DType::F32, DType::F32]),
2039 "must show uniform F32 matmul IS registered (so the mixed gap is visible): \
2040 {supported_combinations:?}",
2041 );
2042 }
2043 other => panic!("expected NoBackendForOp, got {other:?}"),
2044 }
2045 }
2046
2047 #[test]
2048 fn compile_plan_legacy_single_backend_uses_target_backend() {
2049 let mut table = KernelBindingTable::new();
2050 register_add_f32(
2051 &mut table,
2052 BackendId::Cpu,
2053 noop_kernel,
2054 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2055 );
2056 register_add_f32(
2060 &mut table,
2061 BackendId::Cuda,
2062 noop_kernel_b,
2063 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2064 );
2065 let (g, add_id) = build_add_graph();
2066 let order = topo_order(&g, add_id);
2067 let opts = PlanOptions::new().without_cost_population();
2068 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2069 let alts = plan.alternatives(add_id).unwrap();
2070 assert_eq!(alts.len(), 1, "legacy mode → single backend → single alt");
2071 assert_eq!(alts.winner().unwrap().backend, BackendId::Cpu);
2072 }
2073
2074 #[test]
2075 fn compile_plan_cross_co_located_via_placements_callback() {
2076 let mut table = KernelBindingTable::new();
2077 register_add_f32(
2078 &mut table,
2079 BackendId::Cpu,
2080 noop_kernel,
2081 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2082 );
2083 register_add_f32(
2084 &mut table,
2085 BackendId::Cuda,
2086 noop_kernel_b,
2087 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2088 );
2089
2090 let (g, add_id) = build_add_graph();
2091 let order = topo_order(&g, add_id);
2092 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2093 if dev == DeviceLocation::Cpu {
2094 vec![BackendId::Cpu, BackendId::Cuda]
2095 } else {
2096 vec![]
2097 }
2098 };
2099 let opts = PlanOptions::new()
2100 .without_cost_population()
2101 .with_placements_for_device(&placements_fn);
2102 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2103 let alts = plan.alternatives(add_id).unwrap();
2104 assert_eq!(
2105 alts.len(),
2106 2,
2107 "cross-co-located mode aggregates Cpu + Aocl alternatives",
2108 );
2109 }
2110
2111 #[test]
2112 fn compile_plan_precision_requirement_filters_via_default_chain() {
2113 let mut table = KernelBindingTable::new();
2114 register_add_f32(
2116 &mut table,
2117 BackendId::Cpu,
2118 noop_kernel,
2119 PrecisionGuarantee {
2120 bit_stable_on_same_hardware: false,
2121 ..PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU
2122 },
2123 );
2124
2125 let (g, add_id) = build_add_graph();
2126 let order = topo_order(&g, add_id);
2127 let opts = PlanOptions::new()
2128 .without_cost_population()
2129 .with_precision_requirement(PrecisionRequirement::BIT_STABLE);
2130 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
2131 match err {
2132 Error::FilterRejected { filter, .. } => {
2133 assert_eq!(filter, "precision-floor");
2134 }
2135 other => panic!("expected FilterRejected, got {other:?}"),
2136 }
2137 let unconstrained = PlanOptions::new().without_cost_population();
2139 let plan = compile_plan(&g, &order, &table, &unconstrained).expect("compile");
2140 assert!(plan.alternatives(add_id).is_some());
2141 let _ = add_id;
2142 }
2143
2144 #[test]
2145 fn compile_plan_with_cost_ranks_cheaper_winner() {
2146 fn cheap_cost(
2147 _: &[Shape],
2148 _: &[DType],
2149 _: &OpParams,
2150 _: &BackendCapabilities,
2151 ) -> crate::fused::CostEstimate {
2152 crate::fused::CostEstimate {
2153 flops: 10,
2154 bytes_moved: 0,
2155 kernel_overhead_ns: 0,
2156 }
2157 }
2158 fn expensive_cost(
2159 _: &[Shape],
2160 _: &[DType],
2161 _: &OpParams,
2162 _: &BackendCapabilities,
2163 ) -> crate::fused::CostEstimate {
2164 crate::fused::CostEstimate {
2165 flops: 1_000_000,
2166 bytes_moved: 0,
2167 kernel_overhead_ns: 0,
2168 }
2169 }
2170 let mut table = KernelBindingTable::new();
2171 table.register_full(
2172 OpKind::AddElementwise,
2173 &[DType::F32, DType::F32, DType::F32],
2174 BackendId::Cpu,
2175 noop_kernel,
2176 KernelCaps::empty(),
2177 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2178 expensive_cost,
2179 );
2180 table.register_full(
2181 OpKind::AddElementwise,
2182 &[DType::F32, DType::F32, DType::F32],
2183 BackendId::Cuda,
2184 noop_kernel_b,
2185 KernelCaps::empty(),
2186 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2187 cheap_cost,
2188 );
2189
2190 let (g, add_id) = build_add_graph();
2191 let order = topo_order(&g, add_id);
2192 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2193 if dev == DeviceLocation::Cpu {
2194 vec![BackendId::Cpu, BackendId::Cuda]
2195 } else {
2196 vec![]
2197 }
2198 };
2199 let cpu_caps_val = cpu_caps();
2200 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
2201 let opts = PlanOptions::new()
2202 .with_placements_for_device(&placements_fn)
2203 .with_capabilities_for(&caps_fn);
2204 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2205 let alts = plan.alternatives(add_id).unwrap();
2206 assert_eq!(alts.len(), 2);
2207 assert_eq!(
2208 alts.winner().unwrap().backend,
2209 BackendId::Cuda,
2210 "cheaper static cost wins after ranking",
2211 );
2212 }
2213
2214 #[test]
2215 fn compile_plan_judge_layer2_can_flip_layer1_winner() {
2216 use crate::ranker::HashMapJudge;
2220 use fuel_ir::dispatch::SizeClass;
2221
2222 fn cpu_layer1(
2223 _: &[Shape],
2224 _: &[DType],
2225 _: &OpParams,
2226 _: &BackendCapabilities,
2227 ) -> crate::fused::CostEstimate {
2228 crate::fused::CostEstimate {
2229 flops: 10,
2230 bytes_moved: 0,
2231 kernel_overhead_ns: 0,
2232 }
2233 }
2234 fn aocl_layer1(
2235 _: &[Shape],
2236 _: &[DType],
2237 _: &OpParams,
2238 _: &BackendCapabilities,
2239 ) -> crate::fused::CostEstimate {
2240 crate::fused::CostEstimate {
2241 flops: 100_000,
2242 bytes_moved: 0,
2243 kernel_overhead_ns: 0,
2244 }
2245 }
2246 let mut table = KernelBindingTable::new();
2247 table.register_full(
2248 OpKind::AddElementwise,
2249 &[DType::F32, DType::F32, DType::F32],
2250 BackendId::Cpu,
2251 noop_kernel,
2252 KernelCaps::empty(),
2253 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2254 cpu_layer1,
2255 );
2256 table.register_full(
2257 OpKind::AddElementwise,
2258 &[DType::F32, DType::F32, DType::F32],
2259 BackendId::Cuda,
2260 noop_kernel_b,
2261 KernelCaps::empty(),
2262 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2263 aocl_layer1,
2264 );
2265
2266 let (g, add_id) = build_add_graph();
2267 let order = topo_order(&g, add_id);
2268 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2269 if dev == DeviceLocation::Cpu {
2270 vec![BackendId::Cpu, BackendId::Cuda]
2271 } else {
2272 vec![]
2273 }
2274 };
2275 let cpu_caps_val = cpu_caps();
2276 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
2277
2278 let sc = SizeClass::from_elem_count(3);
2281 let mut judge = HashMapJudge::new();
2282 judge.insert(
2283 OpKind::AddElementwise,
2284 DType::F32,
2285 sc,
2286 BackendId::Cpu,
2287 "",
2288 5_000,
2289 0,
2290 );
2291 judge.insert(
2292 OpKind::AddElementwise,
2293 DType::F32,
2294 sc,
2295 BackendId::Cuda,
2296 "",
2297 20,
2298 0,
2299 );
2300
2301 let opts = PlanOptions::new()
2302 .with_placements_for_device(&placements_fn)
2303 .with_capabilities_for(&caps_fn)
2304 .with_judge(&judge);
2305
2306 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2307 let alts = plan.alternatives(add_id).unwrap();
2308 assert_eq!(alts.len(), 2);
2309 assert_eq!(
2310 alts.winner().unwrap().backend,
2311 BackendId::Cuda,
2312 "Layer-2 measurement reverses Layer-1 verdict via compile_plan",
2313 );
2314 }
2315
2316 #[test]
2321 fn compile_plan_stamps_decision_context() {
2322 use fuel_ir::dispatch::SizeClass;
2323
2324 let mut table = KernelBindingTable::new();
2325 register_add_f32(
2326 &mut table,
2327 BackendId::Cpu,
2328 noop_kernel,
2329 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2330 );
2331 let (g, add_id) = build_add_graph();
2332 let order = topo_order(&g, add_id);
2333 let opts = PlanOptions::new().without_cost_population();
2334 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2335 let alts = plan.alternatives(add_id).expect("Add alternatives present");
2336 let ctx = alts.context().expect("context stamped");
2337 assert_eq!(ctx.op, OpKind::AddElementwise);
2338 assert_eq!(ctx.principal_dtype, DType::F32);
2339 assert_eq!(ctx.size_class, SizeClass::from_elem_count(3));
2341 }
2342
2343 #[test]
2352 fn compile_plan_retains_per_device_frontier_no_top_n() {
2353 let mut table = KernelBindingTable::new();
2354 register_add_f32(
2357 &mut table,
2358 BackendId::Cpu,
2359 noop_kernel,
2360 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2361 );
2362 register_add_f32(
2363 &mut table,
2364 BackendId::Cuda,
2365 noop_kernel_b,
2366 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2367 );
2368 register_add_f32(
2369 &mut table,
2370 BackendId::Vulkan,
2371 noop_kernel_c,
2372 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2373 );
2374
2375 let (g, add_id) = build_add_graph();
2376 let order = topo_order(&g, add_id);
2377 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2378 if dev == DeviceLocation::Cpu {
2379 vec![BackendId::Cpu, BackendId::Cuda, BackendId::Vulkan]
2380 } else {
2381 vec![]
2382 }
2383 };
2384 let opts = PlanOptions::new()
2385 .without_cost_population()
2386 .with_placements_for_device(&placements_fn);
2387 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2388 let alts = plan.alternatives(add_id).unwrap();
2389 assert_eq!(
2390 alts.len(),
2391 3,
2392 "all three co-located (device, backend) paths survive — no top-N truncation",
2393 );
2394 }
2395
2396 #[test]
2401 fn compile_plan_pinned_device_matches_stamped_plan() {
2402 let mut table = KernelBindingTable::new();
2403 register_add_f32(
2404 &mut table,
2405 BackendId::Cpu,
2406 noop_kernel,
2407 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2408 );
2409
2410 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2411 if dev == DeviceLocation::Cpu {
2412 vec![BackendId::Cpu]
2413 } else {
2414 vec![]
2415 }
2416 };
2417
2418 let (g_stamped, add_stamped) = build_add_graph();
2420 let order_stamped = topo_order(&g_stamped, add_stamped);
2421 let opts_stamped = PlanOptions::new()
2422 .without_cost_population()
2423 .with_placements_for_device(&placements_fn);
2424 let plan_stamped = compile_plan(&g_stamped, &order_stamped, &table, &opts_stamped)
2425 .expect("stamped compile");
2426
2427 let mut g = Graph::new();
2430 let lhs = g.push(Node {
2431 op: Op::Const,
2432 inputs: vec![],
2433 shape: Shape::from_dims(&[3]),
2434 dtype: DType::F32,
2435 });
2436 let rhs = g.push(Node {
2437 op: Op::Const,
2438 inputs: vec![],
2439 shape: Shape::from_dims(&[3]),
2440 dtype: DType::F32,
2441 });
2442 let add = g.push(Node {
2443 op: Op::Add,
2444 inputs: vec![lhs, rhs],
2445 shape: Shape::from_dims(&[3]),
2446 dtype: DType::F32,
2447 });
2448 let order = topo_order(&g, add);
2449 let opts = PlanOptions::new()
2450 .without_cost_population()
2451 .with_placements_for_device(&placements_fn)
2452 .with_pinned_device(DeviceLocation::Cpu);
2453 let plan = compile_plan(&g, &order, &table, &opts).expect("pinned compile");
2454
2455 let a = plan_stamped.alternatives(add_stamped).expect("stamped set");
2456 let b = plan.alternatives(add).expect("pinned set");
2457 assert_eq!(a.len(), b.len(), "same candidate count");
2458 for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
2459 assert_eq!(ca.backend, cb.backend);
2460 assert_eq!(ca.device, cb.device);
2461 assert_eq!(ca.kernel as usize, cb.kernel as usize, "same kernel ref");
2462 assert_eq!(ca.kernel_source, cb.kernel_source);
2463 }
2464 assert_eq!(a.context(), b.context(), "same decision context");
2465 }
2466
2467 #[test]
2471 fn compile_plan_errors_without_any_device_context() {
2472 let mut table = KernelBindingTable::new();
2473 register_add_f32(
2474 &mut table,
2475 BackendId::Cpu,
2476 noop_kernel,
2477 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2478 );
2479 let mut g = Graph::new();
2480 let lhs = g.push(Node {
2481 op: Op::Const,
2482 inputs: vec![],
2483 shape: Shape::from_dims(&[3]),
2484 dtype: DType::F32,
2485 });
2486 let add = g.push(Node {
2487 op: Op::Add,
2488 inputs: vec![lhs, lhs],
2489 shape: Shape::from_dims(&[3]),
2490 dtype: DType::F32,
2491 });
2492 let order = topo_order(&g, add);
2493 let opts = PlanOptions::new().without_cost_population();
2494 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
2495 let msg = format!("{err:?}");
2496 assert!(
2497 msg.contains("no device context"),
2498 "expected the device-context diagnostic, got: {msg}",
2499 );
2500 }
2501
2502 #[test]
2507 fn compile_plan_skips_op_copy_nodes() {
2508 let mut table = KernelBindingTable::new();
2509 register_add_f32(
2510 &mut table,
2511 BackendId::Cpu,
2512 noop_kernel,
2513 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2514 );
2515 table.register_full(
2518 OpKind::Copy,
2519 &[DType::F32, DType::F32],
2520 BackendId::Cpu,
2521 noop_kernel_b,
2522 KernelCaps::empty(),
2523 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2524 unknown_cost,
2525 );
2526
2527 let (mut g, add_id) = build_add_graph();
2528 let copy_id = g.push(Node {
2529 op: Op::Copy {
2530 target: DeviceLocation::Cpu,
2531 },
2532 inputs: vec![add_id],
2533 shape: Shape::from_dims(&[3]),
2534 dtype: DType::F32,
2535 });
2536 g.set_target_backend(copy_id, BackendId::Cpu);
2537 let order = topo_order(&g, copy_id);
2538 let opts = PlanOptions::new()
2539 .without_cost_population()
2540 .with_pinned_device(DeviceLocation::Cpu);
2541 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2542 assert!(plan.alternatives(add_id).is_some(), "Add is planned");
2543 assert!(
2544 plan.alternatives(copy_id).is_none(),
2545 "Op::Copy is residency-determined — no plan entry",
2546 );
2547 }
2548
2549 #[test]
2553 fn compile_plan_skips_op_move_nodes() {
2554 let mut table = KernelBindingTable::new();
2555 register_add_f32(
2556 &mut table,
2557 BackendId::Cpu,
2558 noop_kernel,
2559 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2560 );
2561 table.register_full(
2564 OpKind::Copy,
2565 &[DType::F32, DType::F32],
2566 BackendId::Cpu,
2567 noop_kernel_b,
2568 KernelCaps::empty(),
2569 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2570 unknown_cost,
2571 );
2572
2573 let (mut g, add_id) = build_add_graph();
2574 let move_id = g.push(Node {
2575 op: Op::Move {
2576 target: DeviceLocation::Cpu,
2577 },
2578 inputs: vec![add_id],
2579 shape: Shape::from_dims(&[3]),
2580 dtype: DType::F32,
2581 });
2582 g.set_target_backend(move_id, BackendId::Cpu);
2583 let order = topo_order(&g, move_id);
2584 let opts = PlanOptions::new()
2585 .without_cost_population()
2586 .with_pinned_device(DeviceLocation::Cpu);
2587 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2588 assert!(plan.alternatives(add_id).is_some(), "Add is planned");
2589 assert!(
2590 plan.alternatives(move_id).is_none(),
2591 "Op::Move is residency-determined — no plan entry",
2592 );
2593 }
2594
2595 #[test]
2599 fn compile_plan_fallback_admits_off_device_candidate() {
2600 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2601 let mut table = KernelBindingTable::new();
2602 register_add_f32(
2605 &mut table,
2606 BackendId::Cpu,
2607 noop_kernel,
2608 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2609 );
2610
2611 let mut g = Graph::new();
2612 let lhs = g.push(Node {
2613 op: Op::Const,
2614 inputs: vec![],
2615 shape: Shape::from_dims(&[3]),
2616 dtype: DType::F32,
2617 });
2618 let add = g.push(Node {
2619 op: Op::Add,
2620 inputs: vec![lhs, lhs],
2621 shape: Shape::from_dims(&[3]),
2622 dtype: DType::F32,
2623 });
2624 let order = topo_order(&g, add);
2625
2626 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2627 if dev == cuda0 {
2628 vec![BackendId::Cuda]
2629 } else {
2630 vec![BackendId::Cpu]
2631 }
2632 };
2633 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2634 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
2635 };
2636 let opts = PlanOptions::new()
2637 .without_cost_population()
2638 .with_pinned_device(cuda0)
2639 .with_placements_for_device(&placements_fn)
2640 .with_fallback_placements_for(&fallback_fn);
2641 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2642 let alts = plan.alternatives(add).expect("Add planned via fallback");
2643 assert_eq!(alts.len(), 1, "fallback set frozen to one winner");
2644 let w = alts.winner().unwrap();
2645 assert_eq!(w.backend, BackendId::Cpu);
2646 assert_eq!(w.device, DeviceLocation::Cpu, "off-device placement");
2647 }
2648
2649 #[test]
2655 fn compile_plan_fallback_not_consulted_when_pinned_has_impl() {
2656 let mut table = KernelBindingTable::new();
2657 register_add_f32(
2658 &mut table,
2659 BackendId::Cpu,
2660 noop_kernel,
2661 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2662 );
2663 register_add_f32(
2664 &mut table,
2665 BackendId::Cuda,
2666 noop_kernel_b,
2667 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2668 );
2669 let (g, add_id) = build_add_graph();
2670 let order = topo_order(&g, add_id);
2671 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2672 if dev == DeviceLocation::Cpu {
2673 vec![BackendId::Cpu]
2674 } else {
2675 vec![]
2676 }
2677 };
2678 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2679 panic!(
2680 "fallback consulted although the pinned device has an \
2681 implementation — locality policy violated",
2682 );
2683 };
2684 let opts = PlanOptions::new()
2685 .without_cost_population()
2686 .with_pinned_device(DeviceLocation::Cpu)
2687 .with_placements_for_device(&placements_fn)
2688 .with_fallback_placements_for(&fallback_fn);
2689 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2690 let alts = plan.alternatives(add_id).unwrap();
2691 assert_eq!(alts.len(), 1);
2692 assert_eq!(alts.winner().unwrap().device, DeviceLocation::Cpu);
2693 }
2694
2695 #[test]
2698 fn compile_plan_fallback_denied_for_destructive_ops() {
2699 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2700 let mut table = KernelBindingTable::new();
2701 table.register_full(
2703 OpKind::ReluInplace,
2704 &[DType::F32, DType::F32],
2705 BackendId::Cpu,
2706 noop_kernel,
2707 KernelCaps::empty(),
2708 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2709 unknown_cost,
2710 );
2711 let mut g = Graph::new();
2712 let lhs = g.push(Node {
2713 op: Op::Const,
2714 inputs: vec![],
2715 shape: Shape::from_dims(&[3]),
2716 dtype: DType::F32,
2717 });
2718 let relu = g.push(Node {
2719 op: Op::ReluInplace,
2720 inputs: vec![lhs],
2721 shape: Shape::from_dims(&[3]),
2722 dtype: DType::F32,
2723 });
2724 let order = topo_order(&g, relu);
2725 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2726 if dev == cuda0 {
2727 vec![BackendId::Cuda]
2728 } else {
2729 vec![BackendId::Cpu]
2730 }
2731 };
2732 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2733 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
2734 };
2735 let opts = PlanOptions::new()
2736 .without_cost_population()
2737 .with_pinned_device(cuda0)
2738 .with_placements_for_device(&placements_fn)
2739 .with_fallback_placements_for(&fallback_fn);
2740 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
2741 assert!(
2742 matches!(
2743 err,
2744 Error::NoBackendForOp {
2745 op: OpKind::ReluInplace,
2746 ..
2747 }
2748 ),
2749 "destructive op must NOT fall back off-device; got {err:?}",
2750 );
2751 }
2752
2753 #[test]
2758 fn compile_plan_fallback_freezes_to_single_winner() {
2759 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2760 let vk0 = DeviceLocation::Vulkan { gpu_id: 0 };
2761 let mut table = KernelBindingTable::new();
2762 register_add_f32(
2763 &mut table,
2764 BackendId::Cpu,
2765 noop_kernel,
2766 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2767 );
2768 register_add_f32(
2769 &mut table,
2770 BackendId::Vulkan,
2771 noop_kernel_b,
2772 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2773 );
2774
2775 let mut g = Graph::new();
2776 let lhs = g.push(Node {
2777 op: Op::Const,
2778 inputs: vec![],
2779 shape: Shape::from_dims(&[3]),
2780 dtype: DType::F32,
2781 });
2782 let add = g.push(Node {
2783 op: Op::Add,
2784 inputs: vec![lhs, lhs],
2785 shape: Shape::from_dims(&[3]),
2786 dtype: DType::F32,
2787 });
2788 let order = topo_order(&g, add);
2789 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2790 if dev == cuda0 {
2791 vec![BackendId::Cuda]
2792 } else {
2793 vec![]
2794 }
2795 };
2796 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2797 vec![
2798 (BackendId::Cpu, DeviceLocation::Cpu),
2799 (BackendId::Vulkan, vk0),
2800 ]
2801 };
2802 let opts = PlanOptions::new()
2803 .without_cost_population()
2804 .with_pinned_device(cuda0)
2805 .with_placements_for_device(&placements_fn)
2806 .with_fallback_placements_for(&fallback_fn);
2807 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2808 let alts = plan.alternatives(add).unwrap();
2809 assert_eq!(
2810 alts.len(),
2811 1,
2812 "fallback set must freeze to its single ranked winner",
2813 );
2814 }
2815
2816 struct FlatEstimator {
2819 latency_ns: u64,
2820 }
2821
2822 impl crate::ranker::TransferEstimator for FlatEstimator {
2823 fn estimate_transfer_ns(
2824 &self,
2825 src: DeviceLocation,
2826 dst: DeviceLocation,
2827 _bytes: u64,
2828 ) -> u64 {
2829 if src == dst { 0 } else { self.latency_ns }
2830 }
2831 }
2832
2833 #[test]
2839 fn compile_plan_prices_fallback_by_input_residency() {
2840 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2841 let vk0 = DeviceLocation::Vulkan { gpu_id: 0 };
2842 let mut table = KernelBindingTable::new();
2843 register_add_f32(
2845 &mut table,
2846 BackendId::Cpu,
2847 noop_kernel,
2848 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2849 );
2850 register_add_f32(
2851 &mut table,
2852 BackendId::Vulkan,
2853 noop_kernel_b,
2854 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2855 );
2856
2857 let mut g = Graph::new();
2858 let lhs = g.push(Node {
2859 op: Op::Const,
2860 inputs: vec![],
2861 shape: Shape::from_dims(&[4]),
2862 dtype: DType::F32,
2863 });
2864 let add = g.push(Node {
2865 op: Op::Add,
2866 inputs: vec![lhs, lhs],
2867 shape: Shape::from_dims(&[4]),
2868 dtype: DType::F32,
2869 });
2870 let order = topo_order(&g, add);
2871
2872 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2873 if dev == cuda0 {
2874 vec![BackendId::Cuda]
2875 } else {
2876 vec![]
2877 }
2878 };
2879 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2880 vec![
2881 (BackendId::Cpu, DeviceLocation::Cpu),
2882 (BackendId::Vulkan, vk0),
2883 ]
2884 };
2885 let residency_fn =
2889 move |id: NodeId| -> Option<DeviceLocation> { (id == lhs).then_some(vk0) };
2890 let est = FlatEstimator { latency_ns: 1_000 };
2891 let cpu_caps_val = cpu_caps();
2892 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
2893 let opts = PlanOptions::new()
2894 .with_pinned_device(cuda0)
2895 .with_placements_for_device(&placements_fn)
2896 .with_fallback_placements_for(&fallback_fn)
2897 .with_capabilities_for(&caps_fn)
2898 .with_transfer_estimator(&est)
2899 .with_input_residency(&residency_fn);
2900 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2901 let alts = plan.alternatives(add).expect("Add planned via fallback");
2902 assert_eq!(alts.len(), 1, "fallback narrows to a single winner");
2903 let w = alts.winner().unwrap();
2904 assert_eq!(
2905 w.device, vk0,
2906 "transfer pricing moves the fallback to the inputs' residency",
2907 );
2908 assert_eq!(w.inbound_transfer_ns, 0, "co-resident inputs price zero");
2909 }
2910
2911 fn cost_600(
2914 _: &[Shape],
2915 _: &[DType],
2916 _: &OpParams,
2917 _: &BackendCapabilities,
2918 ) -> crate::fused::CostEstimate {
2919 crate::fused::CostEstimate {
2920 flops: 600,
2921 bytes_moved: 0,
2922 kernel_overhead_ns: 0,
2923 }
2924 }
2925 fn cost_10(
2926 _: &[Shape],
2927 _: &[DType],
2928 _: &OpParams,
2929 _: &BackendCapabilities,
2930 ) -> crate::fused::CostEstimate {
2931 crate::fused::CostEstimate {
2932 flops: 10,
2933 bytes_moved: 0,
2934 kernel_overhead_ns: 0,
2935 }
2936 }
2937 fn cost_15_000(
2941 _: &[Shape],
2942 _: &[DType],
2943 _: &OpParams,
2944 _: &BackendCapabilities,
2945 ) -> crate::fused::CostEstimate {
2946 crate::fused::CostEstimate {
2947 flops: 15_000,
2948 bytes_moved: 0,
2949 kernel_overhead_ns: 0,
2950 }
2951 }
2952 fn cost_10_000_000(
2953 _: &[Shape],
2954 _: &[DType],
2955 _: &OpParams,
2956 _: &BackendCapabilities,
2957 ) -> crate::fused::CostEstimate {
2958 crate::fused::CostEstimate {
2959 flops: 10_000_000,
2960 bytes_moved: 0,
2961 kernel_overhead_ns: 0,
2962 }
2963 }
2964
2965 fn relaxed_plan_with_costs(
2971 cpu_cost: crate::kernel::CostFn,
2972 cuda_cost: crate::kernel::CostFn,
2973 estimator: &FlatEstimator,
2974 ) -> AlternativeSet {
2975 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2976 let mut table = KernelBindingTable::new();
2977 table.register_full(
2978 OpKind::AddElementwise,
2979 &[DType::F32, DType::F32, DType::F32],
2980 BackendId::Cpu,
2981 noop_kernel,
2982 KernelCaps::empty(),
2983 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2984 cpu_cost,
2985 );
2986 table.register_full(
2987 OpKind::AddElementwise,
2988 &[DType::F32, DType::F32, DType::F32],
2989 BackendId::Cuda,
2990 noop_kernel_b,
2991 KernelCaps::empty(),
2992 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2993 cuda_cost,
2994 );
2995
2996 let (g, add_id) = build_add_graph();
2997 let order = topo_order(&g, add_id);
2998 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2999 if dev == DeviceLocation::Cpu {
3000 vec![BackendId::Cpu]
3001 } else {
3002 vec![]
3003 }
3004 };
3005 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3006 vec![(BackendId::Cuda, cuda0)]
3007 };
3008 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3011 let cpu_caps_val = cpu_caps();
3012 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3013 let opts = PlanOptions::new()
3014 .with_pinned_device(DeviceLocation::Cpu)
3015 .with_placements_for_device(&placements_fn)
3016 .with_fallback_placements_for(&fallback_fn)
3017 .with_capabilities_for(&caps_fn)
3018 .with_transfer_estimator(estimator)
3019 .with_input_residency(&residency_fn);
3020 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3021 plan.alternatives(add_id).expect("Add planned").clone()
3022 }
3023
3024 #[test]
3028 fn compile_plan_relaxed_tiny_op_stays_local_when_transfer_dominates() {
3029 let est = FlatEstimator {
3032 latency_ns: 1_000_000,
3033 };
3034 let set = relaxed_plan_with_costs(cost_600, cost_10, &est);
3035 let w = set.winner().unwrap();
3036 assert_eq!(
3037 w.device,
3038 DeviceLocation::Cpu,
3039 "transfer dominates → stay local"
3040 );
3041 assert_eq!(w.inbound_transfer_ns, 0, "local winner pays no transfer");
3042 assert!(
3043 set.alternatives()
3044 .iter()
3045 .all(|c| c.device == DeviceLocation::Cpu),
3046 "off-device siblings pruned after rank",
3047 );
3048 }
3049
3050 #[test]
3083 fn compile_plan_uncapped_gpu_no_longer_wins_by_being_free() {
3084 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3085
3086 fn build_table() -> KernelBindingTable {
3093 let mut table = KernelBindingTable::new();
3094 table.register_full(
3095 OpKind::AddElementwise,
3096 &[DType::F32, DType::F32, DType::F32],
3097 BackendId::Cpu,
3098 noop_kernel,
3099 KernelCaps::empty(),
3100 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3101 cost_600,
3102 );
3103 table.register_full(
3104 OpKind::AddElementwise,
3105 &[DType::F32, DType::F32, DType::F32],
3106 BackendId::Cuda,
3107 noop_kernel_b,
3108 KernelCaps::empty(),
3109 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3110 cost_15_000,
3111 );
3112 table
3113 }
3114
3115 fn winner_device_under(
3123 table: &KernelBindingTable,
3124 cpu_caps_val: &'static BackendCapabilities,
3125 gpu_caps: Option<&'static BackendCapabilities>,
3126 cuda0: DeviceLocation,
3127 ) -> DeviceLocation {
3128 let (g, add_id) = build_add_graph();
3129 let order = topo_order(&g, add_id);
3130 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3131 if dev == DeviceLocation::Cpu {
3132 vec![BackendId::Cpu]
3133 } else {
3134 vec![]
3135 }
3136 };
3137 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3138 vec![(BackendId::Cuda, cuda0)]
3139 };
3140 let residency_fn =
3144 |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3145 let est = FlatEstimator { latency_ns: 100 };
3148 let caps_fn = move |b: BackendId| -> Option<&BackendCapabilities> {
3149 match b {
3150 BackendId::Cpu => Some(cpu_caps_val),
3151 BackendId::Cuda => gpu_caps,
3152 _ => None,
3153 }
3154 };
3155 let opts = PlanOptions::new()
3156 .with_pinned_device(DeviceLocation::Cpu)
3157 .with_placements_for_device(&placements_fn)
3158 .with_fallback_placements_for(&fallback_fn)
3159 .with_capabilities_for(&caps_fn)
3160 .with_transfer_estimator(&est)
3161 .with_input_residency(&residency_fn);
3162 let plan = compile_plan(&g, &order, table, &opts).expect("compile");
3163 plan.alternatives(add_id).unwrap().winner().unwrap().device
3164 }
3165
3166 let table = build_table();
3167 let cpu_caps_val: &'static BackendCapabilities = Box::leak(Box::new(cpu_caps()));
3171
3172 let winner_bug = winner_device_under(&table, cpu_caps_val, None, cuda0);
3176 assert_eq!(
3177 winner_bug, cuda0,
3178 "PRE-FIX: an uncapped CUDA candidate is skipped by \
3179 compute_static_costs, prices at 0 + 200 transfer, and \
3180 spuriously beats the CPU's honest 600 — this IS the bug",
3181 );
3182
3183 let cuda_caps_val: &'static BackendCapabilities = Box::leak(Box::new(
3186 crate::dispatch::derive_backend_caps(BackendId::Cuda, cuda0, &table),
3187 ));
3188 assert!(
3191 cuda_caps_val
3192 .op_dtype_support
3193 .contains(&(OpKind::AddElementwise, DType::F32)),
3194 "derive_backend_caps must mirror the binding table's \
3195 registered (op, output-dtype) pairs for the backend",
3196 );
3197 assert_eq!(cuda_caps_val.backend_id, BackendId::Cuda);
3198 assert_eq!(cuda_caps_val.device_location, cuda0);
3199
3200 let winner_fixed = winner_device_under(&table, cpu_caps_val, Some(cuda_caps_val), cuda0);
3201 assert_eq!(
3202 winner_fixed,
3203 DeviceLocation::Cpu,
3204 "POST-FIX: with GPU caps registered the CUDA candidate is \
3205 costed honestly (15000 FLOPs ÷ 30/ns = 500 ns compute + 200 \
3206 transfer = 700 > CPU 600), so the CPU-pinned realize stays \
3207 on CPU — no spill onto the unseeded GPU",
3208 );
3209 }
3210
3211 #[test]
3228 fn compile_plan_places_large_compute_on_gpu_small_on_cpu_by_throughput() {
3229 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3230
3231 fn winner(cost: crate::kernel::CostFn, cuda0: DeviceLocation) -> DeviceLocation {
3232 let mut table = KernelBindingTable::new();
3233 table.register_full(
3234 OpKind::AddElementwise,
3235 &[DType::F32, DType::F32, DType::F32],
3236 BackendId::Cpu,
3237 noop_kernel,
3238 KernelCaps::empty(),
3239 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3240 cost,
3241 );
3242 table.register_full(
3243 OpKind::AddElementwise,
3244 &[DType::F32, DType::F32, DType::F32],
3245 BackendId::Cuda,
3246 noop_kernel_b,
3247 KernelCaps::empty(),
3248 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3249 cost,
3250 );
3251
3252 let (g, add_id) = build_add_graph();
3253 let order = topo_order(&g, add_id);
3254 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3255 if dev == DeviceLocation::Cpu {
3256 vec![BackendId::Cpu]
3257 } else {
3258 vec![]
3259 }
3260 };
3261 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3262 vec![(BackendId::Cuda, cuda0)]
3263 };
3264 let residency_fn =
3265 |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3266 let est = FlatEstimator { latency_ns: 100 };
3269 let cpu_caps_val = cpu_caps();
3270 let cuda_caps_val =
3271 crate::dispatch::derive_backend_caps(BackendId::Cuda, cuda0, &table);
3272 let caps_fn = |b: BackendId| -> Option<&BackendCapabilities> {
3273 match b {
3274 BackendId::Cpu => Some(&cpu_caps_val),
3275 BackendId::Cuda => Some(&cuda_caps_val),
3276 _ => None,
3277 }
3278 };
3279 let opts = PlanOptions::new()
3280 .with_pinned_device(DeviceLocation::Cpu)
3281 .with_placements_for_device(&placements_fn)
3282 .with_fallback_placements_for(&fallback_fn)
3283 .with_capabilities_for(&caps_fn)
3284 .with_transfer_estimator(&est)
3285 .with_input_residency(&residency_fn);
3286 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3287 plan.alternatives(add_id).unwrap().winner().unwrap().device
3288 }
3289
3290 assert_eq!(
3291 winner(cost_100, cuda0),
3292 DeviceLocation::Cpu,
3293 "SMALL op: the GPU's throughput win on 100 FLOPs (~3 ns) \
3294 can't overcome the 200 ns inbound transfer → stay on CPU",
3295 );
3296 assert_eq!(
3297 winner(cost_10_000_000, cuda0),
3298 cuda0,
3299 "LARGE op: the GPU's throughput win on 10 M FLOPs (~333 k ns) \
3300 dwarfs the 200 ns transfer → move to CUDA. RED under the \
3301 fixed 1-FLOP/ns prior (equal compute-ns → the transfer \
3302 always loses the GPU the placement)",
3303 );
3304 }
3305
3306 #[test]
3317 fn compile_plan_without_cost_placement_keeps_large_op_on_cpu() {
3318 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3319 let mut table = KernelBindingTable::new();
3320 table.register_full(
3321 OpKind::AddElementwise,
3322 &[DType::F32, DType::F32, DType::F32],
3323 BackendId::Cpu,
3324 noop_kernel,
3325 KernelCaps::empty(),
3326 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3327 cost_10_000_000,
3328 );
3329 table.register_full(
3330 OpKind::AddElementwise,
3331 &[DType::F32, DType::F32, DType::F32],
3332 BackendId::Cuda,
3333 noop_kernel_b,
3334 KernelCaps::empty(),
3335 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3336 cost_10_000_000,
3337 );
3338
3339 let (g, add_id) = build_add_graph();
3340 let order = topo_order(&g, add_id);
3341 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3342 if dev == DeviceLocation::Cpu {
3343 vec![BackendId::Cpu]
3344 } else {
3345 vec![]
3346 }
3347 };
3348 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3349 vec![(BackendId::Cuda, cuda0)]
3350 };
3351 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3352 let est = FlatEstimator { latency_ns: 100 };
3353 let cpu_caps_val = cpu_caps();
3354 let cuda_caps_val = crate::dispatch::derive_backend_caps(BackendId::Cuda, cuda0, &table);
3355 let caps_fn = |b: BackendId| -> Option<&BackendCapabilities> {
3356 match b {
3357 BackendId::Cpu => Some(&cpu_caps_val),
3358 BackendId::Cuda => Some(&cuda_caps_val),
3359 _ => None,
3360 }
3361 };
3362 let opts = PlanOptions::new()
3363 .with_pinned_device(DeviceLocation::Cpu)
3364 .with_placements_for_device(&placements_fn)
3365 .with_fallback_placements_for(&fallback_fn)
3366 .with_capabilities_for(&caps_fn)
3367 .with_transfer_estimator(&est)
3368 .with_input_residency(&residency_fn)
3369 .without_cost_placement();
3370 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3371 let set = plan.alternatives(add_id).unwrap();
3372 assert_eq!(
3373 set.winner().unwrap().device,
3374 DeviceLocation::Cpu,
3375 "without_cost_placement: the large GPU-favorable op stays on the \
3376 pinned CPU device (no relaxed cross-device enumeration)",
3377 );
3378 assert!(
3379 set.alternatives()
3380 .iter()
3381 .all(|c| c.device == DeviceLocation::Cpu),
3382 "no off-device candidate enumerated at all",
3383 );
3384 }
3385
3386 #[test]
3391 fn compile_plan_relaxed_huge_op_moves_when_kernel_gap_dominates() {
3392 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3393 let est = FlatEstimator { latency_ns: 1_000 };
3395 let set = relaxed_plan_with_costs(cost_10_000_000, cost_10, &est);
3396 let w = set.winner().unwrap();
3397 assert_eq!(w.device, cuda0, "kernel gap dominates → move");
3398 assert_eq!(
3399 w.inbound_transfer_ns, 2_000,
3400 "the move's two input crossings are priced on the winner",
3401 );
3402 assert!(
3403 set.alternatives().iter().all(|c| c.device == cuda0),
3404 "set pruned to the winner's device",
3405 );
3406 }
3407
3408 #[test]
3413 fn compile_plan_relaxed_zero_signal_ties_stay_local() {
3414 let est = FlatEstimator { latency_ns: 0 };
3415 let set = relaxed_plan_with_costs(unknown_cost, unknown_cost, &est);
3416 assert_eq!(
3417 set.winner().unwrap().device,
3418 DeviceLocation::Cpu,
3419 "ties break toward the decision device",
3420 );
3421 }
3422
3423 #[test]
3427 fn compile_plan_relaxed_single_device_plan_unchanged() {
3428 let mut table = KernelBindingTable::new();
3429 register_add_f32(
3430 &mut table,
3431 BackendId::Cpu,
3432 noop_kernel,
3433 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3434 );
3435 let (g, add_id) = build_add_graph();
3436 let order = topo_order(&g, add_id);
3437 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3438 if dev == DeviceLocation::Cpu {
3439 vec![BackendId::Cpu]
3440 } else {
3441 vec![]
3442 }
3443 };
3444 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> { Vec::new() };
3446 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3447 let cpu_caps_val = cpu_caps();
3448 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3449
3450 let base_opts = PlanOptions::new()
3451 .with_pinned_device(DeviceLocation::Cpu)
3452 .with_placements_for_device(&placements_fn)
3453 .with_fallback_placements_for(&fallback_fn)
3454 .with_capabilities_for(&caps_fn);
3455 let base = compile_plan(&g, &order, &table, &base_opts).expect("base");
3456
3457 let est = FlatEstimator {
3458 latency_ns: 1_000_000,
3459 };
3460 let wired_opts = PlanOptions::new()
3461 .with_pinned_device(DeviceLocation::Cpu)
3462 .with_placements_for_device(&placements_fn)
3463 .with_fallback_placements_for(&fallback_fn)
3464 .with_capabilities_for(&caps_fn)
3465 .with_transfer_estimator(&est)
3466 .with_input_residency(&residency_fn);
3467 let wired = compile_plan(&g, &order, &table, &wired_opts).expect("wired");
3468
3469 let a = base.alternatives(add_id).unwrap();
3470 let b = wired.alternatives(add_id).unwrap();
3471 assert_eq!(a.len(), b.len(), "same candidate count");
3472 for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
3473 assert_eq!(ca.backend, cb.backend);
3474 assert_eq!(ca.device, cb.device);
3475 assert_eq!(ca.kernel as usize, cb.kernel as usize, "same kernel ref");
3476 assert_eq!(ca.static_cost, cb.static_cost, "same Layer-1 cost");
3477 assert_eq!(cb.inbound_transfer_ns, 0, "no transfer term fires");
3478 }
3479 assert_eq!(a.context(), b.context(), "same decision context");
3480 }
3481
3482 #[test]
3487 fn compile_plan_relaxed_respects_explicit_placement_pin() {
3488 let mut table = KernelBindingTable::new();
3489 register_add_f32(
3490 &mut table,
3491 BackendId::Cpu,
3492 noop_kernel,
3493 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3494 );
3495 register_add_f32(
3496 &mut table,
3497 BackendId::Cuda,
3498 noop_kernel_b,
3499 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3500 );
3501 let (mut g, add_id) = build_add_graph();
3502 g.set_placement(add_id, DeviceLocation::Cpu);
3504 let order = topo_order(&g, add_id);
3505 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3506 if dev == DeviceLocation::Cpu {
3507 vec![BackendId::Cpu]
3508 } else {
3509 vec![]
3510 }
3511 };
3512 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3513 panic!(
3514 "fallback consulted for a hard-pinned node — explicit \
3515 placements must not enter the priced relax",
3516 );
3517 };
3518 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3519 let est = FlatEstimator { latency_ns: 0 };
3520 let cpu_caps_val = cpu_caps();
3521 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3522 let opts = PlanOptions::new()
3523 .with_pinned_device(DeviceLocation::Cpu)
3524 .with_placements_for_device(&placements_fn)
3525 .with_fallback_placements_for(&fallback_fn)
3526 .with_capabilities_for(&caps_fn)
3527 .with_transfer_estimator(&est)
3528 .with_input_residency(&residency_fn);
3529 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3530 assert_eq!(
3531 plan.alternatives(add_id).unwrap().winner().unwrap().device,
3532 DeviceLocation::Cpu,
3533 );
3534 }
3535
3536 #[test]
3539 fn compile_plan_relaxed_destructive_never_moves() {
3540 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3541 let mut table = KernelBindingTable::new();
3542 table.register_full(
3543 OpKind::ReluInplace,
3544 &[DType::F32, DType::F32],
3545 BackendId::Cpu,
3546 noop_kernel,
3547 KernelCaps::empty(),
3548 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3549 cost_600,
3550 );
3551 table.register_full(
3552 OpKind::ReluInplace,
3553 &[DType::F32, DType::F32],
3554 BackendId::Cuda,
3555 noop_kernel_b,
3556 KernelCaps::empty(),
3557 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3558 cost_10,
3559 );
3560 let mut g = Graph::new();
3561 let lhs = g.push(Node {
3562 op: Op::Const,
3563 inputs: vec![],
3564 shape: Shape::from_dims(&[3]),
3565 dtype: DType::F32,
3566 });
3567 let relu = g.push(Node {
3568 op: Op::ReluInplace,
3569 inputs: vec![lhs],
3570 shape: Shape::from_dims(&[3]),
3571 dtype: DType::F32,
3572 });
3573 let order = topo_order(&g, relu);
3574 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3575 if dev == DeviceLocation::Cpu {
3576 vec![BackendId::Cpu]
3577 } else {
3578 vec![]
3579 }
3580 };
3581 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3582 vec![(BackendId::Cuda, cuda0)]
3583 };
3584 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3585 let est = FlatEstimator { latency_ns: 0 };
3586 let cpu_caps_val = cpu_caps();
3587 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3588 let opts = PlanOptions::new()
3589 .with_pinned_device(DeviceLocation::Cpu)
3590 .with_placements_for_device(&placements_fn)
3591 .with_fallback_placements_for(&fallback_fn)
3592 .with_capabilities_for(&caps_fn)
3593 .with_transfer_estimator(&est)
3594 .with_input_residency(&residency_fn);
3595 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3596 assert_eq!(
3597 plan.alternatives(relu).unwrap().winner().unwrap().device,
3598 DeviceLocation::Cpu,
3599 "destructive op stays on the device owning its mutation target",
3600 );
3601 }
3602
3603 #[test]
3608 fn compile_plan_filter_rejected_pinned_device_falls_back() {
3609 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3610 let mut table = KernelBindingTable::new();
3611 register_add_f32(
3614 &mut table,
3615 BackendId::Cuda,
3616 noop_kernel_b,
3617 PrecisionGuarantee {
3618 bit_stable_on_same_hardware: false,
3619 ..PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU
3620 },
3621 );
3622 register_add_f32(
3623 &mut table,
3624 BackendId::Cpu,
3625 noop_kernel,
3626 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3627 );
3628 let mut g = Graph::new();
3629 let lhs = g.push(Node {
3630 op: Op::Const,
3631 inputs: vec![],
3632 shape: Shape::from_dims(&[3]),
3633 dtype: DType::F32,
3634 });
3635 let add = g.push(Node {
3636 op: Op::Add,
3637 inputs: vec![lhs, lhs],
3638 shape: Shape::from_dims(&[3]),
3639 dtype: DType::F32,
3640 });
3641 let order = topo_order(&g, add);
3642 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
3643 if dev == cuda0 {
3644 vec![BackendId::Cuda]
3645 } else {
3646 vec![]
3647 }
3648 };
3649 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3650 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
3651 };
3652 let opts = PlanOptions::new()
3653 .without_cost_population()
3654 .with_pinned_device(cuda0)
3655 .with_placements_for_device(&placements_fn)
3656 .with_fallback_placements_for(&fallback_fn)
3657 .with_precision_requirement(PrecisionRequirement::BIT_STABLE);
3658 let plan = compile_plan(&g, &order, &table, &opts)
3659 .expect("filter-rejected pin falls back instead of erroring");
3660 let alts = plan.alternatives(add).expect("Add planned via fallback");
3661 assert_eq!(alts.len(), 1, "fallback set frozen to one winner");
3662 let w = alts.winner().unwrap();
3663 assert_eq!(w.backend, BackendId::Cpu);
3664 assert_eq!(w.device, DeviceLocation::Cpu);
3665 assert!(
3666 w.precision.bit_stable_on_same_hardware,
3667 "the admissible off-device sibling won",
3668 );
3669 }
3670
3671 #[test]
3676 fn compile_plan_without_estimator_prices_nothing() {
3677 let mut table = KernelBindingTable::new();
3678 register_add_f32(
3679 &mut table,
3680 BackendId::Cpu,
3681 noop_kernel,
3682 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3683 );
3684 let (g, add_id) = build_add_graph();
3685 let order = topo_order(&g, add_id);
3686 let cpu_caps_val = cpu_caps();
3687 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3688 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3689
3690 let base_opts = PlanOptions::new().with_capabilities_for(&caps_fn);
3691 let base = compile_plan(&g, &order, &table, &base_opts).expect("base");
3692
3693 let with_residency = PlanOptions::new()
3694 .with_capabilities_for(&caps_fn)
3695 .with_input_residency(&residency_fn);
3696 let plan = compile_plan(&g, &order, &table, &with_residency).expect("plan");
3697
3698 let a = base.alternatives(add_id).unwrap();
3699 let b = plan.alternatives(add_id).unwrap();
3700 assert_eq!(a.len(), b.len());
3701 for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
3702 assert_eq!(ca.backend, cb.backend);
3703 assert_eq!(ca.device, cb.device);
3704 assert_eq!(ca.kernel as usize, cb.kernel as usize);
3705 assert_eq!(ca.inbound_transfer_ns, 0);
3706 assert_eq!(cb.inbound_transfer_ns, 0);
3707 }
3708 }
3709
3710 #[test]
3716 fn compile_plan_require_transfer_pricing_errors_without_estimator() {
3717 let mut table = KernelBindingTable::new();
3718 register_add_f32(
3719 &mut table,
3720 BackendId::Cpu,
3721 noop_kernel,
3722 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3723 );
3724 let (g, add_id) = build_add_graph();
3725 let order = topo_order(&g, add_id);
3726 let cpu_caps_val = cpu_caps();
3727 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3728
3729 let opts = PlanOptions::new()
3732 .with_capabilities_for(&caps_fn)
3733 .require_transfer_pricing();
3734 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
3735 let msg = format!("{err:?}");
3736 assert!(
3737 msg.contains("transfer") && (msg.contains("estimator") || msg.contains("pricing")),
3738 "error should name the missing transfer estimator / pricing; got: {msg}",
3739 );
3740 }
3741
3742 #[test]
3745 fn compile_plan_require_transfer_pricing_ok_with_estimator() {
3746 let mut table = KernelBindingTable::new();
3747 register_add_f32(
3748 &mut table,
3749 BackendId::Cpu,
3750 noop_kernel,
3751 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3752 );
3753 let (g, add_id) = build_add_graph();
3754 let order = topo_order(&g, add_id);
3755 let cpu_caps_val = cpu_caps();
3756 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3757 let est = FlatEstimator { latency_ns: 1000 };
3758
3759 let opts = PlanOptions::new()
3760 .with_capabilities_for(&caps_fn)
3761 .with_transfer_estimator(&est)
3762 .require_transfer_pricing();
3763 let plan = compile_plan(&g, &order, &table, &opts)
3764 .expect("require_transfer_pricing WITH an estimator must plan fine");
3765 assert!(plan.alternatives(add_id).is_some());
3766 }
3767
3768 #[test]
3769 fn compile_plan_passes_input_layouts_to_filter_chain() {
3770 let mut table = KernelBindingTable::new();
3774 table.register_full(
3775 OpKind::AddElementwise,
3776 &[DType::F32, DType::F32, DType::F32],
3777 BackendId::Cpu,
3778 noop_kernel,
3779 KernelCaps::empty(),
3780 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3781 unknown_cost,
3782 );
3783 table.register_full(
3784 OpKind::AddElementwise,
3785 &[DType::F32, DType::F32, DType::F32],
3786 BackendId::Cpu,
3787 noop_kernel_b,
3788 KernelCaps::strided_input(),
3789 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3790 unknown_cost,
3791 );
3792
3793 let mut g = Graph::new();
3795 let lhs = g.push(Node {
3796 op: Op::Const,
3797 inputs: vec![],
3798 shape: Shape::from_dims(&[6]),
3799 dtype: DType::F32,
3800 });
3801 let strides: StrideVec = smallvec![2isize];
3804 g.set_layout(lhs, Layout::new(Shape::from_dims(&[6]), strides, 0));
3805 let rhs = g.push(Node {
3806 op: Op::Const,
3807 inputs: vec![],
3808 shape: Shape::from_dims(&[6]),
3809 dtype: DType::F32,
3810 });
3811 let add = g.push(Node {
3812 op: Op::Add,
3813 inputs: vec![lhs, rhs],
3814 shape: Shape::from_dims(&[6]),
3815 dtype: DType::F32,
3816 });
3817 g.set_target_backend(add, BackendId::Cpu);
3818 let order = topo_order(&g, add);
3819 let opts = PlanOptions::new().without_cost_population();
3820 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3821 let alts = plan.alternatives(add).unwrap();
3822 assert_eq!(alts.len(), 1);
3825 assert!(alts.winner().unwrap().caps.strided_input);
3826 }
3827
3828 struct BytesEstimator {
3835 latency_ns: u64,
3836 ns_per_byte: u64,
3837 }
3838
3839 impl crate::ranker::TransferEstimator for BytesEstimator {
3840 fn estimate_transfer_ns(
3841 &self,
3842 src: DeviceLocation,
3843 dst: DeviceLocation,
3844 bytes: u64,
3845 ) -> u64 {
3846 if src == dst {
3847 return 0;
3848 }
3849 self.latency_ns
3850 .saturating_add(bytes.saturating_mul(self.ns_per_byte))
3851 }
3852 }
3853
3854 fn cost_50(
3855 _: &[Shape],
3856 _: &[DType],
3857 _: &OpParams,
3858 _: &BackendCapabilities,
3859 ) -> crate::fused::CostEstimate {
3860 crate::fused::CostEstimate {
3861 flops: 50,
3862 bytes_moved: 0,
3863 kernel_overhead_ns: 0,
3864 }
3865 }
3866 fn cost_100(
3867 _: &[Shape],
3868 _: &[DType],
3869 _: &OpParams,
3870 _: &BackendCapabilities,
3871 ) -> crate::fused::CostEstimate {
3872 crate::fused::CostEstimate {
3873 flops: 100,
3874 bytes_moved: 0,
3875 kernel_overhead_ns: 0,
3876 }
3877 }
3878 fn cost_300(
3879 _: &[Shape],
3880 _: &[DType],
3881 _: &OpParams,
3882 _: &BackendCapabilities,
3883 ) -> crate::fused::CostEstimate {
3884 crate::fused::CostEstimate {
3885 flops: 300,
3886 bytes_moved: 0,
3887 kernel_overhead_ns: 0,
3888 }
3889 }
3890 fn cost_800(
3891 _: &[Shape],
3892 _: &[DType],
3893 _: &OpParams,
3894 _: &BackendCapabilities,
3895 ) -> crate::fused::CostEstimate {
3896 crate::fused::CostEstimate {
3897 flops: 800,
3898 bytes_moved: 0,
3899 kernel_overhead_ns: 0,
3900 }
3901 }
3902 fn cost_5000(
3903 _: &[Shape],
3904 _: &[DType],
3905 _: &OpParams,
3906 _: &BackendCapabilities,
3907 ) -> crate::fused::CostEstimate {
3908 crate::fused::CostEstimate {
3909 flops: 5000,
3910 bytes_moved: 0,
3911 kernel_overhead_ns: 0,
3912 }
3913 }
3914 fn cost_100_000(
3915 _: &[Shape],
3916 _: &[DType],
3917 _: &OpParams,
3918 _: &BackendCapabilities,
3919 ) -> crate::fused::CostEstimate {
3920 crate::fused::CostEstimate {
3921 flops: 100_000,
3922 bytes_moved: 0,
3923 kernel_overhead_ns: 0,
3924 }
3925 }
3926
3927 fn register_unary_f32(
3929 table: &mut KernelBindingTable,
3930 op: OpKind,
3931 backend: BackendId,
3932 kernel: crate::kernel::KernelRef,
3933 cost: crate::kernel::CostFn,
3934 ) {
3935 table.register_full(
3936 op,
3937 &[DType::F32, DType::F32],
3938 backend,
3939 kernel,
3940 KernelCaps::empty(),
3941 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3942 cost,
3943 );
3944 }
3945
3946 fn push_f32(g: &mut Graph, op: Op, inputs: Vec<NodeId>, dims: &[usize]) -> NodeId {
3947 g.push(Node {
3948 op,
3949 inputs,
3950 shape: Shape::from_dims(dims),
3951 dtype: DType::F32,
3952 })
3953 }
3954
3955 #[test]
3970 fn dp_mid_sequence_gpu_segment_beats_all_cpu_and_all_gpu() {
3971 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3972 let mut table = KernelBindingTable::new();
3973 register_unary_f32(
3974 &mut table,
3975 OpKind::SqrElementwise,
3976 BackendId::Cpu,
3977 noop_kernel,
3978 cost_100,
3979 );
3980 register_unary_f32(
3981 &mut table,
3982 OpKind::SqrElementwise,
3983 BackendId::Cuda,
3984 noop_kernel_b,
3985 cost_5000,
3986 );
3987 register_unary_f32(
3988 &mut table,
3989 OpKind::NegElementwise,
3990 BackendId::Cpu,
3991 noop_kernel,
3992 cost_800,
3993 );
3994 register_unary_f32(
3995 &mut table,
3996 OpKind::NegElementwise,
3997 BackendId::Cuda,
3998 noop_kernel_b,
3999 cost_100,
4000 );
4001
4002 let mut g = Graph::new();
4003 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4004 let n1 = push_f32(&mut g, Op::Sqr, vec![c], &[4]);
4005 let n2 = push_f32(&mut g, Op::Neg, vec![n1], &[4]);
4006 let n3 = push_f32(&mut g, Op::Neg, vec![n2], &[4]);
4007 let n4 = push_f32(&mut g, Op::Neg, vec![n3], &[4]);
4008 let n5 = push_f32(&mut g, Op::Sqr, vec![n4], &[4]);
4009 let order = topo_order(&g, n5);
4010
4011 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4012 if dev == DeviceLocation::Cpu {
4013 vec![BackendId::Cpu]
4014 } else {
4015 vec![BackendId::Cuda]
4016 }
4017 };
4018 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4019 if dev == DeviceLocation::Cpu {
4020 vec![(BackendId::Cuda, cuda0)]
4021 } else {
4022 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4023 }
4024 };
4025 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4026 (id == c).then_some(DeviceLocation::Cpu)
4027 };
4028 let est = FlatEstimator { latency_ns: 1_000 };
4029 let cpu_caps_val = cpu_caps();
4030 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4031 let opts = PlanOptions::new()
4032 .with_pinned_device(DeviceLocation::Cpu)
4033 .with_placements_for_device(&placements_fn)
4034 .with_fallback_placements_for(&fallback_fn)
4035 .with_capabilities_for(&caps_fn)
4036 .with_transfer_estimator(&est)
4037 .with_input_residency(&residency_fn);
4038 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4039
4040 let dev_of = |id: NodeId| plan.alternatives(id).unwrap().winner().unwrap().device;
4041 assert_eq!(
4042 dev_of(n1),
4043 DeviceLocation::Cpu,
4044 "GPU-hostile entry stays CPU"
4045 );
4046 assert_eq!(dev_of(n2), cuda0, "segment start migrates");
4047 assert_eq!(dev_of(n3), cuda0, "segment interior stays GPU");
4048 assert_eq!(dev_of(n4), cuda0, "segment end stays GPU");
4049 assert_eq!(dev_of(n5), DeviceLocation::Cpu, "GPU-hostile exit returns");
4050
4051 let inbound = |id: NodeId| {
4055 plan.alternatives(id)
4056 .unwrap()
4057 .winner()
4058 .unwrap()
4059 .inbound_transfer_ns
4060 };
4061 assert_eq!(
4062 inbound(n2),
4063 1_000,
4064 "entry crossing priced on the first GPU op"
4065 );
4066 assert_eq!(inbound(n3), 0);
4067 assert_eq!(inbound(n4), 0);
4068 assert_eq!(inbound(n5), 1_000, "exit crossing priced on the return op");
4069
4070 for id in [n1, n2, n3, n4, n5] {
4073 let d = dev_of(id);
4074 assert!(
4075 plan.alternatives(id)
4076 .unwrap()
4077 .alternatives()
4078 .iter()
4079 .all(|c| c.device == d),
4080 "set pruned to the DP-committed device",
4081 );
4082 }
4083 }
4084
4085 #[test]
4101 fn dp_fused_op_loses_when_stranding_exceeds_local_win() {
4102 use fuel_graph::registry::{FusedOpParams, FusedOps};
4103
4104 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4105 let mut table = KernelBindingTable::new();
4106 register_unary_f32(
4107 &mut table,
4108 OpKind::NegElementwise,
4109 BackendId::Cpu,
4110 noop_kernel,
4111 cost_100_000,
4112 );
4113 register_unary_f32(
4114 &mut table,
4115 OpKind::NegElementwise,
4116 BackendId::Cuda,
4117 noop_kernel_b,
4118 cost_100,
4119 );
4120 register_unary_f32(
4121 &mut table,
4122 OpKind::SoftmaxLastDim,
4123 BackendId::Cpu,
4124 noop_kernel,
4125 cost_300,
4126 );
4127 register_unary_f32(
4128 &mut table,
4129 OpKind::SoftmaxLastDim,
4130 BackendId::Cuda,
4131 noop_kernel_b,
4132 cost_100,
4133 );
4134 register_unary_f32(
4136 &mut table,
4137 OpKind::SqrElementwise,
4138 BackendId::Cpu,
4139 noop_kernel,
4140 cost_100,
4141 );
4142
4143 let mut g = Graph::new();
4144 let c = push_f32(&mut g, Op::Const, vec![], &[1]);
4145 let n1 = push_f32(&mut g, Op::Neg, vec![c], &[1]);
4146 let f = push_f32(
4147 &mut g,
4148 Op::Fused(FusedOps::SOFTMAX_LAST_DIM, FusedOpParams::SoftmaxLastDim),
4149 vec![n1],
4150 &[256],
4151 );
4152 let n2 = push_f32(&mut g, Op::Sqr, vec![f], &[256]);
4153 let order = topo_order(&g, n2);
4154
4155 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4156 if dev == DeviceLocation::Cpu {
4157 vec![BackendId::Cpu]
4158 } else {
4159 vec![BackendId::Cuda]
4160 }
4161 };
4162 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4163 if dev == DeviceLocation::Cpu {
4164 vec![(BackendId::Cuda, cuda0)]
4165 } else {
4166 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4167 }
4168 };
4169 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4170 (id == c).then_some(DeviceLocation::Cpu)
4171 };
4172 let est = BytesEstimator {
4173 latency_ns: 10,
4174 ns_per_byte: 1,
4175 };
4176 let cpu_caps_val = cpu_caps();
4177 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4178 let opts = PlanOptions::new()
4179 .with_pinned_device(DeviceLocation::Cpu)
4180 .with_placements_for_device(&placements_fn)
4181 .with_fallback_placements_for(&fallback_fn)
4182 .with_capabilities_for(&caps_fn)
4183 .with_transfer_estimator(&est)
4184 .with_input_residency(&residency_fn);
4185 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4186
4187 let dev_of = |id: NodeId| plan.alternatives(id).unwrap().winner().unwrap().device;
4188 assert_eq!(dev_of(n1), cuda0, "the huge-win producer migrates");
4189 assert_eq!(
4190 dev_of(f),
4191 DeviceLocation::Cpu,
4192 "the locally-faster fused op stays where its output is needed",
4193 );
4194 assert_eq!(dev_of(n2), DeviceLocation::Cpu);
4195 assert!(
4196 plan.alternatives(f)
4197 .unwrap()
4198 .alternatives()
4199 .iter()
4200 .all(|c| c.device == DeviceLocation::Cpu),
4201 "fused set pruned to the committed device",
4202 );
4203 }
4204
4205 #[test]
4213 fn dp_exit_pricing_keeps_final_op_on_realize_target() {
4214 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4215 let mut table = KernelBindingTable::new();
4216 register_unary_f32(
4217 &mut table,
4218 OpKind::NegElementwise,
4219 BackendId::Cpu,
4220 noop_kernel,
4221 cost_50,
4222 );
4223 register_unary_f32(
4224 &mut table,
4225 OpKind::NegElementwise,
4226 BackendId::Cuda,
4227 noop_kernel_b,
4228 cost_100,
4229 );
4230
4231 let mut g = Graph::new();
4232 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4233 let n = push_f32(&mut g, Op::Neg, vec![c], &[4]);
4234 let order = topo_order(&g, n);
4235
4236 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4237 if dev == DeviceLocation::Cpu {
4238 vec![BackendId::Cpu]
4239 } else {
4240 vec![BackendId::Cuda]
4241 }
4242 };
4243 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4244 if dev == DeviceLocation::Cpu {
4245 vec![(BackendId::Cuda, cuda0)]
4246 } else {
4247 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4248 }
4249 };
4250 let residency_fn =
4251 move |id: NodeId| -> Option<DeviceLocation> { (id == c).then_some(cuda0) };
4252 let est = FlatEstimator { latency_ns: 1_000 };
4253 let cpu_caps_val = cpu_caps();
4254 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4255 let opts = PlanOptions::new()
4256 .with_pinned_device(DeviceLocation::Cpu)
4257 .with_placements_for_device(&placements_fn)
4258 .with_fallback_placements_for(&fallback_fn)
4259 .with_capabilities_for(&caps_fn)
4260 .with_transfer_estimator(&est)
4261 .with_input_residency(&residency_fn);
4262 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4263 let w = plan.alternatives(n).unwrap().winner().unwrap();
4264 assert_eq!(
4265 w.device,
4266 DeviceLocation::Cpu,
4267 "exit pricing flips the locally-winning GPU placement",
4268 );
4269 assert_eq!(
4270 w.inbound_transfer_ns, 1_000,
4271 "the GPU-resident input's crossing is priced on the CPU winner",
4272 );
4273 }
4274
4275 #[test]
4278 fn dp_exit_pricing_does_not_pin_when_kernel_gap_dominates() {
4279 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4280 let mut table = KernelBindingTable::new();
4281 register_unary_f32(
4282 &mut table,
4283 OpKind::NegElementwise,
4284 BackendId::Cpu,
4285 noop_kernel,
4286 cost_10_000_000,
4287 );
4288 register_unary_f32(
4289 &mut table,
4290 OpKind::NegElementwise,
4291 BackendId::Cuda,
4292 noop_kernel_b,
4293 cost_100,
4294 );
4295
4296 let mut g = Graph::new();
4297 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4298 let n = push_f32(&mut g, Op::Neg, vec![c], &[4]);
4299 let order = topo_order(&g, n);
4300
4301 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4302 if dev == DeviceLocation::Cpu {
4303 vec![BackendId::Cpu]
4304 } else {
4305 vec![BackendId::Cuda]
4306 }
4307 };
4308 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4309 if dev == DeviceLocation::Cpu {
4310 vec![(BackendId::Cuda, cuda0)]
4311 } else {
4312 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4313 }
4314 };
4315 let residency_fn =
4316 move |id: NodeId| -> Option<DeviceLocation> { (id == c).then_some(cuda0) };
4317 let est = FlatEstimator { latency_ns: 1_000 };
4318 let cpu_caps_val = cpu_caps();
4319 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4320 let opts = PlanOptions::new()
4321 .with_pinned_device(DeviceLocation::Cpu)
4322 .with_placements_for_device(&placements_fn)
4323 .with_fallback_placements_for(&fallback_fn)
4324 .with_capabilities_for(&caps_fn)
4325 .with_transfer_estimator(&est)
4326 .with_input_residency(&residency_fn);
4327 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4328 assert_eq!(
4329 plan.alternatives(n).unwrap().winner().unwrap().device,
4330 cuda0
4331 );
4332 }
4333
4334 #[test]
4340 fn dp_single_device_plan_equals_greedy_plan() {
4341 let mut table = KernelBindingTable::new();
4342 register_add_f32(
4343 &mut table,
4344 BackendId::Cpu,
4345 noop_kernel,
4346 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4347 );
4348 register_add_f32(
4349 &mut table,
4350 BackendId::Cuda,
4351 noop_kernel_b,
4352 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4353 );
4354 let (g, add_id) = build_add_graph();
4355 let order = topo_order(&g, add_id);
4356 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4359 if dev == DeviceLocation::Cpu {
4360 vec![BackendId::Cpu, BackendId::Cuda]
4361 } else {
4362 vec![]
4363 }
4364 };
4365 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> { Vec::new() };
4366 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
4367 let cpu_caps_val = cpu_caps();
4368 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4369
4370 let base_opts = PlanOptions::new()
4371 .with_placements_for_device(&placements_fn)
4372 .with_capabilities_for(&caps_fn);
4373 let base = compile_plan(&g, &order, &table, &base_opts).expect("base");
4374
4375 let est = FlatEstimator {
4376 latency_ns: 1_000_000,
4377 };
4378 let wired_opts = PlanOptions::new()
4379 .with_placements_for_device(&placements_fn)
4380 .with_fallback_placements_for(&fallback_fn)
4381 .with_capabilities_for(&caps_fn)
4382 .with_transfer_estimator(&est)
4383 .with_input_residency(&residency_fn);
4384 let wired = compile_plan(&g, &order, &table, &wired_opts).expect("wired");
4385
4386 assert_eq!(base.alternatives.len(), wired.alternatives.len());
4387 let a = base.alternatives(add_id).unwrap();
4388 let b = wired.alternatives(add_id).unwrap();
4389 assert_eq!(a.len(), b.len(), "same candidate count");
4390 for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
4391 assert_eq!(ca.backend, cb.backend);
4392 assert_eq!(ca.device, cb.device);
4393 assert_eq!(ca.kernel as usize, cb.kernel as usize, "same kernel ref");
4394 assert_eq!(ca.static_cost, cb.static_cost, "same Layer-1 cost");
4395 assert_eq!(cb.inbound_transfer_ns, 0, "no transfer term fires");
4396 }
4397 assert_eq!(a.context(), b.context(), "same decision context");
4398 }
4399
4400 fn run_diamond_regime(latency_ns: u64, expect: DeviceLocation) {
4404 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4405 let mut table = KernelBindingTable::new();
4406 for op in [
4407 OpKind::NegElementwise,
4408 OpKind::SqrElementwise,
4409 OpKind::ReluElementwise,
4410 ] {
4411 register_unary_f32(&mut table, op, BackendId::Cpu, noop_kernel, cost_100);
4412 register_unary_f32(&mut table, op, BackendId::Cuda, noop_kernel_b, cost_10);
4413 }
4414 table.register_full(
4415 OpKind::AddElementwise,
4416 &[DType::F32, DType::F32, DType::F32],
4417 BackendId::Cpu,
4418 noop_kernel,
4419 KernelCaps::empty(),
4420 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4421 cost_100,
4422 );
4423 table.register_full(
4424 OpKind::AddElementwise,
4425 &[DType::F32, DType::F32, DType::F32],
4426 BackendId::Cuda,
4427 noop_kernel_b,
4428 KernelCaps::empty(),
4429 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4430 cost_10,
4431 );
4432
4433 let mut g = Graph::new();
4434 let c0 = push_f32(&mut g, Op::Const, vec![], &[4]);
4435 let a = push_f32(&mut g, Op::Neg, vec![c0], &[4]);
4436 let b = push_f32(&mut g, Op::Sqr, vec![a], &[4]);
4437 let c2 = push_f32(&mut g, Op::Relu, vec![a], &[4]);
4438 let d = push_f32(&mut g, Op::Add, vec![b, c2], &[4]);
4439 let order = topo_order(&g, d);
4440
4441 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4442 if dev == DeviceLocation::Cpu {
4443 vec![BackendId::Cpu]
4444 } else {
4445 vec![BackendId::Cuda]
4446 }
4447 };
4448 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4449 if dev == DeviceLocation::Cpu {
4450 vec![(BackendId::Cuda, cuda0)]
4451 } else {
4452 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4453 }
4454 };
4455 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4456 (id == c0).then_some(DeviceLocation::Cpu)
4457 };
4458 let est = FlatEstimator { latency_ns };
4459 let cpu_caps_val = cpu_caps();
4460 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4461 let opts = PlanOptions::new()
4462 .with_pinned_device(DeviceLocation::Cpu)
4463 .with_placements_for_device(&placements_fn)
4464 .with_fallback_placements_for(&fallback_fn)
4465 .with_capabilities_for(&caps_fn)
4466 .with_transfer_estimator(&est)
4467 .with_input_residency(&residency_fn);
4468 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4469 for id in [a, b, c2, d] {
4470 assert_eq!(
4471 plan.alternatives(id).unwrap().winner().unwrap().device,
4472 expect,
4473 "diamond join must commit a consistent placement",
4474 );
4475 }
4476 }
4477
4478 #[test]
4483 fn dp_diamond_join_merges_consistently() {
4484 run_diamond_regime(1_000_000, DeviceLocation::Cpu);
4486 run_diamond_regime(0, DeviceLocation::Cuda { gpu_id: 0 });
4488 }
4489
4490 #[test]
4496 fn dp_thousand_node_chain_plans_within_sanity_bound() {
4497 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4498 let mut table = KernelBindingTable::new();
4499 register_unary_f32(
4502 &mut table,
4503 OpKind::NegElementwise,
4504 BackendId::Cpu,
4505 noop_kernel,
4506 cost_100,
4507 );
4508 register_unary_f32(
4509 &mut table,
4510 OpKind::NegElementwise,
4511 BackendId::Cuda,
4512 noop_kernel_b,
4513 cost_100,
4514 );
4515
4516 let mut g = Graph::new();
4517 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4518 let mut prev = c;
4519 let mut nodes = Vec::with_capacity(1000);
4520 for _ in 0..1000 {
4521 let n = push_f32(&mut g, Op::Neg, vec![prev], &[4]);
4522 nodes.push(n);
4523 prev = n;
4524 }
4525 let order = topo_order(&g, prev);
4526
4527 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4528 if dev == DeviceLocation::Cpu {
4529 vec![BackendId::Cpu]
4530 } else {
4531 vec![BackendId::Cuda]
4532 }
4533 };
4534 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4535 if dev == DeviceLocation::Cpu {
4536 vec![(BackendId::Cuda, cuda0)]
4537 } else {
4538 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4539 }
4540 };
4541 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4542 (id == c).then_some(DeviceLocation::Cpu)
4543 };
4544 let est = FlatEstimator { latency_ns: 10 };
4545 let cpu_caps_val = cpu_caps();
4546 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4547 let opts = PlanOptions::new()
4548 .with_pinned_device(DeviceLocation::Cpu)
4549 .with_placements_for_device(&placements_fn)
4550 .with_fallback_placements_for(&fallback_fn)
4551 .with_capabilities_for(&caps_fn)
4552 .with_transfer_estimator(&est)
4553 .with_input_residency(&residency_fn);
4554
4555 let start = std::time::Instant::now();
4556 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4557 let elapsed = start.elapsed();
4558 assert!(
4559 elapsed.as_secs() < 5,
4560 "1000-node DP plan took {elapsed:?} — pathological scaling",
4561 );
4562
4563 assert_eq!(plan.alternatives.len(), 1000);
4564 for &n in &nodes {
4565 assert_eq!(
4566 plan.alternatives(n).unwrap().winner().unwrap().device,
4567 DeviceLocation::Cpu,
4568 "equal-cost ties break toward the decision device end-to-end",
4569 );
4570 }
4571 }
4572
4573 #[test]
4577 fn dp_chain_connects_through_view_passthroughs() {
4578 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4579 let mut table = KernelBindingTable::new();
4580 register_unary_f32(
4584 &mut table,
4585 OpKind::NegElementwise,
4586 BackendId::Cpu,
4587 noop_kernel,
4588 cost_800,
4589 );
4590 register_unary_f32(
4591 &mut table,
4592 OpKind::NegElementwise,
4593 BackendId::Cuda,
4594 noop_kernel_b,
4595 cost_100,
4596 );
4597
4598 let mut g = Graph::new();
4599 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4600 let n1 = push_f32(&mut g, Op::Neg, vec![c], &[4]);
4601 let r = push_f32(
4602 &mut g,
4603 Op::Reshape(Shape::from_dims(&[2, 2])),
4604 vec![n1],
4605 &[2, 2],
4606 );
4607 let n2 = push_f32(&mut g, Op::Neg, vec![r], &[2, 2]);
4608 let n3 = push_f32(&mut g, Op::Neg, vec![n2], &[2, 2]);
4609 let order = topo_order(&g, n3);
4610
4611 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4612 if dev == DeviceLocation::Cpu {
4613 vec![BackendId::Cpu]
4614 } else {
4615 vec![BackendId::Cuda]
4616 }
4617 };
4618 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4619 if dev == DeviceLocation::Cpu {
4620 vec![(BackendId::Cuda, cuda0)]
4621 } else {
4622 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4623 }
4624 };
4625 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4626 (id == c).then_some(DeviceLocation::Cpu)
4627 };
4628 let est = FlatEstimator { latency_ns: 1_000 };
4629 let cpu_caps_val = cpu_caps();
4630 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4631 let opts = PlanOptions::new()
4632 .with_pinned_device(DeviceLocation::Cpu)
4633 .with_placements_for_device(&placements_fn)
4634 .with_fallback_placements_for(&fallback_fn)
4635 .with_capabilities_for(&caps_fn)
4636 .with_transfer_estimator(&est)
4637 .with_input_residency(&residency_fn);
4638 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4639
4640 for id in [n1, n2, n3] {
4644 assert_eq!(
4645 plan.alternatives(id).unwrap().winner().unwrap().device,
4646 cuda0,
4647 "the chain must not break at the Reshape pass-through",
4648 );
4649 }
4650 assert!(
4651 plan.alternatives(r).is_none(),
4652 "Reshape carries no plan entry"
4653 );
4654 }
4655
4656 #[cfg(feature = "telemetry")]
4661 mod telemetry_wiring {
4662 use super::*;
4663 use crate::telemetry::{
4664 Contiguity, FdxOperandDesc, HwStamp, StructureKeyProvider, StructureKeyToken,
4665 TelemetryConfig, TelemetryHooks, TelemetryMode, TelemetrySink,
4666 };
4667 use std::sync::Mutex;
4668
4669 struct StubProvider;
4673 impl StructureKeyProvider for StubProvider {
4674 fn structure_key(
4675 &self,
4676 op_class: &str,
4677 operands: &[FdxOperandDesc],
4678 _arch: &str,
4679 ) -> Option<StructureKeyToken> {
4680 Some(StructureKeyToken(format!(
4681 "{op_class}:stub:n={}",
4682 operands.len()
4683 )))
4684 }
4685 }
4686
4687 fn cpu_hw() -> HwStamp {
4688 HwStamp {
4689 compute_capability: None,
4690 hardware_sku: "test-cpu".into(),
4691 driver_version: "n/a".into(),
4692 }
4693 }
4694
4695 fn generic_only_add_table() -> KernelBindingTable {
4700 let mut table = KernelBindingTable::new();
4701 table.register_full_with_source_generic(
4702 OpKind::AddElementwise,
4703 &[DType::F32, DType::F32, DType::F32],
4704 BackendId::Cpu,
4705 noop_kernel,
4706 KernelCaps::strided_input(),
4707 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4708 unknown_cost,
4709 "baracuda-generic-strided",
4710 true, 0, None, );
4714 table
4715 }
4716
4717 #[test]
4729 fn generic_only_cell_emits_one_aggregated_miss_through_compile_plan() {
4730 let table = generic_only_add_table();
4731 let (g, add_id) = build_add_graph();
4732 let order = topo_order(&g, add_id);
4733
4734 let sink = Mutex::new(TelemetrySink::new());
4735 let provider = StubProvider;
4736 let config = TelemetryConfig {
4737 mode: TelemetryMode::Coarse,
4738 out_path: None,
4739 };
4740 let hooks = TelemetryHooks {
4741 config: &config,
4742 sink: &sink,
4743 provider: &provider,
4744 hw: cpu_hw(),
4745 };
4746 let opts = PlanOptions::new()
4747 .without_cost_population()
4748 .with_telemetry(&hooks);
4749 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4750
4751 let sink = sink.into_inner().expect("sink lock");
4752 assert_eq!(
4753 sink.miss_cell_count(),
4754 1,
4755 "a generic-only cell must emit exactly one aggregated miss cell",
4756 );
4757 let recs = sink.miss_records();
4758 assert_eq!(recs.len(), 1);
4759 assert_eq!(
4763 recs[0].wanted,
4764 StructureKeyToken("AddElementwise:stub:n=3".into()),
4765 "the wanted token must reflect the live op_class + operands",
4766 );
4767 assert_eq!(recs[0].fallback.kernel_source, "baracuda-generic-strided");
4768 assert_eq!(recs[0].fallback.op, OpKind::AddElementwise);
4769 assert_eq!(recs[0].fallback.backend, BackendId::Cpu);
4770 assert_eq!(
4771 recs[0].fallback.dtypes,
4772 vec![DType::F32, DType::F32, DType::F32],
4773 );
4774 assert_eq!(recs[0].count, 1);
4775 assert_eq!(recs[0].hw, cpu_hw());
4776 }
4777
4778 #[test]
4784 fn telemetry_off_emits_nothing_and_does_not_change_the_plan() {
4785 let table = generic_only_add_table();
4786 let (g, add_id) = build_add_graph();
4787 let order = topo_order(&g, add_id);
4788
4789 let sink = Mutex::new(TelemetrySink::new());
4790 let provider = StubProvider;
4791 let config = TelemetryConfig::default(); let hooks = TelemetryHooks {
4793 config: &config,
4794 sink: &sink,
4795 provider: &provider,
4796 hw: cpu_hw(),
4797 };
4798 let opts = PlanOptions::new()
4799 .without_cost_population()
4800 .with_telemetry(&hooks);
4801 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4802
4803 assert!(
4804 sink.into_inner().expect("sink lock").is_empty(),
4805 "Off mode must emit nothing",
4806 );
4807 let alts = plan.alternatives(add_id).expect("Add alternatives present");
4809 assert_eq!(alts.len(), 1);
4810 assert_eq!(alts.winner().unwrap().backend, BackendId::Cpu);
4811 }
4812
4813 #[test]
4818 fn specialized_winner_emits_no_miss() {
4819 let mut table = KernelBindingTable::new();
4820 register_add_f32(
4822 &mut table,
4823 BackendId::Cpu,
4824 noop_kernel,
4825 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4826 );
4827 let (g, add_id) = build_add_graph();
4828 let order = topo_order(&g, add_id);
4829
4830 let sink = Mutex::new(TelemetrySink::new());
4831 let provider = StubProvider;
4832 let config = TelemetryConfig {
4833 mode: TelemetryMode::Coarse,
4834 out_path: None,
4835 };
4836 let hooks = TelemetryHooks {
4837 config: &config,
4838 sink: &sink,
4839 provider: &provider,
4840 hw: cpu_hw(),
4841 };
4842 let opts = PlanOptions::new()
4843 .without_cost_population()
4844 .with_telemetry(&hooks);
4845 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4846
4847 let sink = sink.into_inner().expect("sink lock");
4848 assert!(
4849 sink.miss_records().is_empty(),
4850 "a specialized (is_generic=false) winner must emit no miss",
4851 );
4852 assert_eq!(
4856 sink.dispatch_cell_count(),
4857 1,
4858 "a specialized winner still emits its dispatch record",
4859 );
4860 let _ = add_id;
4861 }
4862
4863 fn two_sibling_add_table() -> KernelBindingTable {
4871 let mut table = KernelBindingTable::new();
4872 table.register_full_with_source(
4873 OpKind::AddElementwise,
4874 &[DType::F32, DType::F32, DType::F32],
4875 BackendId::Cpu,
4876 noop_kernel,
4877 KernelCaps::empty(),
4878 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4879 unknown_cost,
4880 "portable-cpu",
4881 );
4882 table.register_full_with_source(
4883 OpKind::AddElementwise,
4884 &[DType::F32, DType::F32, DType::F32],
4885 BackendId::Cpu,
4886 noop_kernel_b,
4887 KernelCaps::empty(),
4888 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4889 unknown_cost,
4890 "aocl",
4891 );
4892 table
4893 }
4894
4895 #[test]
4907 fn detailed_dispatch_record_emitted_with_per_candidate_judge_latency() {
4908 use crate::ranker::HashMapJudge;
4909 use fuel_ir::dispatch::SizeClass;
4910
4911 let table = two_sibling_add_table();
4912 let (g, add_id) = build_add_graph();
4913 let order = topo_order(&g, add_id);
4914
4915 let sc = SizeClass::from_elem_count(3);
4919 let mut judge = HashMapJudge::new();
4920 judge.insert(
4921 OpKind::AddElementwise,
4922 DType::F32,
4923 sc,
4924 BackendId::Cpu,
4925 "portable-cpu",
4926 41_230,
4927 0,
4928 );
4929
4930 let sink = Mutex::new(TelemetrySink::new());
4931 let provider = StubProvider;
4932 let config = TelemetryConfig {
4933 mode: TelemetryMode::Detailed,
4934 out_path: None,
4935 };
4936 let hooks = TelemetryHooks {
4937 config: &config,
4938 sink: &sink,
4939 provider: &provider,
4940 hw: cpu_hw(),
4941 };
4942 let opts = PlanOptions::new()
4943 .without_cost_population()
4944 .with_telemetry(&hooks)
4945 .with_judge(&judge);
4946 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4947
4948 let sink = sink.into_inner().expect("sink lock");
4949 assert_eq!(
4950 sink.dispatch_cell_count(),
4951 1,
4952 "one planned cell ⇒ exactly one aggregated dispatch record",
4953 );
4954 assert_eq!(
4955 sink.miss_cell_count(),
4956 0,
4957 "specialized winners emit no miss"
4958 );
4959 let recs = sink.dispatch_records();
4960 assert_eq!(recs.len(), 1);
4961 let rec = &recs[0];
4962 assert_eq!(rec.chosen.kernel_source, "portable-cpu");
4964 assert_eq!(rec.chosen.op, OpKind::AddElementwise);
4965 assert_eq!(rec.chosen.backend, BackendId::Cpu);
4966 assert_eq!(rec.chosen.dtypes, vec![DType::F32, DType::F32, DType::F32]);
4967 assert_eq!(
4968 rec.chosen.kernel_revision_hash, 0,
4969 "hand-written ⇒ untracked"
4970 );
4971 assert_eq!(rec.count, 1);
4972 assert_eq!(rec.hw, cpu_hw());
4973 assert_eq!(
4976 rec.structure_key,
4977 Some(StructureKeyToken("AddElementwise:stub:n=3".into())),
4978 );
4979 assert_eq!(rec.candidates.len(), 2, "both admitted alternatives appear");
4982 let by_src = |src: &str| {
4983 rec.candidates
4984 .iter()
4985 .find(|c| c.impl_id.kernel_source == src)
4986 .unwrap_or_else(|| panic!("candidate {src} present"))
4987 };
4988 assert_eq!(
4989 by_src("portable-cpu").latency_ns,
4990 Some(41_230),
4991 "the measured winner carries its own ns",
4992 );
4993 assert_eq!(
4994 by_src("aocl").latency_ns,
4995 None,
4996 "the unmeasured sibling is None, never a fabricated 0",
4997 );
4998 }
4999
5000 #[test]
5004 fn coarse_dispatch_record_has_no_candidates() {
5005 let table = two_sibling_add_table();
5006 let (g, add_id) = build_add_graph();
5007 let order = topo_order(&g, add_id);
5008
5009 let sink = Mutex::new(TelemetrySink::new());
5010 let provider = StubProvider;
5011 let config = TelemetryConfig {
5012 mode: TelemetryMode::Coarse,
5013 out_path: None,
5014 };
5015 let hooks = TelemetryHooks {
5016 config: &config,
5017 sink: &sink,
5018 provider: &provider,
5019 hw: cpu_hw(),
5020 };
5021 let opts = PlanOptions::new()
5022 .without_cost_population()
5023 .with_telemetry(&hooks);
5024 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
5025
5026 let sink = sink.into_inner().expect("sink lock");
5027 assert_eq!(
5028 sink.dispatch_cell_count(),
5029 1,
5030 "Coarse still emits the chosen signal"
5031 );
5032 let recs = sink.dispatch_records();
5033 assert!(
5034 recs[0].candidates.is_empty(),
5035 "Coarse omits candidates (no Judge reads)"
5036 );
5037 assert_eq!(recs[0].chosen.kernel_source, "portable-cpu");
5038 assert_eq!(recs[0].count, 1);
5039 }
5040
5041 #[test]
5044 fn telemetry_off_emits_no_dispatch_record() {
5045 let table = two_sibling_add_table();
5046 let (g, add_id) = build_add_graph();
5047 let order = topo_order(&g, add_id);
5048
5049 let sink = Mutex::new(TelemetrySink::new());
5050 let provider = StubProvider;
5051 let config = TelemetryConfig::default(); let hooks = TelemetryHooks {
5053 config: &config,
5054 sink: &sink,
5055 provider: &provider,
5056 hw: cpu_hw(),
5057 };
5058 let opts = PlanOptions::new()
5059 .without_cost_population()
5060 .with_telemetry(&hooks);
5061 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
5062
5063 assert!(
5064 sink.into_inner().expect("sink lock").is_empty(),
5065 "Off emits neither dispatch nor miss",
5066 );
5067 let _ = add_id;
5068 }
5069
5070 struct RecordingProvider {
5079 seen: Mutex<Vec<FdxOperandDesc>>,
5080 }
5081 impl StructureKeyProvider for RecordingProvider {
5082 fn structure_key(
5083 &self,
5084 op_class: &str,
5085 operands: &[FdxOperandDesc],
5086 _arch: &str,
5087 ) -> Option<StructureKeyToken> {
5088 *self.seen.lock().expect("record lock") = operands.to_vec();
5089 Some(StructureKeyToken(format!(
5090 "{op_class}:n={}",
5091 operands.len()
5092 )))
5093 }
5094 }
5095
5096 #[test]
5106 fn structure_key_operand_slice_folds_in_the_output() {
5107 let table = generic_only_add_table();
5108 let (g, add_id) = build_add_graph();
5109 let order = topo_order(&g, add_id);
5110
5111 let sink = Mutex::new(TelemetrySink::new());
5112 let provider = RecordingProvider {
5113 seen: Mutex::new(Vec::new()),
5114 };
5115 let config = TelemetryConfig {
5116 mode: TelemetryMode::Coarse,
5117 out_path: None,
5118 };
5119 let hooks = TelemetryHooks {
5120 config: &config,
5121 sink: &sink,
5122 provider: &provider,
5123 hw: cpu_hw(),
5124 };
5125 let opts = PlanOptions::new()
5126 .without_cost_population()
5127 .with_telemetry(&hooks);
5128 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
5129
5130 let seen = provider.seen.into_inner().expect("record lock");
5131 assert_eq!(
5133 seen.len(),
5134 3,
5135 "operand slice must be node inputs (2) then the output (1)",
5136 );
5137 let out = seen.last().expect("output operand present");
5138 assert_eq!(
5140 out.dtype,
5141 DType::F32,
5142 "output operand carries the node dtype"
5143 );
5144 assert_eq!(
5145 out.shape,
5146 vec![3i64],
5147 "output operand carries the node shape"
5148 );
5149 assert_eq!(
5150 out.contiguity,
5151 Contiguity::Contiguous,
5152 "the Add output is contiguous",
5153 );
5154 let _ = add_id;
5155 }
5156 }
5157}