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 match backend {
105 BackendId::Cpu => DeviceLocation::Cpu,
106 BackendId::Cuda => DeviceLocation::Cuda { gpu_id: 0 },
107 BackendId::Vulkan => DeviceLocation::Vulkan { gpu_id: 0 },
108 BackendId::Metal => DeviceLocation::Metal { gpu_id: 0 },
109 _ => DeviceLocation::Cpu,
110 }
111}
112
113pub(crate) fn decision_device_for(
123 graph: &Graph,
124 options: &PlanOptions<'_>,
125 id: NodeId,
126) -> Option<DeviceLocation> {
127 graph
128 .placement(id)
129 .or(options.pinned_device)
130 .or_else(|| graph.target_backend(id).map(default_device_for))
131}
132
133pub(crate) fn candidate_backends_for(
153 graph: &Graph,
154 options: &PlanOptions<'_>,
155 id: NodeId,
156 node: &fuel_graph::Node,
157) -> Vec<BackendId> {
158 let Some(target_device) = decision_device_for(graph, options, id) else {
159 return Vec::new();
160 };
161 let mut backends: Vec<BackendId> = match options.placements_for_device {
162 Some(f) => f(target_device),
163 None => vec![
164 graph
165 .target_backend(id)
166 .unwrap_or_else(|| backend_for_device(target_device)),
167 ],
168 };
169 if node.op.destructive_input().is_none()
174 && let Some(fallback) = options.fallback_placements_for
175 {
176 backends.extend(fallback(target_device).into_iter().map(|(b, _)| b));
177 }
178 let mut unique: Vec<BackendId> = Vec::with_capacity(backends.len());
180 for b in backends {
181 if !unique.contains(&b) {
182 unique.push(b);
183 }
184 }
185 unique
186}
187
188pub fn backend_for_device(loc: DeviceLocation) -> BackendId {
193 match loc {
194 DeviceLocation::Cpu => BackendId::Cpu,
195 DeviceLocation::Cuda { .. } => BackendId::Cuda,
196 DeviceLocation::Vulkan { .. } => BackendId::Vulkan,
197 DeviceLocation::Metal { .. } => BackendId::Metal,
198 }
199}
200
201pub struct PlanOptions<'env> {
292 pub precision_requirement: PrecisionRequirement,
295 pub populate_costs: bool,
299 pub placements_for_device: Option<&'env (dyn Fn(DeviceLocation) -> Vec<BackendId> + 'env)>,
302 pub pinned_device: Option<DeviceLocation>,
305 pub fallback_placements_for:
308 Option<&'env (dyn Fn(DeviceLocation) -> Vec<(BackendId, DeviceLocation)> + 'env)>,
309 pub capabilities_for: Option<&'env CapabilitiesLookup<'env>>,
312 pub judge: Option<&'env dyn JudgeOracle>,
318 pub transfer_estimator: Option<&'env dyn TransferEstimator>,
339 pub require_transfer_pricing: bool,
356 pub input_residency: Option<&'env (dyn Fn(NodeId) -> Option<DeviceLocation> + 'env)>,
368 pub reuse_plan: Option<&'env ExecutionPlan>,
385 pub allow_cost_placement: bool,
404 pub device_budget_bytes: Option<usize>,
412 pub device_budget_source: Option<crate::device_budget::BudgetSource>,
416 #[cfg(feature = "telemetry")]
424 pub telemetry: Option<&'env crate::telemetry::TelemetryHooks<'env>>,
425}
426
427impl Default for PlanOptions<'_> {
428 fn default() -> Self {
429 Self {
430 precision_requirement: PrecisionRequirement::default(),
431 populate_costs: true,
432 placements_for_device: None,
433 pinned_device: None,
434 fallback_placements_for: None,
435 capabilities_for: None,
436 judge: None,
437 transfer_estimator: None,
438 require_transfer_pricing: false,
439 input_residency: None,
440 reuse_plan: None,
441 allow_cost_placement: true,
442 device_budget_bytes: None,
443 device_budget_source: None,
444 #[cfg(feature = "telemetry")]
445 telemetry: None,
446 }
447 }
448}
449
450impl<'env> PlanOptions<'env> {
451 pub fn new() -> Self {
453 Self::default()
454 }
455
456 pub fn with_device_budget_bytes(mut self, budget_bytes: usize) -> Self {
458 self.device_budget_bytes = Some(budget_bytes);
459 self
460 }
461
462 pub fn with_resolved_device_budget(
465 mut self,
466 budget: crate::device_budget::ResolvedBudget,
467 ) -> Self {
468 self.device_budget_bytes = Some(budget.bytes);
469 self.device_budget_source = Some(budget.source);
470 self
471 }
472
473 pub fn with_precision_requirement(mut self, req: PrecisionRequirement) -> Self {
475 self.precision_requirement = req;
476 self
477 }
478
479 pub fn without_cost_population(mut self) -> Self {
483 self.populate_costs = false;
484 self
485 }
486
487 pub fn with_placements_for_device(
490 mut self,
491 f: &'env (dyn Fn(DeviceLocation) -> Vec<BackendId> + 'env),
492 ) -> Self {
493 self.placements_for_device = Some(f);
494 self
495 }
496
497 pub fn with_pinned_device(mut self, device: DeviceLocation) -> Self {
502 self.pinned_device = Some(device);
503 self
504 }
505
506 pub fn without_cost_placement(mut self) -> Self {
511 self.allow_cost_placement = false;
512 self
513 }
514
515 pub fn require_transfer_pricing(mut self) -> Self {
523 self.require_transfer_pricing = true;
524 self
525 }
526
527 pub fn with_fallback_placements_for(
536 mut self,
537 f: &'env (dyn Fn(DeviceLocation) -> Vec<(BackendId, DeviceLocation)> + 'env),
538 ) -> Self {
539 self.fallback_placements_for = Some(f);
540 self
541 }
542
543 pub fn with_capabilities_for(mut self, f: &'env CapabilitiesLookup<'env>) -> Self {
546 self.capabilities_for = Some(f);
547 self
548 }
549
550 pub fn with_judge(mut self, judge: &'env dyn JudgeOracle) -> Self {
554 self.judge = Some(judge);
555 self
556 }
557
558 pub fn with_transfer_estimator(mut self, est: &'env dyn TransferEstimator) -> Self {
564 self.transfer_estimator = Some(est);
565 self
566 }
567
568 pub fn with_input_residency(
572 mut self,
573 f: &'env (dyn Fn(NodeId) -> Option<DeviceLocation> + 'env),
574 ) -> Self {
575 self.input_residency = Some(f);
576 self
577 }
578
579 pub fn with_reuse_plan(mut self, base: &'env ExecutionPlan) -> Self {
582 self.reuse_plan = Some(base);
583 self
584 }
585
586 #[cfg(feature = "telemetry")]
592 pub fn with_telemetry(mut self, hooks: &'env crate::telemetry::TelemetryHooks<'env>) -> Self {
593 self.telemetry = Some(hooks);
594 self
595 }
596}
597
598pub fn compile_plan(
681 graph: &Graph,
682 order: &[NodeId],
683 bindings_table: &KernelBindingTable,
684 options: &PlanOptions<'_>,
685) -> Result<ExecutionPlan> {
686 if options.require_transfer_pricing && options.transfer_estimator.is_none() {
694 return Err(Error::Msg(
695 "compile_plan: require_transfer_pricing is set but no transfer \
696 estimator is wired — placement would silently price transfers at \
697 zero (latency-greedy). Wire PlanOptions::with_transfer_estimator(..) \
698 or drop the pricing requirement."
699 .into(),
700 )
701 .bt());
702 }
703
704 let generation = crate::dispatch::topology_generation();
710 let mut alternatives_map = HashMap::with_capacity(order.len());
711
712 let mut residency: HashMap<NodeId, DeviceLocation> = HashMap::with_capacity(order.len());
716
717 let mut dp = PlacementDp::new();
720 let mut dp_drafts: HashMap<NodeId, NodeDraft> = HashMap::new();
721
722 for &id in order {
723 let node = graph.node(id);
724
725 if let Some(base) = options.reuse_plan
731 && let Some(set) = base.alternatives(id)
732 {
733 let resident = early_residency(graph, options, id, node)
734 .or_else(|| set.winner().map(|w| w.device));
735 if let Some(loc) = resident {
736 residency.insert(id, loc);
737 }
738 alternatives_map.insert(id, set.clone());
739 continue;
740 }
741
742 let early = early_residency(graph, options, id, node);
745
746 let mut dp_row_opened = false;
747 let winner_device = match build_node_draft(graph, id, node, bindings_table, options)? {
748 Some(draft) => {
749 let devices = distinct_devices(&draft.set);
750 let dp_estimator = options
751 .transfer_estimator
752 .filter(|_| draft.relaxed && early.is_none() && devices.len() >= 2);
753 if let Some(est) = dp_estimator {
754 open_dp_row(
758 &mut dp,
759 graph,
760 id,
761 node,
762 &draft.set,
763 &devices,
764 &residency,
765 est,
766 options.capabilities_for,
767 );
768 dp_drafts.insert(id, draft);
769 dp_row_opened = true;
770 None
771 } else {
772 if let Some(est) = options.transfer_estimator
779 && let [single] = devices.as_slice()
780 {
781 close_open_inputs(&mut dp, graph, node, *single, est, &mut residency);
782 }
783 let set = finalize_node_greedy(
784 graph,
785 node,
786 draft,
787 bindings_table,
788 options,
789 &residency,
790 )?;
791 let dev = set.winner().map(|w| w.device);
792 if devices.len() > 1
796 && let (Some(est), Some(wd)) = (options.transfer_estimator, dev)
797 {
798 close_open_inputs(&mut dp, graph, node, wd, est, &mut residency);
799 }
800 alternatives_map.insert(id, set);
801 dev
802 }
803 }
804 None => {
805 if let fuel_graph::Op::Copy { target } | fuel_graph::Op::Move { target } = node.op
811 && let Some(est) = options.transfer_estimator
812 {
813 close_open_inputs(&mut dp, graph, node, target, est, &mut residency);
814 }
815 None
816 }
817 };
818
819 if dp_row_opened {
820 continue;
824 }
825
826 let resident = early
828 .or(winner_device)
829 .or_else(|| {
830 graph.target_backend(id).map(|b| {
835 options
836 .pinned_device
837 .unwrap_or_else(|| default_device_for(b))
838 })
839 })
840 .or_else(|| {
841 if is_passthrough(node) {
846 node.inputs.first().and_then(|i| residency.get(i)).copied()
847 } else {
848 None
849 }
850 });
851 if let Some(loc) = resident {
852 residency.insert(id, loc);
853 } else if is_passthrough(node) {
854 if let Some(&input) = node.inputs.first() {
860 let root = dp.resolve(input);
861 if let Some(dev) = dp.committed_device(root) {
862 residency.insert(id, dev);
863 } else {
864 dp.add_alias(id, root);
865 }
866 }
867 }
868 }
869
870 if !dp_drafts.is_empty() {
873 let Some(est) = options.transfer_estimator else {
874 return Err(Error::Msg(
877 "compile_plan: placement DP rows exist without a transfer \
878 estimator — internal invariant violated"
879 .into(),
880 )
881 .bt());
882 };
883 let commits = dp.finish(options.pinned_device, |nid| node_bytes(graph, nid), est);
884 for (n, d) in commits {
885 residency.insert(n, d);
886 }
887 for &id in order {
891 if residency.contains_key(&id) {
892 continue;
893 }
894 let node = graph.node(id);
895 if is_passthrough(node)
896 && let Some(&loc) = node.inputs.first().and_then(|i| residency.get(i))
897 {
898 residency.insert(id, loc);
899 }
900 }
901 for &id in order {
906 let Some(draft) = dp_drafts.remove(&id) else {
907 continue;
908 };
909 let chosen = dp.committed_device(id).ok_or_else(|| {
910 Error::Msg(format!(
911 "compile_plan: placement DP left node {:?} uncommitted — \
912 internal invariant violated",
913 id,
914 ))
915 .bt()
916 })?;
917 let node = graph.node(id);
918 let mut set = draft.set;
919 let inputs = priced_inputs_for(graph, node, &residency);
920 apply_inbound_transfer_costs(&mut set, &inputs, est);
921 set.rank_by_composite_cost();
922 let keep: Vec<usize> = set
923 .alternatives()
924 .iter()
925 .enumerate()
926 .filter_map(|(i, c)| (c.device == chosen).then_some(i))
927 .collect();
928 if keep.len() < set.len() {
929 set.retain_indices(&keep);
930 }
931 set.retain_per_device_frontier(KEEP_PER_DEVICE);
937 if set.is_empty() {
938 return Err(missing_binding_error(
941 bindings_table,
942 draft.op_kind,
943 &draft.dtypes,
944 draft.diag_backend,
945 ));
946 }
947 alternatives_map.insert(id, set);
948 }
949 }
950
951 #[cfg(feature = "telemetry")]
956 emit_plan_telemetry(graph, &alternatives_map, bindings_table, options);
957
958 Ok(ExecutionPlan {
959 order: order.to_vec(),
960 alternatives: alternatives_map,
961 generation,
962 })
963}
964
965#[cfg(feature = "telemetry")]
990fn emit_plan_telemetry(
991 graph: &Graph,
992 alternatives: &HashMap<NodeId, AlternativeSet>,
993 bindings_table: &KernelBindingTable,
994 options: &PlanOptions<'_>,
995) {
996 use crate::telemetry::{
997 DispatchRecord, FdxOperandDesc, ImplId, TELEMETRY_SCHEMA_VERSION, detect_miss_precomputed,
998 };
999
1000 let Some(hooks) = options.telemetry else {
1002 return;
1003 };
1004 if !hooks.config.is_enabled() {
1005 return;
1006 }
1007 let arch = hooks.arch_tag();
1008 let want_candidates = hooks.config.mode.wants_candidates();
1009
1010 for (&id, set) in alternatives {
1011 let Some(winner) = set.winner() else {
1012 continue;
1013 };
1014 let node = graph.node(id);
1015 let Some(op_kind) = op_to_op_kind(&node.op) else {
1016 continue;
1017 };
1018 let dtypes = build_lookup_dtypes(graph, node);
1019
1020 let winner_ptr = winner.kernel as *const () as usize;
1025 let winner_entry = bindings_table
1026 .lookup_alternatives(op_kind, &dtypes, winner.backend)
1027 .iter()
1028 .find(|e| e.kernel as *const () as usize == winner_ptr)
1029 .copied();
1030 let is_generic = winner_entry.is_some_and(|e| e.is_generic);
1031 let winner_revision = winner_entry.map_or(0, |e| e.kernel_revision_hash);
1032
1033 let mut operands: Vec<FdxOperandDesc> = node
1039 .inputs
1040 .iter()
1041 .map(|&input_id| {
1042 FdxOperandDesc::from_layout(&graph.layout(input_id), graph.node(input_id).dtype)
1043 })
1044 .collect();
1045 operands.push(FdxOperandDesc::from_layout(&graph.layout(id), node.dtype));
1046 let op_class = format!("{op_kind:?}");
1047
1048 let structure_key = hooks.provider.structure_key(&op_class, &operands, &arch);
1052
1053 let chosen = ImplId {
1055 backend: winner.backend,
1056 op: op_kind,
1057 dtypes: dtypes.to_vec(),
1058 kernel_source: winner.kernel_source.to_string(),
1059 kernel_revision_hash: winner_revision,
1060 };
1061
1062 let candidates = if want_candidates {
1065 build_candidates(set, op_kind, &dtypes, bindings_table, options.judge)
1066 } else {
1067 Vec::new()
1068 };
1069
1070 let dispatch = DispatchRecord {
1072 schema: TELEMETRY_SCHEMA_VERSION,
1073 structure_key,
1074 chosen: chosen.clone(),
1075 candidates,
1076 count: 1,
1077 hw: hooks.hw.clone(),
1078 };
1079 if let Ok(mut sink) = hooks.sink.lock() {
1080 sink.record_dispatch(dispatch);
1081 }
1082
1083 if let Some(miss) = detect_miss_precomputed(
1087 is_generic,
1088 chosen,
1089 &op_class,
1090 &operands,
1091 &arch,
1092 hooks.provider,
1093 hooks.hw.clone(),
1094 ) {
1095 if let Ok(mut sink) = hooks.sink.lock() {
1098 sink.record_miss(miss);
1099 }
1100 }
1101 }
1102}
1103
1104#[cfg(feature = "telemetry")]
1113fn build_candidates(
1114 set: &AlternativeSet,
1115 op_kind: OpKind,
1116 dtypes: &[DType],
1117 bindings_table: &KernelBindingTable,
1118 judge: Option<&dyn JudgeOracle>,
1119) -> Vec<crate::telemetry::Candidate> {
1120 use crate::telemetry::{Candidate as TeleCandidate, ImplId};
1121
1122 let ctx = set.context();
1125 set.alternatives()
1126 .iter()
1127 .map(|cand| {
1128 let ptr = cand.kernel as *const () as usize;
1129 let revision = bindings_table
1130 .lookup_alternatives(op_kind, dtypes, cand.backend)
1131 .iter()
1132 .find(|e| e.kernel as *const () as usize == ptr)
1133 .map_or(0, |e| e.kernel_revision_hash);
1134 let impl_id = ImplId {
1135 backend: cand.backend,
1136 op: op_kind,
1137 dtypes: dtypes.to_vec(),
1138 kernel_source: cand.kernel_source.to_string(),
1139 kernel_revision_hash: revision,
1140 };
1141 let latency_ns = match (judge, ctx) {
1142 (Some(j), Some(ctx)) => j.measured_latency_ns(
1143 ctx.op,
1144 ctx.principal_dtype,
1145 ctx.size_class,
1146 cand.backend,
1147 cand.kernel_source,
1148 revision,
1154 ),
1155 _ => None,
1156 };
1157 TeleCandidate {
1158 impl_id,
1159 latency_ns,
1160 }
1161 })
1162 .collect()
1163}
1164
1165pub fn node_needs_plan_entry(op: &fuel_graph::Op) -> bool {
1173 op_to_op_kind(op).is_some()
1174 && !matches!(
1175 op,
1176 fuel_graph::Op::Copy { .. } | fuel_graph::Op::Move { .. }
1177 )
1178}
1179
1180fn is_passthrough(node: &fuel_graph::Node) -> bool {
1184 node.op.is_view_op()
1185 || matches!(
1186 node.op,
1187 fuel_graph::Op::Reshape(_) | fuel_graph::Op::Contiguize
1188 )
1189}
1190
1191fn distinct_devices(set: &AlternativeSet) -> SmallVec<[DeviceLocation; 4]> {
1195 let mut out: SmallVec<[DeviceLocation; 4]> = SmallVec::new();
1196 for c in set.alternatives() {
1197 if !out.contains(&c.device) {
1198 out.push(c.device);
1199 }
1200 }
1201 out
1202}
1203
1204fn node_bytes(graph: &Graph, id: NodeId) -> u64 {
1208 let n = graph.node(id);
1209 (n.shape.elem_count() as u64).saturating_mul(n.dtype.size_in_bytes() as u64)
1210}
1211
1212fn open_dp_row(
1217 dp: &mut PlacementDp,
1218 graph: &Graph,
1219 id: NodeId,
1220 node: &fuel_graph::Node,
1221 set: &AlternativeSet,
1222 devices: &[DeviceLocation],
1223 residency: &HashMap<NodeId, DeviceLocation>,
1224 est: &dyn TransferEstimator,
1225 caps_for: Option<&CapabilitiesLookup<'_>>,
1226) {
1227 let rates_for = |backend: BackendId| -> (f64, f64) {
1236 caps_for
1237 .and_then(|f| f(backend))
1238 .map(|caps| {
1239 (
1240 caps.compute_throughput_flops_per_ns,
1241 caps.mem_bandwidth_bytes_per_ns,
1242 )
1243 })
1244 .unwrap_or_else(|| default_backend_rates(backend))
1245 };
1246 let device_costs: Vec<(DeviceLocation, u64)> = devices
1247 .iter()
1248 .map(|&d| {
1249 let min = set
1250 .alternatives()
1251 .iter()
1252 .filter(|c| c.device == d)
1253 .map(|c| {
1254 let (cr, bw) = rates_for(c.backend);
1255 composite_ns(&c.static_cost, cr, bw)
1256 })
1257 .min()
1258 .unwrap_or(u64::MAX);
1259 (d, min)
1260 })
1261 .collect();
1262
1263 let mut fixed: Vec<(DeviceLocation, u64)> = Vec::new();
1264 let mut chains: Vec<ChainInput> = Vec::new();
1265 for &input in &node.inputs {
1266 let bytes = node_bytes(graph, input);
1267 if let Some(&src) = residency.get(&input) {
1268 fixed.push((src, bytes));
1269 continue;
1270 }
1271 let root = dp.resolve(input);
1272 if dp.is_open(root) {
1273 match chains.iter_mut().find(|ci| ci.producer == root) {
1274 Some(ci) => ci.edge_bytes.push(bytes),
1275 None => chains.push(ChainInput {
1276 producer: root,
1277 edge_bytes: smallvec::smallvec![bytes],
1278 }),
1279 }
1280 } else if let Some(dev) = dp.committed_device(root) {
1281 fixed.push((dev, bytes));
1284 }
1285 }
1288 dp.push_row(id, &device_costs, &fixed, &chains, est);
1289}
1290
1291fn close_open_inputs(
1297 dp: &mut PlacementDp,
1298 graph: &Graph,
1299 node: &fuel_graph::Node,
1300 toward: DeviceLocation,
1301 est: &dyn TransferEstimator,
1302 residency: &mut HashMap<NodeId, DeviceLocation>,
1303) {
1304 for &input in &node.inputs {
1305 if residency.contains_key(&input) {
1306 continue;
1307 }
1308 let root = dp.resolve(input);
1309 if dp.is_open(root) {
1310 let commits = dp.close_toward(root, toward, &[node_bytes(graph, input)], est);
1311 for (n, d) in commits {
1312 residency.insert(n, d);
1313 }
1314 }
1315 if !residency.contains_key(&input)
1316 && let Some(d) = dp.committed_device(root)
1317 {
1318 residency.insert(input, d);
1319 }
1320 }
1321}
1322
1323fn early_residency(
1332 graph: &Graph,
1333 options: &PlanOptions<'_>,
1334 id: NodeId,
1335 node: &fuel_graph::Node,
1336) -> Option<DeviceLocation> {
1337 match node.op {
1338 fuel_graph::Op::Copy { target }
1339 | fuel_graph::Op::Move { target }
1340 | fuel_graph::Op::Alloc { target } => return Some(target),
1341 _ => {}
1342 }
1343 if let Some(loc) = graph.placement(id) {
1344 return Some(loc);
1345 }
1346 options.input_residency.and_then(|f| f(id))
1347}
1348
1349fn priced_inputs_for(
1355 graph: &Graph,
1356 node: &fuel_graph::Node,
1357 residency: &HashMap<NodeId, DeviceLocation>,
1358) -> Vec<(DeviceLocation, u64)> {
1359 node.inputs
1360 .iter()
1361 .filter_map(|&input_id| {
1362 let src = residency.get(&input_id).copied()?;
1363 let in_node = graph.node(input_id);
1364 let bytes = (in_node.shape.elem_count() as u64)
1365 .saturating_mul(in_node.dtype.size_in_bytes() as u64);
1366 Some((src, bytes))
1367 })
1368 .collect()
1369}
1370
1371struct NodeDraft {
1377 set: AlternativeSet,
1378 relaxed: bool,
1381 from_fallback: bool,
1384 costed: bool,
1388 op_kind: OpKind,
1389 dtypes: Vec<DType>,
1390 diag_backend: BackendId,
1391}
1392
1393fn build_node_draft(
1400 graph: &Graph,
1401 id: NodeId,
1402 node: &fuel_graph::Node,
1403 bindings_table: &KernelBindingTable,
1404 options: &PlanOptions<'_>,
1405) -> Result<Option<NodeDraft>> {
1406 if !node_needs_plan_entry(&node.op) {
1422 return Ok(None);
1423 }
1424 let Some(op_kind) = op_to_op_kind(&node.op) else {
1425 return Ok(None);
1427 };
1428
1429 let explicit_backend = graph.target_backend(id);
1433 let target_device = decision_device_for(graph, options, id).ok_or_else(|| {
1434 Error::Msg(format!(
1435 "compile_plan: node {:?} ({:?}) has no device context — \
1436 set PlanOptions::pinned_device, a graph placement, or \
1437 the node's target_backend",
1438 id, node.op,
1439 ))
1440 .bt()
1441 })?;
1442 let diag_backend = explicit_backend.unwrap_or_else(|| backend_for_device(target_device));
1446 let dtypes = build_lookup_dtypes(graph, node);
1447
1448 let placements: Vec<(BackendId, DeviceLocation)> = match options.placements_for_device {
1452 Some(f) => f(target_device)
1453 .into_iter()
1454 .map(|backend| (backend, target_device))
1455 .collect(),
1456 None => vec![(diag_backend, target_device)],
1457 };
1458
1459 let op_params = candidate_default_op_params(graph, node);
1460
1461 let pricing_active = options.transfer_estimator.is_some()
1479 && options.populate_costs
1480 && options.capabilities_for.is_some();
1481 let fallback_allowed =
1482 node.op.destructive_input().is_none() && options.fallback_placements_for.is_some();
1483 let relaxed = options.allow_cost_placement
1484 && pricing_active
1485 && fallback_allowed
1486 && graph.placement(id).is_none();
1487
1488 let mut set;
1489 let mut from_fallback = false;
1490 if relaxed {
1491 let mut merged = placements.clone();
1496 if let Some(fallback) = options.fallback_placements_for {
1497 merged.extend(fallback(target_device));
1498 }
1499 set = enumerate_candidates(op_kind, &dtypes, &merged, &op_params, bindings_table);
1500 } else {
1501 set = enumerate_candidates(op_kind, &dtypes, &placements, &op_params, bindings_table);
1502
1503 if set.is_empty()
1511 && fallback_allowed
1512 && let Some(fallback) = options.fallback_placements_for
1513 {
1514 let fb_placements = fallback(target_device);
1515 if !fb_placements.is_empty() {
1516 set = enumerate_candidates(
1517 op_kind,
1518 &dtypes,
1519 &fb_placements,
1520 &op_params,
1521 bindings_table,
1522 );
1523 from_fallback = !set.is_empty();
1524 }
1525 }
1526 }
1527
1528 if set.is_empty() {
1533 return Err(missing_binding_error(
1534 bindings_table,
1535 op_kind,
1536 &dtypes,
1537 diag_backend,
1538 ));
1539 }
1540
1541 let input_layouts: Vec<fuel_ir::Layout> = node
1543 .inputs
1544 .iter()
1545 .map(|&input_id| graph.layout(input_id))
1546 .collect();
1547 let ctx = FilterContext::new(op_kind, &dtypes, &input_layouts);
1548 let chain = default_chain(options.precision_requirement);
1549 if let Err(err) = apply_filter_chain(&mut set, &chain, &ctx) {
1550 if relaxed || from_fallback || !fallback_allowed {
1559 return Err(err);
1560 }
1561 let Some(fallback) = options.fallback_placements_for else {
1562 return Err(err);
1563 };
1564 let fb_placements = fallback(target_device);
1565 if fb_placements.is_empty() {
1566 return Err(err);
1567 }
1568 let mut fb_set =
1569 enumerate_candidates(op_kind, &dtypes, &fb_placements, &op_params, bindings_table);
1570 if fb_set.is_empty() {
1571 return Err(err);
1572 }
1573 apply_filter_chain(&mut fb_set, &chain, &ctx)?;
1576 set = fb_set;
1577 from_fallback = true;
1578 }
1579
1580 if let Some(&principal_dtype) = dtypes.first() {
1591 let input_shapes: Vec<Shape> = node
1592 .inputs
1593 .iter()
1594 .map(|&input_id| graph.node(input_id).shape.clone())
1595 .collect();
1596 let size_class = SizeClass::for_op(op_kind, &input_shapes);
1597 set.set_context(DecisionContext {
1598 op: op_kind,
1599 principal_dtype,
1600 size_class,
1601 });
1602 }
1603
1604 let costed = if options.populate_costs {
1608 if let Some(caps_for) = options.capabilities_for {
1609 let input_shapes: Vec<Shape> = node
1610 .inputs
1611 .iter()
1612 .map(|&input_id| graph.node(input_id).shape.clone())
1613 .collect();
1614 compute_static_costs(
1615 &mut set,
1616 op_kind,
1617 &dtypes,
1618 &input_shapes,
1619 bindings_table,
1620 caps_for,
1621 options.judge,
1622 );
1623 true
1624 } else {
1625 false
1626 }
1627 } else {
1628 false
1629 };
1630
1631 Ok(Some(NodeDraft {
1632 set,
1633 relaxed,
1634 from_fallback,
1635 costed,
1636 op_kind,
1637 dtypes,
1638 diag_backend,
1639 }))
1640}
1641
1642fn finalize_node_greedy(
1649 graph: &Graph,
1650 node: &fuel_graph::Node,
1651 draft: NodeDraft,
1652 bindings_table: &KernelBindingTable,
1653 options: &PlanOptions<'_>,
1654 residency: &HashMap<NodeId, DeviceLocation>,
1655) -> Result<AlternativeSet> {
1656 let NodeDraft {
1657 mut set,
1658 relaxed,
1659 from_fallback,
1660 costed,
1661 op_kind,
1662 dtypes,
1663 diag_backend,
1664 } = draft;
1665
1666 if costed {
1667 if let Some(estimator) = options.transfer_estimator {
1673 let inputs = priced_inputs_for(graph, node, residency);
1674 apply_inbound_transfer_costs(&mut set, &inputs, estimator);
1675 }
1676 set.rank_by_composite_cost();
1677 }
1678
1679 if relaxed && let Some(winner_device) = set.winner().map(|c| c.device) {
1690 let keep: Vec<usize> = set
1691 .alternatives()
1692 .iter()
1693 .enumerate()
1694 .filter_map(|(i, c)| (c.device == winner_device).then_some(i))
1695 .collect();
1696 if keep.len() < set.len() {
1697 set.retain_indices(&keep);
1698 }
1699 }
1700
1701 set.retain_per_device_frontier(KEEP_PER_DEVICE);
1709
1710 if from_fallback && set.len() > 1 {
1717 set.retain_indices(&[0]);
1718 }
1719
1720 if set.is_empty() {
1727 return Err(missing_binding_error(
1728 bindings_table,
1729 op_kind,
1730 &dtypes,
1731 diag_backend,
1732 ));
1733 }
1734
1735 Ok(set)
1736}
1737
1738fn missing_binding_error(
1744 table: &KernelBindingTable,
1745 op: OpKind,
1746 dtypes: &[DType],
1747 backend: BackendId,
1748) -> Error {
1749 let _ = backend;
1754 let (available_backends, supported_combinations) = table.coverage_diagnostic();
1755 Error::NoBackendForOp {
1756 op,
1757 dtypes: dtypes.to_vec(),
1758 available_backends,
1759 supported_combinations,
1760 }
1761 .bt()
1762}
1763
1764fn candidate_default_op_params(
1772 _graph: &Graph,
1773 _node: &fuel_graph::Node,
1774) -> crate::kernel::OpParams {
1775 crate::kernel::OpParams::None
1776}
1777
1778#[cfg(test)]
1779mod tests {
1780 use super::*;
1781 use crate::fused::PrecisionGuarantee;
1782 use crate::kernel::{KernelCaps, OpParams, unknown_cost};
1783 use fuel_graph::{Node, Op, topo_order};
1784 use fuel_ir::backend::{BackendCapabilities, SubstrateClass, TransferPath};
1785 use fuel_ir::{DType, Layout, Result as FuelResult, Shape, StrideVec};
1786 use fuel_memory::Storage;
1787 use smallvec::smallvec;
1788 use std::collections::HashSet;
1789 use std::sync::{Arc, RwLock};
1790
1791 fn noop_kernel(
1792 _i: &[Arc<RwLock<Storage>>],
1793 _o: &mut [Arc<RwLock<Storage>>],
1794 _l: &[Layout],
1795 _p: &OpParams,
1796 ) -> FuelResult<()> {
1797 Ok(())
1798 }
1799
1800 fn noop_kernel_b(
1801 _i: &[Arc<RwLock<Storage>>],
1802 _o: &mut [Arc<RwLock<Storage>>],
1803 _l: &[Layout],
1804 _p: &OpParams,
1805 ) -> FuelResult<()> {
1806 Ok(())
1807 }
1808
1809 fn noop_kernel_c(
1810 _i: &[Arc<RwLock<Storage>>],
1811 _o: &mut [Arc<RwLock<Storage>>],
1812 _l: &[Layout],
1813 _p: &OpParams,
1814 ) -> FuelResult<()> {
1815 Ok(())
1816 }
1817
1818 fn register_add_f32(
1819 table: &mut KernelBindingTable,
1820 backend: BackendId,
1821 kernel: crate::kernel::KernelRef,
1822 precision: PrecisionGuarantee,
1823 ) {
1824 table.register_full(
1825 OpKind::AddElementwise,
1826 &[DType::F32, DType::F32, DType::F32],
1827 backend,
1828 kernel,
1829 KernelCaps::empty(),
1830 precision,
1831 unknown_cost,
1832 );
1833 }
1834
1835 fn build_add_graph() -> (Graph, NodeId) {
1836 let mut g = Graph::new();
1837 let lhs = g.push(Node {
1838 op: Op::Const,
1839 inputs: vec![],
1840 shape: Shape::from_dims(&[3]),
1841 dtype: DType::F32,
1842 });
1843 let rhs = g.push(Node {
1844 op: Op::Const,
1845 inputs: vec![],
1846 shape: Shape::from_dims(&[3]),
1847 dtype: DType::F32,
1848 });
1849 let add = g.push(Node {
1850 op: Op::Add,
1851 inputs: vec![lhs, rhs],
1852 shape: Shape::from_dims(&[3]),
1853 dtype: DType::F32,
1854 });
1855 g.set_target_backend(add, BackendId::Cpu);
1856 (g, add)
1857 }
1858
1859 fn cpu_caps() -> BackendCapabilities {
1860 BackendCapabilities {
1861 backend_id: BackendId::Cpu,
1862 device_location: DeviceLocation::Cpu,
1863 op_dtype_support: HashSet::new(),
1864 required_alignment: 64,
1865 access_granularity_bits: 8,
1866 transfer_paths: vec![(DeviceLocation::Cpu, TransferPath::SameDevice)],
1867 storage_substrate: SubstrateClass::HostBytes,
1868 compute_throughput_flops_per_ns: 1.0,
1869 mem_bandwidth_bytes_per_ns: 4.0,
1870 }
1871 }
1872
1873 #[test]
1874 fn empty_plan_has_no_alternatives() {
1875 let p = ExecutionPlan::empty();
1876 assert!(p.order.is_empty());
1877 assert!(p.alternatives.is_empty());
1878 assert!(p.alternatives(NodeId(0)).is_none());
1879 }
1880
1881 #[test]
1882 fn default_device_per_backend_matches_router_convention() {
1883 assert_eq!(default_device_for(BackendId::Cpu), DeviceLocation::Cpu);
1884 assert_eq!(
1885 default_device_for(BackendId::Cuda),
1886 DeviceLocation::Cuda { gpu_id: 0 },
1887 );
1888 assert_eq!(
1889 default_device_for(BackendId::Vulkan),
1890 DeviceLocation::Vulkan { gpu_id: 0 },
1891 );
1892 }
1893
1894 #[test]
1895 fn compile_plan_skips_view_and_const_nodes() {
1896 let mut table = KernelBindingTable::new();
1897 register_add_f32(
1898 &mut table,
1899 BackendId::Cpu,
1900 noop_kernel,
1901 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1902 );
1903
1904 let mut g = Graph::new();
1905 let lhs = g.push(Node {
1906 op: Op::Const,
1907 inputs: vec![],
1908 shape: Shape::from_dims(&[6]),
1909 dtype: DType::F32,
1910 });
1911 let rhs = g.push(Node {
1912 op: Op::Const,
1913 inputs: vec![],
1914 shape: Shape::from_dims(&[6]),
1915 dtype: DType::F32,
1916 });
1917 let add = g.push(Node {
1918 op: Op::Add,
1919 inputs: vec![lhs, rhs],
1920 shape: Shape::from_dims(&[6]),
1921 dtype: DType::F32,
1922 });
1923 let reshape = g.push(Node {
1924 op: Op::Reshape(Shape::from_dims(&[2, 3])),
1925 inputs: vec![add],
1926 shape: Shape::from_dims(&[2, 3]),
1927 dtype: DType::F32,
1928 });
1929 g.set_target_backend(add, BackendId::Cpu);
1930 g.set_target_backend(reshape, BackendId::Cpu);
1931
1932 let order = topo_order(&g, reshape);
1933 let opts = PlanOptions::new().without_cost_population();
1934 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
1935
1936 assert_eq!(plan.order.len(), 4);
1937 assert_eq!(
1938 plan.alternatives.len(),
1939 1,
1940 "only Add carries an alternative set",
1941 );
1942 let alts = plan.alternatives(add).expect("Add alternatives present");
1943 assert_eq!(alts.len(), 1);
1944 assert!(plan.alternatives(lhs).is_none());
1945 assert!(plan.alternatives(rhs).is_none());
1946 assert!(plan.alternatives(reshape).is_none());
1947 }
1948
1949 #[test]
1950 fn compile_plan_fails_fast_on_missing_binding() {
1951 let table = KernelBindingTable::new();
1952 let mut g = Graph::new();
1953 let lhs = g.push(Node {
1954 op: Op::Const,
1955 inputs: vec![],
1956 shape: Shape::from_dims(&[2, 3]),
1957 dtype: DType::F32,
1958 });
1959 let rhs = g.push(Node {
1960 op: Op::Const,
1961 inputs: vec![],
1962 shape: Shape::from_dims(&[3, 2]),
1963 dtype: DType::F32,
1964 });
1965 let mm = g.push(Node {
1966 op: Op::MatMul,
1967 inputs: vec![lhs, rhs],
1968 shape: Shape::from_dims(&[2, 2]),
1969 dtype: DType::F32,
1970 });
1971 g.set_target_backend(mm, BackendId::Cpu);
1972
1973 let order = topo_order(&g, mm);
1974 let opts = PlanOptions::new().without_cost_population();
1975 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
1976 match err {
1977 Error::NoBackendForOp { op, dtypes, .. } => {
1978 assert_eq!(op, OpKind::MatMul);
1979 assert_eq!(dtypes, vec![DType::F32, DType::F32, DType::F32]);
1980 }
1981 other => panic!("expected NoBackendForOp, got {other:?}"),
1982 }
1983 }
1984
1985 #[test]
1998 fn plan_time_miss_reports_real_coverage_not_empty() {
1999 let bindings = crate::dispatch::global_bindings(); let mut g = Graph::new();
2001 let lhs = g.push(Node {
2002 op: Op::Const,
2003 inputs: vec![],
2004 shape: Shape::from_dims(&[2, 3]),
2005 dtype: DType::F32,
2006 });
2007 let rhs = g.push(Node {
2010 op: Op::Const,
2011 inputs: vec![],
2012 shape: Shape::from_dims(&[3, 2]),
2013 dtype: DType::F64,
2014 });
2015 let mm = g.push(Node {
2016 op: Op::MatMul,
2017 inputs: vec![lhs, rhs],
2018 shape: Shape::from_dims(&[2, 2]),
2019 dtype: DType::F32,
2020 });
2021 g.set_target_backend(mm, BackendId::Cpu);
2022
2023 let order = topo_order(&g, mm);
2024 let opts = PlanOptions::new().without_cost_population();
2025 let err = compile_plan(&g, &order, &bindings, &opts).unwrap_err();
2026 match err {
2027 Error::NoBackendForOp {
2028 op,
2029 dtypes,
2030 available_backends,
2031 supported_combinations,
2032 } => {
2033 assert_eq!(op, OpKind::MatMul);
2034 assert_eq!(
2035 dtypes,
2036 vec![DType::F32, DType::F64, DType::F32],
2037 "the mixed-precision key (F32 activation, F64 weight)",
2038 );
2039 assert!(
2041 available_backends.contains(&BackendId::Cpu),
2042 "a populated table must report Cpu, never []: {available_backends:?}",
2043 );
2044 assert!(
2045 supported_combinations
2046 .iter()
2047 .any(|(b, o, d)| *b == BackendId::Cpu
2048 && *o == OpKind::MatMul
2049 && *d == vec![DType::F32, DType::F32, DType::F32]),
2050 "must show uniform F32 matmul IS registered (so the mixed gap is visible): \
2051 {supported_combinations:?}",
2052 );
2053 }
2054 other => panic!("expected NoBackendForOp, got {other:?}"),
2055 }
2056 }
2057
2058 #[test]
2059 fn compile_plan_legacy_single_backend_uses_target_backend() {
2060 let mut table = KernelBindingTable::new();
2061 register_add_f32(
2062 &mut table,
2063 BackendId::Cpu,
2064 noop_kernel,
2065 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2066 );
2067 register_add_f32(
2071 &mut table,
2072 BackendId::Cuda,
2073 noop_kernel_b,
2074 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2075 );
2076 let (g, add_id) = build_add_graph();
2077 let order = topo_order(&g, add_id);
2078 let opts = PlanOptions::new().without_cost_population();
2079 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2080 let alts = plan.alternatives(add_id).unwrap();
2081 assert_eq!(alts.len(), 1, "legacy mode → single backend → single alt");
2082 assert_eq!(alts.winner().unwrap().backend, BackendId::Cpu);
2083 }
2084
2085 #[test]
2086 fn compile_plan_cross_co_located_via_placements_callback() {
2087 let mut table = KernelBindingTable::new();
2088 register_add_f32(
2089 &mut table,
2090 BackendId::Cpu,
2091 noop_kernel,
2092 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2093 );
2094 register_add_f32(
2095 &mut table,
2096 BackendId::Cuda,
2097 noop_kernel_b,
2098 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2099 );
2100
2101 let (g, add_id) = build_add_graph();
2102 let order = topo_order(&g, add_id);
2103 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2104 if dev == DeviceLocation::Cpu {
2105 vec![BackendId::Cpu, BackendId::Cuda]
2106 } else {
2107 vec![]
2108 }
2109 };
2110 let opts = PlanOptions::new()
2111 .without_cost_population()
2112 .with_placements_for_device(&placements_fn);
2113 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2114 let alts = plan.alternatives(add_id).unwrap();
2115 assert_eq!(
2116 alts.len(),
2117 2,
2118 "cross-co-located mode aggregates Cpu + Aocl alternatives",
2119 );
2120 }
2121
2122 #[test]
2123 fn compile_plan_precision_requirement_filters_via_default_chain() {
2124 let mut table = KernelBindingTable::new();
2125 register_add_f32(
2127 &mut table,
2128 BackendId::Cpu,
2129 noop_kernel,
2130 PrecisionGuarantee {
2131 bit_stable_on_same_hardware: false,
2132 ..PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU
2133 },
2134 );
2135
2136 let (g, add_id) = build_add_graph();
2137 let order = topo_order(&g, add_id);
2138 let opts = PlanOptions::new()
2139 .without_cost_population()
2140 .with_precision_requirement(PrecisionRequirement::BIT_STABLE);
2141 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
2142 match err {
2143 Error::FilterRejected { filter, .. } => {
2144 assert_eq!(filter, "precision-floor");
2145 }
2146 other => panic!("expected FilterRejected, got {other:?}"),
2147 }
2148 let unconstrained = PlanOptions::new().without_cost_population();
2150 let plan = compile_plan(&g, &order, &table, &unconstrained).expect("compile");
2151 assert!(plan.alternatives(add_id).is_some());
2152 let _ = add_id;
2153 }
2154
2155 #[test]
2156 fn compile_plan_with_cost_ranks_cheaper_winner() {
2157 fn cheap_cost(
2158 _: &[Shape],
2159 _: &[DType],
2160 _: &OpParams,
2161 _: &BackendCapabilities,
2162 ) -> crate::fused::CostEstimate {
2163 crate::fused::CostEstimate {
2164 flops: 10,
2165 bytes_moved: 0,
2166 kernel_overhead_ns: 0,
2167 }
2168 }
2169 fn expensive_cost(
2170 _: &[Shape],
2171 _: &[DType],
2172 _: &OpParams,
2173 _: &BackendCapabilities,
2174 ) -> crate::fused::CostEstimate {
2175 crate::fused::CostEstimate {
2176 flops: 1_000_000,
2177 bytes_moved: 0,
2178 kernel_overhead_ns: 0,
2179 }
2180 }
2181 let mut table = KernelBindingTable::new();
2182 table.register_full(
2183 OpKind::AddElementwise,
2184 &[DType::F32, DType::F32, DType::F32],
2185 BackendId::Cpu,
2186 noop_kernel,
2187 KernelCaps::empty(),
2188 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2189 expensive_cost,
2190 );
2191 table.register_full(
2192 OpKind::AddElementwise,
2193 &[DType::F32, DType::F32, DType::F32],
2194 BackendId::Cuda,
2195 noop_kernel_b,
2196 KernelCaps::empty(),
2197 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2198 cheap_cost,
2199 );
2200
2201 let (g, add_id) = build_add_graph();
2202 let order = topo_order(&g, add_id);
2203 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2204 if dev == DeviceLocation::Cpu {
2205 vec![BackendId::Cpu, BackendId::Cuda]
2206 } else {
2207 vec![]
2208 }
2209 };
2210 let cpu_caps_val = cpu_caps();
2211 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
2212 let opts = PlanOptions::new()
2213 .with_placements_for_device(&placements_fn)
2214 .with_capabilities_for(&caps_fn);
2215 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2216 let alts = plan.alternatives(add_id).unwrap();
2217 assert_eq!(alts.len(), 2);
2218 assert_eq!(
2219 alts.winner().unwrap().backend,
2220 BackendId::Cuda,
2221 "cheaper static cost wins after ranking",
2222 );
2223 }
2224
2225 #[test]
2226 fn compile_plan_judge_layer2_can_flip_layer1_winner() {
2227 use crate::ranker::HashMapJudge;
2231 use fuel_ir::dispatch::SizeClass;
2232
2233 fn cpu_layer1(
2234 _: &[Shape],
2235 _: &[DType],
2236 _: &OpParams,
2237 _: &BackendCapabilities,
2238 ) -> crate::fused::CostEstimate {
2239 crate::fused::CostEstimate {
2240 flops: 10,
2241 bytes_moved: 0,
2242 kernel_overhead_ns: 0,
2243 }
2244 }
2245 fn aocl_layer1(
2246 _: &[Shape],
2247 _: &[DType],
2248 _: &OpParams,
2249 _: &BackendCapabilities,
2250 ) -> crate::fused::CostEstimate {
2251 crate::fused::CostEstimate {
2252 flops: 100_000,
2253 bytes_moved: 0,
2254 kernel_overhead_ns: 0,
2255 }
2256 }
2257 let mut table = KernelBindingTable::new();
2258 table.register_full(
2259 OpKind::AddElementwise,
2260 &[DType::F32, DType::F32, DType::F32],
2261 BackendId::Cpu,
2262 noop_kernel,
2263 KernelCaps::empty(),
2264 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2265 cpu_layer1,
2266 );
2267 table.register_full(
2268 OpKind::AddElementwise,
2269 &[DType::F32, DType::F32, DType::F32],
2270 BackendId::Cuda,
2271 noop_kernel_b,
2272 KernelCaps::empty(),
2273 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2274 aocl_layer1,
2275 );
2276
2277 let (g, add_id) = build_add_graph();
2278 let order = topo_order(&g, add_id);
2279 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2280 if dev == DeviceLocation::Cpu {
2281 vec![BackendId::Cpu, BackendId::Cuda]
2282 } else {
2283 vec![]
2284 }
2285 };
2286 let cpu_caps_val = cpu_caps();
2287 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
2288
2289 let sc = SizeClass::from_elem_count(3);
2292 let mut judge = HashMapJudge::new();
2293 judge.insert(
2294 OpKind::AddElementwise,
2295 DType::F32,
2296 sc,
2297 BackendId::Cpu,
2298 "",
2299 5_000,
2300 0,
2301 );
2302 judge.insert(
2303 OpKind::AddElementwise,
2304 DType::F32,
2305 sc,
2306 BackendId::Cuda,
2307 "",
2308 20,
2309 0,
2310 );
2311
2312 let opts = PlanOptions::new()
2313 .with_placements_for_device(&placements_fn)
2314 .with_capabilities_for(&caps_fn)
2315 .with_judge(&judge);
2316
2317 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2318 let alts = plan.alternatives(add_id).unwrap();
2319 assert_eq!(alts.len(), 2);
2320 assert_eq!(
2321 alts.winner().unwrap().backend,
2322 BackendId::Cuda,
2323 "Layer-2 measurement reverses Layer-1 verdict via compile_plan",
2324 );
2325 }
2326
2327 #[test]
2332 fn compile_plan_stamps_decision_context() {
2333 use fuel_ir::dispatch::SizeClass;
2334
2335 let mut table = KernelBindingTable::new();
2336 register_add_f32(
2337 &mut table,
2338 BackendId::Cpu,
2339 noop_kernel,
2340 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2341 );
2342 let (g, add_id) = build_add_graph();
2343 let order = topo_order(&g, add_id);
2344 let opts = PlanOptions::new().without_cost_population();
2345 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2346 let alts = plan.alternatives(add_id).expect("Add alternatives present");
2347 let ctx = alts.context().expect("context stamped");
2348 assert_eq!(ctx.op, OpKind::AddElementwise);
2349 assert_eq!(ctx.principal_dtype, DType::F32);
2350 assert_eq!(ctx.size_class, SizeClass::from_elem_count(3));
2352 }
2353
2354 #[test]
2363 fn compile_plan_retains_per_device_frontier_no_top_n() {
2364 let mut table = KernelBindingTable::new();
2365 register_add_f32(
2368 &mut table,
2369 BackendId::Cpu,
2370 noop_kernel,
2371 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2372 );
2373 register_add_f32(
2374 &mut table,
2375 BackendId::Cuda,
2376 noop_kernel_b,
2377 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2378 );
2379 register_add_f32(
2380 &mut table,
2381 BackendId::Vulkan,
2382 noop_kernel_c,
2383 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2384 );
2385
2386 let (g, add_id) = build_add_graph();
2387 let order = topo_order(&g, add_id);
2388 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2389 if dev == DeviceLocation::Cpu {
2390 vec![BackendId::Cpu, BackendId::Cuda, BackendId::Vulkan]
2391 } else {
2392 vec![]
2393 }
2394 };
2395 let opts = PlanOptions::new()
2396 .without_cost_population()
2397 .with_placements_for_device(&placements_fn);
2398 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2399 let alts = plan.alternatives(add_id).unwrap();
2400 assert_eq!(
2401 alts.len(),
2402 3,
2403 "all three co-located (device, backend) paths survive — no top-N truncation",
2404 );
2405 }
2406
2407 #[test]
2412 fn compile_plan_pinned_device_matches_stamped_plan() {
2413 let mut table = KernelBindingTable::new();
2414 register_add_f32(
2415 &mut table,
2416 BackendId::Cpu,
2417 noop_kernel,
2418 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2419 );
2420
2421 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2422 if dev == DeviceLocation::Cpu {
2423 vec![BackendId::Cpu]
2424 } else {
2425 vec![]
2426 }
2427 };
2428
2429 let (g_stamped, add_stamped) = build_add_graph();
2431 let order_stamped = topo_order(&g_stamped, add_stamped);
2432 let opts_stamped = PlanOptions::new()
2433 .without_cost_population()
2434 .with_placements_for_device(&placements_fn);
2435 let plan_stamped = compile_plan(&g_stamped, &order_stamped, &table, &opts_stamped)
2436 .expect("stamped compile");
2437
2438 let mut g = Graph::new();
2441 let lhs = g.push(Node {
2442 op: Op::Const,
2443 inputs: vec![],
2444 shape: Shape::from_dims(&[3]),
2445 dtype: DType::F32,
2446 });
2447 let rhs = g.push(Node {
2448 op: Op::Const,
2449 inputs: vec![],
2450 shape: Shape::from_dims(&[3]),
2451 dtype: DType::F32,
2452 });
2453 let add = g.push(Node {
2454 op: Op::Add,
2455 inputs: vec![lhs, rhs],
2456 shape: Shape::from_dims(&[3]),
2457 dtype: DType::F32,
2458 });
2459 let order = topo_order(&g, add);
2460 let opts = PlanOptions::new()
2461 .without_cost_population()
2462 .with_placements_for_device(&placements_fn)
2463 .with_pinned_device(DeviceLocation::Cpu);
2464 let plan = compile_plan(&g, &order, &table, &opts).expect("pinned compile");
2465
2466 let a = plan_stamped.alternatives(add_stamped).expect("stamped set");
2467 let b = plan.alternatives(add).expect("pinned set");
2468 assert_eq!(a.len(), b.len(), "same candidate count");
2469 for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
2470 assert_eq!(ca.backend, cb.backend);
2471 assert_eq!(ca.device, cb.device);
2472 assert_eq!(ca.kernel as usize, cb.kernel as usize, "same kernel ref");
2473 assert_eq!(ca.kernel_source, cb.kernel_source);
2474 }
2475 assert_eq!(a.context(), b.context(), "same decision context");
2476 }
2477
2478 #[test]
2482 fn compile_plan_errors_without_any_device_context() {
2483 let mut table = KernelBindingTable::new();
2484 register_add_f32(
2485 &mut table,
2486 BackendId::Cpu,
2487 noop_kernel,
2488 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2489 );
2490 let mut g = Graph::new();
2491 let lhs = g.push(Node {
2492 op: Op::Const,
2493 inputs: vec![],
2494 shape: Shape::from_dims(&[3]),
2495 dtype: DType::F32,
2496 });
2497 let add = g.push(Node {
2498 op: Op::Add,
2499 inputs: vec![lhs, lhs],
2500 shape: Shape::from_dims(&[3]),
2501 dtype: DType::F32,
2502 });
2503 let order = topo_order(&g, add);
2504 let opts = PlanOptions::new().without_cost_population();
2505 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
2506 let msg = format!("{err:?}");
2507 assert!(
2508 msg.contains("no device context"),
2509 "expected the device-context diagnostic, got: {msg}",
2510 );
2511 }
2512
2513 #[test]
2518 fn compile_plan_skips_op_copy_nodes() {
2519 let mut table = KernelBindingTable::new();
2520 register_add_f32(
2521 &mut table,
2522 BackendId::Cpu,
2523 noop_kernel,
2524 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2525 );
2526 table.register_full(
2529 OpKind::Copy,
2530 &[DType::F32, DType::F32],
2531 BackendId::Cpu,
2532 noop_kernel_b,
2533 KernelCaps::empty(),
2534 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2535 unknown_cost,
2536 );
2537
2538 let (mut g, add_id) = build_add_graph();
2539 let copy_id = g.push(Node {
2540 op: Op::Copy {
2541 target: DeviceLocation::Cpu,
2542 },
2543 inputs: vec![add_id],
2544 shape: Shape::from_dims(&[3]),
2545 dtype: DType::F32,
2546 });
2547 g.set_target_backend(copy_id, BackendId::Cpu);
2548 let order = topo_order(&g, copy_id);
2549 let opts = PlanOptions::new()
2550 .without_cost_population()
2551 .with_pinned_device(DeviceLocation::Cpu);
2552 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2553 assert!(plan.alternatives(add_id).is_some(), "Add is planned");
2554 assert!(
2555 plan.alternatives(copy_id).is_none(),
2556 "Op::Copy is residency-determined — no plan entry",
2557 );
2558 }
2559
2560 #[test]
2564 fn compile_plan_skips_op_move_nodes() {
2565 let mut table = KernelBindingTable::new();
2566 register_add_f32(
2567 &mut table,
2568 BackendId::Cpu,
2569 noop_kernel,
2570 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2571 );
2572 table.register_full(
2575 OpKind::Copy,
2576 &[DType::F32, DType::F32],
2577 BackendId::Cpu,
2578 noop_kernel_b,
2579 KernelCaps::empty(),
2580 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2581 unknown_cost,
2582 );
2583
2584 let (mut g, add_id) = build_add_graph();
2585 let move_id = g.push(Node {
2586 op: Op::Move {
2587 target: DeviceLocation::Cpu,
2588 },
2589 inputs: vec![add_id],
2590 shape: Shape::from_dims(&[3]),
2591 dtype: DType::F32,
2592 });
2593 g.set_target_backend(move_id, BackendId::Cpu);
2594 let order = topo_order(&g, move_id);
2595 let opts = PlanOptions::new()
2596 .without_cost_population()
2597 .with_pinned_device(DeviceLocation::Cpu);
2598 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2599 assert!(plan.alternatives(add_id).is_some(), "Add is planned");
2600 assert!(
2601 plan.alternatives(move_id).is_none(),
2602 "Op::Move is residency-determined — no plan entry",
2603 );
2604 }
2605
2606 #[test]
2610 fn compile_plan_fallback_admits_off_device_candidate() {
2611 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2612 let mut table = KernelBindingTable::new();
2613 register_add_f32(
2616 &mut table,
2617 BackendId::Cpu,
2618 noop_kernel,
2619 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2620 );
2621
2622 let mut g = Graph::new();
2623 let lhs = g.push(Node {
2624 op: Op::Const,
2625 inputs: vec![],
2626 shape: Shape::from_dims(&[3]),
2627 dtype: DType::F32,
2628 });
2629 let add = g.push(Node {
2630 op: Op::Add,
2631 inputs: vec![lhs, lhs],
2632 shape: Shape::from_dims(&[3]),
2633 dtype: DType::F32,
2634 });
2635 let order = topo_order(&g, add);
2636
2637 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2638 if dev == cuda0 {
2639 vec![BackendId::Cuda]
2640 } else {
2641 vec![BackendId::Cpu]
2642 }
2643 };
2644 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2645 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
2646 };
2647 let opts = PlanOptions::new()
2648 .without_cost_population()
2649 .with_pinned_device(cuda0)
2650 .with_placements_for_device(&placements_fn)
2651 .with_fallback_placements_for(&fallback_fn);
2652 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2653 let alts = plan.alternatives(add).expect("Add planned via fallback");
2654 assert_eq!(alts.len(), 1, "fallback set frozen to one winner");
2655 let w = alts.winner().unwrap();
2656 assert_eq!(w.backend, BackendId::Cpu);
2657 assert_eq!(w.device, DeviceLocation::Cpu, "off-device placement");
2658 }
2659
2660 #[test]
2666 fn compile_plan_fallback_not_consulted_when_pinned_has_impl() {
2667 let mut table = KernelBindingTable::new();
2668 register_add_f32(
2669 &mut table,
2670 BackendId::Cpu,
2671 noop_kernel,
2672 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2673 );
2674 register_add_f32(
2675 &mut table,
2676 BackendId::Cuda,
2677 noop_kernel_b,
2678 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2679 );
2680 let (g, add_id) = build_add_graph();
2681 let order = topo_order(&g, add_id);
2682 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2683 if dev == DeviceLocation::Cpu {
2684 vec![BackendId::Cpu]
2685 } else {
2686 vec![]
2687 }
2688 };
2689 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2690 panic!(
2691 "fallback consulted although the pinned device has an \
2692 implementation — locality policy violated",
2693 );
2694 };
2695 let opts = PlanOptions::new()
2696 .without_cost_population()
2697 .with_pinned_device(DeviceLocation::Cpu)
2698 .with_placements_for_device(&placements_fn)
2699 .with_fallback_placements_for(&fallback_fn);
2700 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2701 let alts = plan.alternatives(add_id).unwrap();
2702 assert_eq!(alts.len(), 1);
2703 assert_eq!(alts.winner().unwrap().device, DeviceLocation::Cpu);
2704 }
2705
2706 #[test]
2709 fn compile_plan_fallback_denied_for_destructive_ops() {
2710 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2711 let mut table = KernelBindingTable::new();
2712 table.register_full(
2714 OpKind::ReluInplace,
2715 &[DType::F32, DType::F32],
2716 BackendId::Cpu,
2717 noop_kernel,
2718 KernelCaps::empty(),
2719 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2720 unknown_cost,
2721 );
2722 let mut g = Graph::new();
2723 let lhs = g.push(Node {
2724 op: Op::Const,
2725 inputs: vec![],
2726 shape: Shape::from_dims(&[3]),
2727 dtype: DType::F32,
2728 });
2729 let relu = g.push(Node {
2730 op: Op::ReluInplace,
2731 inputs: vec![lhs],
2732 shape: Shape::from_dims(&[3]),
2733 dtype: DType::F32,
2734 });
2735 let order = topo_order(&g, relu);
2736 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2737 if dev == cuda0 {
2738 vec![BackendId::Cuda]
2739 } else {
2740 vec![BackendId::Cpu]
2741 }
2742 };
2743 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2744 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
2745 };
2746 let opts = PlanOptions::new()
2747 .without_cost_population()
2748 .with_pinned_device(cuda0)
2749 .with_placements_for_device(&placements_fn)
2750 .with_fallback_placements_for(&fallback_fn);
2751 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
2752 assert!(
2753 matches!(
2754 err,
2755 Error::NoBackendForOp {
2756 op: OpKind::ReluInplace,
2757 ..
2758 }
2759 ),
2760 "destructive op must NOT fall back off-device; got {err:?}",
2761 );
2762 }
2763
2764 #[test]
2769 fn compile_plan_fallback_freezes_to_single_winner() {
2770 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2771 let vk0 = DeviceLocation::Vulkan { gpu_id: 0 };
2772 let mut table = KernelBindingTable::new();
2773 register_add_f32(
2774 &mut table,
2775 BackendId::Cpu,
2776 noop_kernel,
2777 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2778 );
2779 register_add_f32(
2780 &mut table,
2781 BackendId::Vulkan,
2782 noop_kernel_b,
2783 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2784 );
2785
2786 let mut g = Graph::new();
2787 let lhs = g.push(Node {
2788 op: Op::Const,
2789 inputs: vec![],
2790 shape: Shape::from_dims(&[3]),
2791 dtype: DType::F32,
2792 });
2793 let add = g.push(Node {
2794 op: Op::Add,
2795 inputs: vec![lhs, lhs],
2796 shape: Shape::from_dims(&[3]),
2797 dtype: DType::F32,
2798 });
2799 let order = topo_order(&g, add);
2800 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2801 if dev == cuda0 {
2802 vec![BackendId::Cuda]
2803 } else {
2804 vec![]
2805 }
2806 };
2807 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2808 vec![
2809 (BackendId::Cpu, DeviceLocation::Cpu),
2810 (BackendId::Vulkan, vk0),
2811 ]
2812 };
2813 let opts = PlanOptions::new()
2814 .without_cost_population()
2815 .with_pinned_device(cuda0)
2816 .with_placements_for_device(&placements_fn)
2817 .with_fallback_placements_for(&fallback_fn);
2818 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2819 let alts = plan.alternatives(add).unwrap();
2820 assert_eq!(
2821 alts.len(),
2822 1,
2823 "fallback set must freeze to its single ranked winner",
2824 );
2825 }
2826
2827 struct FlatEstimator {
2830 latency_ns: u64,
2831 }
2832
2833 impl crate::ranker::TransferEstimator for FlatEstimator {
2834 fn estimate_transfer_ns(
2835 &self,
2836 src: DeviceLocation,
2837 dst: DeviceLocation,
2838 _bytes: u64,
2839 ) -> u64 {
2840 if src == dst { 0 } else { self.latency_ns }
2841 }
2842 }
2843
2844 #[test]
2850 fn compile_plan_prices_fallback_by_input_residency() {
2851 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2852 let vk0 = DeviceLocation::Vulkan { gpu_id: 0 };
2853 let mut table = KernelBindingTable::new();
2854 register_add_f32(
2856 &mut table,
2857 BackendId::Cpu,
2858 noop_kernel,
2859 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2860 );
2861 register_add_f32(
2862 &mut table,
2863 BackendId::Vulkan,
2864 noop_kernel_b,
2865 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2866 );
2867
2868 let mut g = Graph::new();
2869 let lhs = g.push(Node {
2870 op: Op::Const,
2871 inputs: vec![],
2872 shape: Shape::from_dims(&[4]),
2873 dtype: DType::F32,
2874 });
2875 let add = g.push(Node {
2876 op: Op::Add,
2877 inputs: vec![lhs, lhs],
2878 shape: Shape::from_dims(&[4]),
2879 dtype: DType::F32,
2880 });
2881 let order = topo_order(&g, add);
2882
2883 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2884 if dev == cuda0 {
2885 vec![BackendId::Cuda]
2886 } else {
2887 vec![]
2888 }
2889 };
2890 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2891 vec![
2892 (BackendId::Cpu, DeviceLocation::Cpu),
2893 (BackendId::Vulkan, vk0),
2894 ]
2895 };
2896 let residency_fn =
2900 move |id: NodeId| -> Option<DeviceLocation> { (id == lhs).then_some(vk0) };
2901 let est = FlatEstimator { latency_ns: 1_000 };
2902 let cpu_caps_val = cpu_caps();
2903 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
2904 let opts = PlanOptions::new()
2905 .with_pinned_device(cuda0)
2906 .with_placements_for_device(&placements_fn)
2907 .with_fallback_placements_for(&fallback_fn)
2908 .with_capabilities_for(&caps_fn)
2909 .with_transfer_estimator(&est)
2910 .with_input_residency(&residency_fn);
2911 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2912 let alts = plan.alternatives(add).expect("Add planned via fallback");
2913 assert_eq!(alts.len(), 1, "fallback narrows to a single winner");
2914 let w = alts.winner().unwrap();
2915 assert_eq!(
2916 w.device, vk0,
2917 "transfer pricing moves the fallback to the inputs' residency",
2918 );
2919 assert_eq!(w.inbound_transfer_ns, 0, "co-resident inputs price zero");
2920 }
2921
2922 fn cost_600(
2925 _: &[Shape],
2926 _: &[DType],
2927 _: &OpParams,
2928 _: &BackendCapabilities,
2929 ) -> crate::fused::CostEstimate {
2930 crate::fused::CostEstimate {
2931 flops: 600,
2932 bytes_moved: 0,
2933 kernel_overhead_ns: 0,
2934 }
2935 }
2936 fn cost_10(
2937 _: &[Shape],
2938 _: &[DType],
2939 _: &OpParams,
2940 _: &BackendCapabilities,
2941 ) -> crate::fused::CostEstimate {
2942 crate::fused::CostEstimate {
2943 flops: 10,
2944 bytes_moved: 0,
2945 kernel_overhead_ns: 0,
2946 }
2947 }
2948 fn cost_15_000(
2952 _: &[Shape],
2953 _: &[DType],
2954 _: &OpParams,
2955 _: &BackendCapabilities,
2956 ) -> crate::fused::CostEstimate {
2957 crate::fused::CostEstimate {
2958 flops: 15_000,
2959 bytes_moved: 0,
2960 kernel_overhead_ns: 0,
2961 }
2962 }
2963 fn cost_10_000_000(
2964 _: &[Shape],
2965 _: &[DType],
2966 _: &OpParams,
2967 _: &BackendCapabilities,
2968 ) -> crate::fused::CostEstimate {
2969 crate::fused::CostEstimate {
2970 flops: 10_000_000,
2971 bytes_moved: 0,
2972 kernel_overhead_ns: 0,
2973 }
2974 }
2975
2976 fn relaxed_plan_with_costs(
2982 cpu_cost: crate::kernel::CostFn,
2983 cuda_cost: crate::kernel::CostFn,
2984 estimator: &FlatEstimator,
2985 ) -> AlternativeSet {
2986 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2987 let mut table = KernelBindingTable::new();
2988 table.register_full(
2989 OpKind::AddElementwise,
2990 &[DType::F32, DType::F32, DType::F32],
2991 BackendId::Cpu,
2992 noop_kernel,
2993 KernelCaps::empty(),
2994 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2995 cpu_cost,
2996 );
2997 table.register_full(
2998 OpKind::AddElementwise,
2999 &[DType::F32, DType::F32, DType::F32],
3000 BackendId::Cuda,
3001 noop_kernel_b,
3002 KernelCaps::empty(),
3003 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3004 cuda_cost,
3005 );
3006
3007 let (g, add_id) = build_add_graph();
3008 let order = topo_order(&g, add_id);
3009 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3010 if dev == DeviceLocation::Cpu {
3011 vec![BackendId::Cpu]
3012 } else {
3013 vec![]
3014 }
3015 };
3016 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3017 vec![(BackendId::Cuda, cuda0)]
3018 };
3019 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3022 let cpu_caps_val = cpu_caps();
3023 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3024 let opts = PlanOptions::new()
3025 .with_pinned_device(DeviceLocation::Cpu)
3026 .with_placements_for_device(&placements_fn)
3027 .with_fallback_placements_for(&fallback_fn)
3028 .with_capabilities_for(&caps_fn)
3029 .with_transfer_estimator(estimator)
3030 .with_input_residency(&residency_fn);
3031 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3032 plan.alternatives(add_id).expect("Add planned").clone()
3033 }
3034
3035 #[test]
3039 fn compile_plan_relaxed_tiny_op_stays_local_when_transfer_dominates() {
3040 let est = FlatEstimator {
3043 latency_ns: 1_000_000,
3044 };
3045 let set = relaxed_plan_with_costs(cost_600, cost_10, &est);
3046 let w = set.winner().unwrap();
3047 assert_eq!(
3048 w.device,
3049 DeviceLocation::Cpu,
3050 "transfer dominates → stay local"
3051 );
3052 assert_eq!(w.inbound_transfer_ns, 0, "local winner pays no transfer");
3053 assert!(
3054 set.alternatives()
3055 .iter()
3056 .all(|c| c.device == DeviceLocation::Cpu),
3057 "off-device siblings pruned after rank",
3058 );
3059 }
3060
3061 #[test]
3094 fn compile_plan_uncapped_gpu_no_longer_wins_by_being_free() {
3095 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3096
3097 fn build_table() -> KernelBindingTable {
3104 let mut table = KernelBindingTable::new();
3105 table.register_full(
3106 OpKind::AddElementwise,
3107 &[DType::F32, DType::F32, DType::F32],
3108 BackendId::Cpu,
3109 noop_kernel,
3110 KernelCaps::empty(),
3111 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3112 cost_600,
3113 );
3114 table.register_full(
3115 OpKind::AddElementwise,
3116 &[DType::F32, DType::F32, DType::F32],
3117 BackendId::Cuda,
3118 noop_kernel_b,
3119 KernelCaps::empty(),
3120 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3121 cost_15_000,
3122 );
3123 table
3124 }
3125
3126 fn winner_device_under(
3134 table: &KernelBindingTable,
3135 cpu_caps_val: &'static BackendCapabilities,
3136 gpu_caps: Option<&'static BackendCapabilities>,
3137 cuda0: DeviceLocation,
3138 ) -> DeviceLocation {
3139 let (g, add_id) = build_add_graph();
3140 let order = topo_order(&g, add_id);
3141 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3142 if dev == DeviceLocation::Cpu {
3143 vec![BackendId::Cpu]
3144 } else {
3145 vec![]
3146 }
3147 };
3148 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3149 vec![(BackendId::Cuda, cuda0)]
3150 };
3151 let residency_fn =
3155 |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3156 let est = FlatEstimator { latency_ns: 100 };
3159 let caps_fn = move |b: BackendId| -> Option<&BackendCapabilities> {
3160 match b {
3161 BackendId::Cpu => Some(cpu_caps_val),
3162 BackendId::Cuda => gpu_caps,
3163 _ => None,
3164 }
3165 };
3166 let opts = PlanOptions::new()
3167 .with_pinned_device(DeviceLocation::Cpu)
3168 .with_placements_for_device(&placements_fn)
3169 .with_fallback_placements_for(&fallback_fn)
3170 .with_capabilities_for(&caps_fn)
3171 .with_transfer_estimator(&est)
3172 .with_input_residency(&residency_fn);
3173 let plan = compile_plan(&g, &order, table, &opts).expect("compile");
3174 plan.alternatives(add_id).unwrap().winner().unwrap().device
3175 }
3176
3177 let table = build_table();
3178 let cpu_caps_val: &'static BackendCapabilities = Box::leak(Box::new(cpu_caps()));
3182
3183 let winner_bug = winner_device_under(&table, cpu_caps_val, None, cuda0);
3187 assert_eq!(
3188 winner_bug, cuda0,
3189 "PRE-FIX: an uncapped CUDA candidate is skipped by \
3190 compute_static_costs, prices at 0 + 200 transfer, and \
3191 spuriously beats the CPU's honest 600 — this IS the bug",
3192 );
3193
3194 let cuda_caps_val: &'static BackendCapabilities = Box::leak(Box::new(
3197 crate::dispatch::derive_backend_caps(BackendId::Cuda, cuda0, &table),
3198 ));
3199 assert!(
3202 cuda_caps_val
3203 .op_dtype_support
3204 .contains(&(OpKind::AddElementwise, DType::F32)),
3205 "derive_backend_caps must mirror the binding table's \
3206 registered (op, output-dtype) pairs for the backend",
3207 );
3208 assert_eq!(cuda_caps_val.backend_id, BackendId::Cuda);
3209 assert_eq!(cuda_caps_val.device_location, cuda0);
3210
3211 let winner_fixed = winner_device_under(&table, cpu_caps_val, Some(cuda_caps_val), cuda0);
3212 assert_eq!(
3213 winner_fixed,
3214 DeviceLocation::Cpu,
3215 "POST-FIX: with GPU caps registered the CUDA candidate is \
3216 costed honestly (15000 FLOPs ÷ 30/ns = 500 ns compute + 200 \
3217 transfer = 700 > CPU 600), so the CPU-pinned realize stays \
3218 on CPU — no spill onto the unseeded GPU",
3219 );
3220 }
3221
3222 #[test]
3239 fn compile_plan_places_large_compute_on_gpu_small_on_cpu_by_throughput() {
3240 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3241
3242 fn winner(cost: crate::kernel::CostFn, cuda0: DeviceLocation) -> DeviceLocation {
3243 let mut table = KernelBindingTable::new();
3244 table.register_full(
3245 OpKind::AddElementwise,
3246 &[DType::F32, DType::F32, DType::F32],
3247 BackendId::Cpu,
3248 noop_kernel,
3249 KernelCaps::empty(),
3250 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3251 cost,
3252 );
3253 table.register_full(
3254 OpKind::AddElementwise,
3255 &[DType::F32, DType::F32, DType::F32],
3256 BackendId::Cuda,
3257 noop_kernel_b,
3258 KernelCaps::empty(),
3259 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3260 cost,
3261 );
3262
3263 let (g, add_id) = build_add_graph();
3264 let order = topo_order(&g, add_id);
3265 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3266 if dev == DeviceLocation::Cpu {
3267 vec![BackendId::Cpu]
3268 } else {
3269 vec![]
3270 }
3271 };
3272 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3273 vec![(BackendId::Cuda, cuda0)]
3274 };
3275 let residency_fn =
3276 |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3277 let est = FlatEstimator { latency_ns: 100 };
3280 let cpu_caps_val = cpu_caps();
3281 let cuda_caps_val =
3282 crate::dispatch::derive_backend_caps(BackendId::Cuda, cuda0, &table);
3283 let caps_fn = |b: BackendId| -> Option<&BackendCapabilities> {
3284 match b {
3285 BackendId::Cpu => Some(&cpu_caps_val),
3286 BackendId::Cuda => Some(&cuda_caps_val),
3287 _ => None,
3288 }
3289 };
3290 let opts = PlanOptions::new()
3291 .with_pinned_device(DeviceLocation::Cpu)
3292 .with_placements_for_device(&placements_fn)
3293 .with_fallback_placements_for(&fallback_fn)
3294 .with_capabilities_for(&caps_fn)
3295 .with_transfer_estimator(&est)
3296 .with_input_residency(&residency_fn);
3297 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3298 plan.alternatives(add_id).unwrap().winner().unwrap().device
3299 }
3300
3301 assert_eq!(
3302 winner(cost_100, cuda0),
3303 DeviceLocation::Cpu,
3304 "SMALL op: the GPU's throughput win on 100 FLOPs (~3 ns) \
3305 can't overcome the 200 ns inbound transfer → stay on CPU",
3306 );
3307 assert_eq!(
3308 winner(cost_10_000_000, cuda0),
3309 cuda0,
3310 "LARGE op: the GPU's throughput win on 10 M FLOPs (~333 k ns) \
3311 dwarfs the 200 ns transfer → move to CUDA. RED under the \
3312 fixed 1-FLOP/ns prior (equal compute-ns → the transfer \
3313 always loses the GPU the placement)",
3314 );
3315 }
3316
3317 #[test]
3328 fn compile_plan_without_cost_placement_keeps_large_op_on_cpu() {
3329 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3330 let mut table = KernelBindingTable::new();
3331 table.register_full(
3332 OpKind::AddElementwise,
3333 &[DType::F32, DType::F32, DType::F32],
3334 BackendId::Cpu,
3335 noop_kernel,
3336 KernelCaps::empty(),
3337 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3338 cost_10_000_000,
3339 );
3340 table.register_full(
3341 OpKind::AddElementwise,
3342 &[DType::F32, DType::F32, DType::F32],
3343 BackendId::Cuda,
3344 noop_kernel_b,
3345 KernelCaps::empty(),
3346 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3347 cost_10_000_000,
3348 );
3349
3350 let (g, add_id) = build_add_graph();
3351 let order = topo_order(&g, add_id);
3352 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3353 if dev == DeviceLocation::Cpu {
3354 vec![BackendId::Cpu]
3355 } else {
3356 vec![]
3357 }
3358 };
3359 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3360 vec![(BackendId::Cuda, cuda0)]
3361 };
3362 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3363 let est = FlatEstimator { latency_ns: 100 };
3364 let cpu_caps_val = cpu_caps();
3365 let cuda_caps_val = crate::dispatch::derive_backend_caps(BackendId::Cuda, cuda0, &table);
3366 let caps_fn = |b: BackendId| -> Option<&BackendCapabilities> {
3367 match b {
3368 BackendId::Cpu => Some(&cpu_caps_val),
3369 BackendId::Cuda => Some(&cuda_caps_val),
3370 _ => None,
3371 }
3372 };
3373 let opts = PlanOptions::new()
3374 .with_pinned_device(DeviceLocation::Cpu)
3375 .with_placements_for_device(&placements_fn)
3376 .with_fallback_placements_for(&fallback_fn)
3377 .with_capabilities_for(&caps_fn)
3378 .with_transfer_estimator(&est)
3379 .with_input_residency(&residency_fn)
3380 .without_cost_placement();
3381 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3382 let set = plan.alternatives(add_id).unwrap();
3383 assert_eq!(
3384 set.winner().unwrap().device,
3385 DeviceLocation::Cpu,
3386 "without_cost_placement: the large GPU-favorable op stays on the \
3387 pinned CPU device (no relaxed cross-device enumeration)",
3388 );
3389 assert!(
3390 set.alternatives()
3391 .iter()
3392 .all(|c| c.device == DeviceLocation::Cpu),
3393 "no off-device candidate enumerated at all",
3394 );
3395 }
3396
3397 #[test]
3402 fn compile_plan_relaxed_huge_op_moves_when_kernel_gap_dominates() {
3403 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3404 let est = FlatEstimator { latency_ns: 1_000 };
3406 let set = relaxed_plan_with_costs(cost_10_000_000, cost_10, &est);
3407 let w = set.winner().unwrap();
3408 assert_eq!(w.device, cuda0, "kernel gap dominates → move");
3409 assert_eq!(
3410 w.inbound_transfer_ns, 2_000,
3411 "the move's two input crossings are priced on the winner",
3412 );
3413 assert!(
3414 set.alternatives().iter().all(|c| c.device == cuda0),
3415 "set pruned to the winner's device",
3416 );
3417 }
3418
3419 #[test]
3424 fn compile_plan_relaxed_zero_signal_ties_stay_local() {
3425 let est = FlatEstimator { latency_ns: 0 };
3426 let set = relaxed_plan_with_costs(unknown_cost, unknown_cost, &est);
3427 assert_eq!(
3428 set.winner().unwrap().device,
3429 DeviceLocation::Cpu,
3430 "ties break toward the decision device",
3431 );
3432 }
3433
3434 #[test]
3438 fn compile_plan_relaxed_single_device_plan_unchanged() {
3439 let mut table = KernelBindingTable::new();
3440 register_add_f32(
3441 &mut table,
3442 BackendId::Cpu,
3443 noop_kernel,
3444 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3445 );
3446 let (g, add_id) = build_add_graph();
3447 let order = topo_order(&g, add_id);
3448 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3449 if dev == DeviceLocation::Cpu {
3450 vec![BackendId::Cpu]
3451 } else {
3452 vec![]
3453 }
3454 };
3455 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> { Vec::new() };
3457 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3458 let cpu_caps_val = cpu_caps();
3459 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3460
3461 let base_opts = PlanOptions::new()
3462 .with_pinned_device(DeviceLocation::Cpu)
3463 .with_placements_for_device(&placements_fn)
3464 .with_fallback_placements_for(&fallback_fn)
3465 .with_capabilities_for(&caps_fn);
3466 let base = compile_plan(&g, &order, &table, &base_opts).expect("base");
3467
3468 let est = FlatEstimator {
3469 latency_ns: 1_000_000,
3470 };
3471 let wired_opts = PlanOptions::new()
3472 .with_pinned_device(DeviceLocation::Cpu)
3473 .with_placements_for_device(&placements_fn)
3474 .with_fallback_placements_for(&fallback_fn)
3475 .with_capabilities_for(&caps_fn)
3476 .with_transfer_estimator(&est)
3477 .with_input_residency(&residency_fn);
3478 let wired = compile_plan(&g, &order, &table, &wired_opts).expect("wired");
3479
3480 let a = base.alternatives(add_id).unwrap();
3481 let b = wired.alternatives(add_id).unwrap();
3482 assert_eq!(a.len(), b.len(), "same candidate count");
3483 for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
3484 assert_eq!(ca.backend, cb.backend);
3485 assert_eq!(ca.device, cb.device);
3486 assert_eq!(ca.kernel as usize, cb.kernel as usize, "same kernel ref");
3487 assert_eq!(ca.static_cost, cb.static_cost, "same Layer-1 cost");
3488 assert_eq!(cb.inbound_transfer_ns, 0, "no transfer term fires");
3489 }
3490 assert_eq!(a.context(), b.context(), "same decision context");
3491 }
3492
3493 #[test]
3498 fn compile_plan_relaxed_respects_explicit_placement_pin() {
3499 let mut table = KernelBindingTable::new();
3500 register_add_f32(
3501 &mut table,
3502 BackendId::Cpu,
3503 noop_kernel,
3504 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3505 );
3506 register_add_f32(
3507 &mut table,
3508 BackendId::Cuda,
3509 noop_kernel_b,
3510 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3511 );
3512 let (mut g, add_id) = build_add_graph();
3513 g.set_placement(add_id, DeviceLocation::Cpu);
3515 let order = topo_order(&g, add_id);
3516 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3517 if dev == DeviceLocation::Cpu {
3518 vec![BackendId::Cpu]
3519 } else {
3520 vec![]
3521 }
3522 };
3523 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3524 panic!(
3525 "fallback consulted for a hard-pinned node — explicit \
3526 placements must not enter the priced relax",
3527 );
3528 };
3529 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3530 let est = FlatEstimator { latency_ns: 0 };
3531 let cpu_caps_val = cpu_caps();
3532 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3533 let opts = PlanOptions::new()
3534 .with_pinned_device(DeviceLocation::Cpu)
3535 .with_placements_for_device(&placements_fn)
3536 .with_fallback_placements_for(&fallback_fn)
3537 .with_capabilities_for(&caps_fn)
3538 .with_transfer_estimator(&est)
3539 .with_input_residency(&residency_fn);
3540 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3541 assert_eq!(
3542 plan.alternatives(add_id).unwrap().winner().unwrap().device,
3543 DeviceLocation::Cpu,
3544 );
3545 }
3546
3547 #[test]
3550 fn compile_plan_relaxed_destructive_never_moves() {
3551 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3552 let mut table = KernelBindingTable::new();
3553 table.register_full(
3554 OpKind::ReluInplace,
3555 &[DType::F32, DType::F32],
3556 BackendId::Cpu,
3557 noop_kernel,
3558 KernelCaps::empty(),
3559 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3560 cost_600,
3561 );
3562 table.register_full(
3563 OpKind::ReluInplace,
3564 &[DType::F32, DType::F32],
3565 BackendId::Cuda,
3566 noop_kernel_b,
3567 KernelCaps::empty(),
3568 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3569 cost_10,
3570 );
3571 let mut g = Graph::new();
3572 let lhs = g.push(Node {
3573 op: Op::Const,
3574 inputs: vec![],
3575 shape: Shape::from_dims(&[3]),
3576 dtype: DType::F32,
3577 });
3578 let relu = g.push(Node {
3579 op: Op::ReluInplace,
3580 inputs: vec![lhs],
3581 shape: Shape::from_dims(&[3]),
3582 dtype: DType::F32,
3583 });
3584 let order = topo_order(&g, relu);
3585 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3586 if dev == DeviceLocation::Cpu {
3587 vec![BackendId::Cpu]
3588 } else {
3589 vec![]
3590 }
3591 };
3592 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3593 vec![(BackendId::Cuda, cuda0)]
3594 };
3595 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3596 let est = FlatEstimator { latency_ns: 0 };
3597 let cpu_caps_val = cpu_caps();
3598 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3599 let opts = PlanOptions::new()
3600 .with_pinned_device(DeviceLocation::Cpu)
3601 .with_placements_for_device(&placements_fn)
3602 .with_fallback_placements_for(&fallback_fn)
3603 .with_capabilities_for(&caps_fn)
3604 .with_transfer_estimator(&est)
3605 .with_input_residency(&residency_fn);
3606 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3607 assert_eq!(
3608 plan.alternatives(relu).unwrap().winner().unwrap().device,
3609 DeviceLocation::Cpu,
3610 "destructive op stays on the device owning its mutation target",
3611 );
3612 }
3613
3614 #[test]
3619 fn compile_plan_filter_rejected_pinned_device_falls_back() {
3620 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3621 let mut table = KernelBindingTable::new();
3622 register_add_f32(
3625 &mut table,
3626 BackendId::Cuda,
3627 noop_kernel_b,
3628 PrecisionGuarantee {
3629 bit_stable_on_same_hardware: false,
3630 ..PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU
3631 },
3632 );
3633 register_add_f32(
3634 &mut table,
3635 BackendId::Cpu,
3636 noop_kernel,
3637 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3638 );
3639 let mut g = Graph::new();
3640 let lhs = g.push(Node {
3641 op: Op::Const,
3642 inputs: vec![],
3643 shape: Shape::from_dims(&[3]),
3644 dtype: DType::F32,
3645 });
3646 let add = g.push(Node {
3647 op: Op::Add,
3648 inputs: vec![lhs, lhs],
3649 shape: Shape::from_dims(&[3]),
3650 dtype: DType::F32,
3651 });
3652 let order = topo_order(&g, add);
3653 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
3654 if dev == cuda0 {
3655 vec![BackendId::Cuda]
3656 } else {
3657 vec![]
3658 }
3659 };
3660 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3661 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
3662 };
3663 let opts = PlanOptions::new()
3664 .without_cost_population()
3665 .with_pinned_device(cuda0)
3666 .with_placements_for_device(&placements_fn)
3667 .with_fallback_placements_for(&fallback_fn)
3668 .with_precision_requirement(PrecisionRequirement::BIT_STABLE);
3669 let plan = compile_plan(&g, &order, &table, &opts)
3670 .expect("filter-rejected pin falls back instead of erroring");
3671 let alts = plan.alternatives(add).expect("Add planned via fallback");
3672 assert_eq!(alts.len(), 1, "fallback set frozen to one winner");
3673 let w = alts.winner().unwrap();
3674 assert_eq!(w.backend, BackendId::Cpu);
3675 assert_eq!(w.device, DeviceLocation::Cpu);
3676 assert!(
3677 w.precision.bit_stable_on_same_hardware,
3678 "the admissible off-device sibling won",
3679 );
3680 }
3681
3682 #[test]
3687 fn compile_plan_without_estimator_prices_nothing() {
3688 let mut table = KernelBindingTable::new();
3689 register_add_f32(
3690 &mut table,
3691 BackendId::Cpu,
3692 noop_kernel,
3693 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3694 );
3695 let (g, add_id) = build_add_graph();
3696 let order = topo_order(&g, add_id);
3697 let cpu_caps_val = cpu_caps();
3698 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3699 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3700
3701 let base_opts = PlanOptions::new().with_capabilities_for(&caps_fn);
3702 let base = compile_plan(&g, &order, &table, &base_opts).expect("base");
3703
3704 let with_residency = PlanOptions::new()
3705 .with_capabilities_for(&caps_fn)
3706 .with_input_residency(&residency_fn);
3707 let plan = compile_plan(&g, &order, &table, &with_residency).expect("plan");
3708
3709 let a = base.alternatives(add_id).unwrap();
3710 let b = plan.alternatives(add_id).unwrap();
3711 assert_eq!(a.len(), b.len());
3712 for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
3713 assert_eq!(ca.backend, cb.backend);
3714 assert_eq!(ca.device, cb.device);
3715 assert_eq!(ca.kernel as usize, cb.kernel as usize);
3716 assert_eq!(ca.inbound_transfer_ns, 0);
3717 assert_eq!(cb.inbound_transfer_ns, 0);
3718 }
3719 }
3720
3721 #[test]
3727 fn compile_plan_require_transfer_pricing_errors_without_estimator() {
3728 let mut table = KernelBindingTable::new();
3729 register_add_f32(
3730 &mut table,
3731 BackendId::Cpu,
3732 noop_kernel,
3733 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3734 );
3735 let (g, add_id) = build_add_graph();
3736 let order = topo_order(&g, add_id);
3737 let cpu_caps_val = cpu_caps();
3738 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3739
3740 let opts = PlanOptions::new()
3743 .with_capabilities_for(&caps_fn)
3744 .require_transfer_pricing();
3745 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
3746 let msg = format!("{err:?}");
3747 assert!(
3748 msg.contains("transfer") && (msg.contains("estimator") || msg.contains("pricing")),
3749 "error should name the missing transfer estimator / pricing; got: {msg}",
3750 );
3751 }
3752
3753 #[test]
3756 fn compile_plan_require_transfer_pricing_ok_with_estimator() {
3757 let mut table = KernelBindingTable::new();
3758 register_add_f32(
3759 &mut table,
3760 BackendId::Cpu,
3761 noop_kernel,
3762 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3763 );
3764 let (g, add_id) = build_add_graph();
3765 let order = topo_order(&g, add_id);
3766 let cpu_caps_val = cpu_caps();
3767 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3768 let est = FlatEstimator { latency_ns: 1000 };
3769
3770 let opts = PlanOptions::new()
3771 .with_capabilities_for(&caps_fn)
3772 .with_transfer_estimator(&est)
3773 .require_transfer_pricing();
3774 let plan = compile_plan(&g, &order, &table, &opts)
3775 .expect("require_transfer_pricing WITH an estimator must plan fine");
3776 assert!(plan.alternatives(add_id).is_some());
3777 }
3778
3779 #[test]
3780 fn compile_plan_passes_input_layouts_to_filter_chain() {
3781 let mut table = KernelBindingTable::new();
3785 table.register_full(
3786 OpKind::AddElementwise,
3787 &[DType::F32, DType::F32, DType::F32],
3788 BackendId::Cpu,
3789 noop_kernel,
3790 KernelCaps::empty(),
3791 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3792 unknown_cost,
3793 );
3794 table.register_full(
3795 OpKind::AddElementwise,
3796 &[DType::F32, DType::F32, DType::F32],
3797 BackendId::Cpu,
3798 noop_kernel_b,
3799 KernelCaps::strided_input(),
3800 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3801 unknown_cost,
3802 );
3803
3804 let mut g = Graph::new();
3806 let lhs = g.push(Node {
3807 op: Op::Const,
3808 inputs: vec![],
3809 shape: Shape::from_dims(&[6]),
3810 dtype: DType::F32,
3811 });
3812 let strides: StrideVec = smallvec![2isize];
3815 g.set_layout(lhs, Layout::new(Shape::from_dims(&[6]), strides, 0));
3816 let rhs = g.push(Node {
3817 op: Op::Const,
3818 inputs: vec![],
3819 shape: Shape::from_dims(&[6]),
3820 dtype: DType::F32,
3821 });
3822 let add = g.push(Node {
3823 op: Op::Add,
3824 inputs: vec![lhs, rhs],
3825 shape: Shape::from_dims(&[6]),
3826 dtype: DType::F32,
3827 });
3828 g.set_target_backend(add, BackendId::Cpu);
3829 let order = topo_order(&g, add);
3830 let opts = PlanOptions::new().without_cost_population();
3831 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3832 let alts = plan.alternatives(add).unwrap();
3833 assert_eq!(alts.len(), 1);
3836 assert!(alts.winner().unwrap().caps.strided_input);
3837 }
3838
3839 struct BytesEstimator {
3846 latency_ns: u64,
3847 ns_per_byte: u64,
3848 }
3849
3850 impl crate::ranker::TransferEstimator for BytesEstimator {
3851 fn estimate_transfer_ns(
3852 &self,
3853 src: DeviceLocation,
3854 dst: DeviceLocation,
3855 bytes: u64,
3856 ) -> u64 {
3857 if src == dst {
3858 return 0;
3859 }
3860 self.latency_ns
3861 .saturating_add(bytes.saturating_mul(self.ns_per_byte))
3862 }
3863 }
3864
3865 fn cost_50(
3866 _: &[Shape],
3867 _: &[DType],
3868 _: &OpParams,
3869 _: &BackendCapabilities,
3870 ) -> crate::fused::CostEstimate {
3871 crate::fused::CostEstimate {
3872 flops: 50,
3873 bytes_moved: 0,
3874 kernel_overhead_ns: 0,
3875 }
3876 }
3877 fn cost_100(
3878 _: &[Shape],
3879 _: &[DType],
3880 _: &OpParams,
3881 _: &BackendCapabilities,
3882 ) -> crate::fused::CostEstimate {
3883 crate::fused::CostEstimate {
3884 flops: 100,
3885 bytes_moved: 0,
3886 kernel_overhead_ns: 0,
3887 }
3888 }
3889 fn cost_300(
3890 _: &[Shape],
3891 _: &[DType],
3892 _: &OpParams,
3893 _: &BackendCapabilities,
3894 ) -> crate::fused::CostEstimate {
3895 crate::fused::CostEstimate {
3896 flops: 300,
3897 bytes_moved: 0,
3898 kernel_overhead_ns: 0,
3899 }
3900 }
3901 fn cost_800(
3902 _: &[Shape],
3903 _: &[DType],
3904 _: &OpParams,
3905 _: &BackendCapabilities,
3906 ) -> crate::fused::CostEstimate {
3907 crate::fused::CostEstimate {
3908 flops: 800,
3909 bytes_moved: 0,
3910 kernel_overhead_ns: 0,
3911 }
3912 }
3913 fn cost_5000(
3914 _: &[Shape],
3915 _: &[DType],
3916 _: &OpParams,
3917 _: &BackendCapabilities,
3918 ) -> crate::fused::CostEstimate {
3919 crate::fused::CostEstimate {
3920 flops: 5000,
3921 bytes_moved: 0,
3922 kernel_overhead_ns: 0,
3923 }
3924 }
3925 fn cost_100_000(
3926 _: &[Shape],
3927 _: &[DType],
3928 _: &OpParams,
3929 _: &BackendCapabilities,
3930 ) -> crate::fused::CostEstimate {
3931 crate::fused::CostEstimate {
3932 flops: 100_000,
3933 bytes_moved: 0,
3934 kernel_overhead_ns: 0,
3935 }
3936 }
3937
3938 fn register_unary_f32(
3940 table: &mut KernelBindingTable,
3941 op: OpKind,
3942 backend: BackendId,
3943 kernel: crate::kernel::KernelRef,
3944 cost: crate::kernel::CostFn,
3945 ) {
3946 table.register_full(
3947 op,
3948 &[DType::F32, DType::F32],
3949 backend,
3950 kernel,
3951 KernelCaps::empty(),
3952 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3953 cost,
3954 );
3955 }
3956
3957 fn push_f32(g: &mut Graph, op: Op, inputs: Vec<NodeId>, dims: &[usize]) -> NodeId {
3958 g.push(Node {
3959 op,
3960 inputs,
3961 shape: Shape::from_dims(dims),
3962 dtype: DType::F32,
3963 })
3964 }
3965
3966 #[test]
3981 fn dp_mid_sequence_gpu_segment_beats_all_cpu_and_all_gpu() {
3982 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3983 let mut table = KernelBindingTable::new();
3984 register_unary_f32(
3985 &mut table,
3986 OpKind::SqrElementwise,
3987 BackendId::Cpu,
3988 noop_kernel,
3989 cost_100,
3990 );
3991 register_unary_f32(
3992 &mut table,
3993 OpKind::SqrElementwise,
3994 BackendId::Cuda,
3995 noop_kernel_b,
3996 cost_5000,
3997 );
3998 register_unary_f32(
3999 &mut table,
4000 OpKind::NegElementwise,
4001 BackendId::Cpu,
4002 noop_kernel,
4003 cost_800,
4004 );
4005 register_unary_f32(
4006 &mut table,
4007 OpKind::NegElementwise,
4008 BackendId::Cuda,
4009 noop_kernel_b,
4010 cost_100,
4011 );
4012
4013 let mut g = Graph::new();
4014 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4015 let n1 = push_f32(&mut g, Op::Sqr, vec![c], &[4]);
4016 let n2 = push_f32(&mut g, Op::Neg, vec![n1], &[4]);
4017 let n3 = push_f32(&mut g, Op::Neg, vec![n2], &[4]);
4018 let n4 = push_f32(&mut g, Op::Neg, vec![n3], &[4]);
4019 let n5 = push_f32(&mut g, Op::Sqr, vec![n4], &[4]);
4020 let order = topo_order(&g, n5);
4021
4022 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4023 if dev == DeviceLocation::Cpu {
4024 vec![BackendId::Cpu]
4025 } else {
4026 vec![BackendId::Cuda]
4027 }
4028 };
4029 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4030 if dev == DeviceLocation::Cpu {
4031 vec![(BackendId::Cuda, cuda0)]
4032 } else {
4033 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4034 }
4035 };
4036 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4037 (id == c).then_some(DeviceLocation::Cpu)
4038 };
4039 let est = FlatEstimator { latency_ns: 1_000 };
4040 let cpu_caps_val = cpu_caps();
4041 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4042 let opts = PlanOptions::new()
4043 .with_pinned_device(DeviceLocation::Cpu)
4044 .with_placements_for_device(&placements_fn)
4045 .with_fallback_placements_for(&fallback_fn)
4046 .with_capabilities_for(&caps_fn)
4047 .with_transfer_estimator(&est)
4048 .with_input_residency(&residency_fn);
4049 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4050
4051 let dev_of = |id: NodeId| plan.alternatives(id).unwrap().winner().unwrap().device;
4052 assert_eq!(
4053 dev_of(n1),
4054 DeviceLocation::Cpu,
4055 "GPU-hostile entry stays CPU"
4056 );
4057 assert_eq!(dev_of(n2), cuda0, "segment start migrates");
4058 assert_eq!(dev_of(n3), cuda0, "segment interior stays GPU");
4059 assert_eq!(dev_of(n4), cuda0, "segment end stays GPU");
4060 assert_eq!(dev_of(n5), DeviceLocation::Cpu, "GPU-hostile exit returns");
4061
4062 let inbound = |id: NodeId| {
4066 plan.alternatives(id)
4067 .unwrap()
4068 .winner()
4069 .unwrap()
4070 .inbound_transfer_ns
4071 };
4072 assert_eq!(
4073 inbound(n2),
4074 1_000,
4075 "entry crossing priced on the first GPU op"
4076 );
4077 assert_eq!(inbound(n3), 0);
4078 assert_eq!(inbound(n4), 0);
4079 assert_eq!(inbound(n5), 1_000, "exit crossing priced on the return op");
4080
4081 for id in [n1, n2, n3, n4, n5] {
4084 let d = dev_of(id);
4085 assert!(
4086 plan.alternatives(id)
4087 .unwrap()
4088 .alternatives()
4089 .iter()
4090 .all(|c| c.device == d),
4091 "set pruned to the DP-committed device",
4092 );
4093 }
4094 }
4095
4096 #[test]
4112 fn dp_fused_op_loses_when_stranding_exceeds_local_win() {
4113 use fuel_graph::registry::{FusedOpParams, FusedOps};
4114
4115 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4116 let mut table = KernelBindingTable::new();
4117 register_unary_f32(
4118 &mut table,
4119 OpKind::NegElementwise,
4120 BackendId::Cpu,
4121 noop_kernel,
4122 cost_100_000,
4123 );
4124 register_unary_f32(
4125 &mut table,
4126 OpKind::NegElementwise,
4127 BackendId::Cuda,
4128 noop_kernel_b,
4129 cost_100,
4130 );
4131 register_unary_f32(
4132 &mut table,
4133 OpKind::SoftmaxLastDim,
4134 BackendId::Cpu,
4135 noop_kernel,
4136 cost_300,
4137 );
4138 register_unary_f32(
4139 &mut table,
4140 OpKind::SoftmaxLastDim,
4141 BackendId::Cuda,
4142 noop_kernel_b,
4143 cost_100,
4144 );
4145 register_unary_f32(
4147 &mut table,
4148 OpKind::SqrElementwise,
4149 BackendId::Cpu,
4150 noop_kernel,
4151 cost_100,
4152 );
4153
4154 let mut g = Graph::new();
4155 let c = push_f32(&mut g, Op::Const, vec![], &[1]);
4156 let n1 = push_f32(&mut g, Op::Neg, vec![c], &[1]);
4157 let f = push_f32(
4158 &mut g,
4159 Op::Fused(FusedOps::SOFTMAX_LAST_DIM, FusedOpParams::SoftmaxLastDim),
4160 vec![n1],
4161 &[256],
4162 );
4163 let n2 = push_f32(&mut g, Op::Sqr, vec![f], &[256]);
4164 let order = topo_order(&g, n2);
4165
4166 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4167 if dev == DeviceLocation::Cpu {
4168 vec![BackendId::Cpu]
4169 } else {
4170 vec![BackendId::Cuda]
4171 }
4172 };
4173 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4174 if dev == DeviceLocation::Cpu {
4175 vec![(BackendId::Cuda, cuda0)]
4176 } else {
4177 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4178 }
4179 };
4180 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4181 (id == c).then_some(DeviceLocation::Cpu)
4182 };
4183 let est = BytesEstimator {
4184 latency_ns: 10,
4185 ns_per_byte: 1,
4186 };
4187 let cpu_caps_val = cpu_caps();
4188 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4189 let opts = PlanOptions::new()
4190 .with_pinned_device(DeviceLocation::Cpu)
4191 .with_placements_for_device(&placements_fn)
4192 .with_fallback_placements_for(&fallback_fn)
4193 .with_capabilities_for(&caps_fn)
4194 .with_transfer_estimator(&est)
4195 .with_input_residency(&residency_fn);
4196 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4197
4198 let dev_of = |id: NodeId| plan.alternatives(id).unwrap().winner().unwrap().device;
4199 assert_eq!(dev_of(n1), cuda0, "the huge-win producer migrates");
4200 assert_eq!(
4201 dev_of(f),
4202 DeviceLocation::Cpu,
4203 "the locally-faster fused op stays where its output is needed",
4204 );
4205 assert_eq!(dev_of(n2), DeviceLocation::Cpu);
4206 assert!(
4207 plan.alternatives(f)
4208 .unwrap()
4209 .alternatives()
4210 .iter()
4211 .all(|c| c.device == DeviceLocation::Cpu),
4212 "fused set pruned to the committed device",
4213 );
4214 }
4215
4216 #[test]
4224 fn dp_exit_pricing_keeps_final_op_on_realize_target() {
4225 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4226 let mut table = KernelBindingTable::new();
4227 register_unary_f32(
4228 &mut table,
4229 OpKind::NegElementwise,
4230 BackendId::Cpu,
4231 noop_kernel,
4232 cost_50,
4233 );
4234 register_unary_f32(
4235 &mut table,
4236 OpKind::NegElementwise,
4237 BackendId::Cuda,
4238 noop_kernel_b,
4239 cost_100,
4240 );
4241
4242 let mut g = Graph::new();
4243 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4244 let n = push_f32(&mut g, Op::Neg, vec![c], &[4]);
4245 let order = topo_order(&g, n);
4246
4247 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4248 if dev == DeviceLocation::Cpu {
4249 vec![BackendId::Cpu]
4250 } else {
4251 vec![BackendId::Cuda]
4252 }
4253 };
4254 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4255 if dev == DeviceLocation::Cpu {
4256 vec![(BackendId::Cuda, cuda0)]
4257 } else {
4258 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4259 }
4260 };
4261 let residency_fn =
4262 move |id: NodeId| -> Option<DeviceLocation> { (id == c).then_some(cuda0) };
4263 let est = FlatEstimator { latency_ns: 1_000 };
4264 let cpu_caps_val = cpu_caps();
4265 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4266 let opts = PlanOptions::new()
4267 .with_pinned_device(DeviceLocation::Cpu)
4268 .with_placements_for_device(&placements_fn)
4269 .with_fallback_placements_for(&fallback_fn)
4270 .with_capabilities_for(&caps_fn)
4271 .with_transfer_estimator(&est)
4272 .with_input_residency(&residency_fn);
4273 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4274 let w = plan.alternatives(n).unwrap().winner().unwrap();
4275 assert_eq!(
4276 w.device,
4277 DeviceLocation::Cpu,
4278 "exit pricing flips the locally-winning GPU placement",
4279 );
4280 assert_eq!(
4281 w.inbound_transfer_ns, 1_000,
4282 "the GPU-resident input's crossing is priced on the CPU winner",
4283 );
4284 }
4285
4286 #[test]
4289 fn dp_exit_pricing_does_not_pin_when_kernel_gap_dominates() {
4290 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4291 let mut table = KernelBindingTable::new();
4292 register_unary_f32(
4293 &mut table,
4294 OpKind::NegElementwise,
4295 BackendId::Cpu,
4296 noop_kernel,
4297 cost_10_000_000,
4298 );
4299 register_unary_f32(
4300 &mut table,
4301 OpKind::NegElementwise,
4302 BackendId::Cuda,
4303 noop_kernel_b,
4304 cost_100,
4305 );
4306
4307 let mut g = Graph::new();
4308 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4309 let n = push_f32(&mut g, Op::Neg, vec![c], &[4]);
4310 let order = topo_order(&g, n);
4311
4312 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4313 if dev == DeviceLocation::Cpu {
4314 vec![BackendId::Cpu]
4315 } else {
4316 vec![BackendId::Cuda]
4317 }
4318 };
4319 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4320 if dev == DeviceLocation::Cpu {
4321 vec![(BackendId::Cuda, cuda0)]
4322 } else {
4323 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4324 }
4325 };
4326 let residency_fn =
4327 move |id: NodeId| -> Option<DeviceLocation> { (id == c).then_some(cuda0) };
4328 let est = FlatEstimator { latency_ns: 1_000 };
4329 let cpu_caps_val = cpu_caps();
4330 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4331 let opts = PlanOptions::new()
4332 .with_pinned_device(DeviceLocation::Cpu)
4333 .with_placements_for_device(&placements_fn)
4334 .with_fallback_placements_for(&fallback_fn)
4335 .with_capabilities_for(&caps_fn)
4336 .with_transfer_estimator(&est)
4337 .with_input_residency(&residency_fn);
4338 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4339 assert_eq!(
4340 plan.alternatives(n).unwrap().winner().unwrap().device,
4341 cuda0
4342 );
4343 }
4344
4345 #[test]
4351 fn dp_single_device_plan_equals_greedy_plan() {
4352 let mut table = KernelBindingTable::new();
4353 register_add_f32(
4354 &mut table,
4355 BackendId::Cpu,
4356 noop_kernel,
4357 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4358 );
4359 register_add_f32(
4360 &mut table,
4361 BackendId::Cuda,
4362 noop_kernel_b,
4363 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4364 );
4365 let (g, add_id) = build_add_graph();
4366 let order = topo_order(&g, add_id);
4367 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4370 if dev == DeviceLocation::Cpu {
4371 vec![BackendId::Cpu, BackendId::Cuda]
4372 } else {
4373 vec![]
4374 }
4375 };
4376 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> { Vec::new() };
4377 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
4378 let cpu_caps_val = cpu_caps();
4379 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4380
4381 let base_opts = PlanOptions::new()
4382 .with_placements_for_device(&placements_fn)
4383 .with_capabilities_for(&caps_fn);
4384 let base = compile_plan(&g, &order, &table, &base_opts).expect("base");
4385
4386 let est = FlatEstimator {
4387 latency_ns: 1_000_000,
4388 };
4389 let wired_opts = PlanOptions::new()
4390 .with_placements_for_device(&placements_fn)
4391 .with_fallback_placements_for(&fallback_fn)
4392 .with_capabilities_for(&caps_fn)
4393 .with_transfer_estimator(&est)
4394 .with_input_residency(&residency_fn);
4395 let wired = compile_plan(&g, &order, &table, &wired_opts).expect("wired");
4396
4397 assert_eq!(base.alternatives.len(), wired.alternatives.len());
4398 let a = base.alternatives(add_id).unwrap();
4399 let b = wired.alternatives(add_id).unwrap();
4400 assert_eq!(a.len(), b.len(), "same candidate count");
4401 for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
4402 assert_eq!(ca.backend, cb.backend);
4403 assert_eq!(ca.device, cb.device);
4404 assert_eq!(ca.kernel as usize, cb.kernel as usize, "same kernel ref");
4405 assert_eq!(ca.static_cost, cb.static_cost, "same Layer-1 cost");
4406 assert_eq!(cb.inbound_transfer_ns, 0, "no transfer term fires");
4407 }
4408 assert_eq!(a.context(), b.context(), "same decision context");
4409 }
4410
4411 fn run_diamond_regime(latency_ns: u64, expect: DeviceLocation) {
4415 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4416 let mut table = KernelBindingTable::new();
4417 for op in [
4418 OpKind::NegElementwise,
4419 OpKind::SqrElementwise,
4420 OpKind::ReluElementwise,
4421 ] {
4422 register_unary_f32(&mut table, op, BackendId::Cpu, noop_kernel, cost_100);
4423 register_unary_f32(&mut table, op, BackendId::Cuda, noop_kernel_b, cost_10);
4424 }
4425 table.register_full(
4426 OpKind::AddElementwise,
4427 &[DType::F32, DType::F32, DType::F32],
4428 BackendId::Cpu,
4429 noop_kernel,
4430 KernelCaps::empty(),
4431 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4432 cost_100,
4433 );
4434 table.register_full(
4435 OpKind::AddElementwise,
4436 &[DType::F32, DType::F32, DType::F32],
4437 BackendId::Cuda,
4438 noop_kernel_b,
4439 KernelCaps::empty(),
4440 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4441 cost_10,
4442 );
4443
4444 let mut g = Graph::new();
4445 let c0 = push_f32(&mut g, Op::Const, vec![], &[4]);
4446 let a = push_f32(&mut g, Op::Neg, vec![c0], &[4]);
4447 let b = push_f32(&mut g, Op::Sqr, vec![a], &[4]);
4448 let c2 = push_f32(&mut g, Op::Relu, vec![a], &[4]);
4449 let d = push_f32(&mut g, Op::Add, vec![b, c2], &[4]);
4450 let order = topo_order(&g, d);
4451
4452 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4453 if dev == DeviceLocation::Cpu {
4454 vec![BackendId::Cpu]
4455 } else {
4456 vec![BackendId::Cuda]
4457 }
4458 };
4459 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4460 if dev == DeviceLocation::Cpu {
4461 vec![(BackendId::Cuda, cuda0)]
4462 } else {
4463 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4464 }
4465 };
4466 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4467 (id == c0).then_some(DeviceLocation::Cpu)
4468 };
4469 let est = FlatEstimator { latency_ns };
4470 let cpu_caps_val = cpu_caps();
4471 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4472 let opts = PlanOptions::new()
4473 .with_pinned_device(DeviceLocation::Cpu)
4474 .with_placements_for_device(&placements_fn)
4475 .with_fallback_placements_for(&fallback_fn)
4476 .with_capabilities_for(&caps_fn)
4477 .with_transfer_estimator(&est)
4478 .with_input_residency(&residency_fn);
4479 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4480 for id in [a, b, c2, d] {
4481 assert_eq!(
4482 plan.alternatives(id).unwrap().winner().unwrap().device,
4483 expect,
4484 "diamond join must commit a consistent placement",
4485 );
4486 }
4487 }
4488
4489 #[test]
4494 fn dp_diamond_join_merges_consistently() {
4495 run_diamond_regime(1_000_000, DeviceLocation::Cpu);
4497 run_diamond_regime(0, DeviceLocation::Cuda { gpu_id: 0 });
4499 }
4500
4501 #[test]
4507 fn dp_thousand_node_chain_plans_within_sanity_bound() {
4508 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4509 let mut table = KernelBindingTable::new();
4510 register_unary_f32(
4513 &mut table,
4514 OpKind::NegElementwise,
4515 BackendId::Cpu,
4516 noop_kernel,
4517 cost_100,
4518 );
4519 register_unary_f32(
4520 &mut table,
4521 OpKind::NegElementwise,
4522 BackendId::Cuda,
4523 noop_kernel_b,
4524 cost_100,
4525 );
4526
4527 let mut g = Graph::new();
4528 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4529 let mut prev = c;
4530 let mut nodes = Vec::with_capacity(1000);
4531 for _ in 0..1000 {
4532 let n = push_f32(&mut g, Op::Neg, vec![prev], &[4]);
4533 nodes.push(n);
4534 prev = n;
4535 }
4536 let order = topo_order(&g, prev);
4537
4538 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4539 if dev == DeviceLocation::Cpu {
4540 vec![BackendId::Cpu]
4541 } else {
4542 vec![BackendId::Cuda]
4543 }
4544 };
4545 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4546 if dev == DeviceLocation::Cpu {
4547 vec![(BackendId::Cuda, cuda0)]
4548 } else {
4549 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4550 }
4551 };
4552 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4553 (id == c).then_some(DeviceLocation::Cpu)
4554 };
4555 let est = FlatEstimator { latency_ns: 10 };
4556 let cpu_caps_val = cpu_caps();
4557 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4558 let opts = PlanOptions::new()
4559 .with_pinned_device(DeviceLocation::Cpu)
4560 .with_placements_for_device(&placements_fn)
4561 .with_fallback_placements_for(&fallback_fn)
4562 .with_capabilities_for(&caps_fn)
4563 .with_transfer_estimator(&est)
4564 .with_input_residency(&residency_fn);
4565
4566 let start = std::time::Instant::now();
4567 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4568 let elapsed = start.elapsed();
4569 assert!(
4570 elapsed.as_secs() < 5,
4571 "1000-node DP plan took {elapsed:?} — pathological scaling",
4572 );
4573
4574 assert_eq!(plan.alternatives.len(), 1000);
4575 for &n in &nodes {
4576 assert_eq!(
4577 plan.alternatives(n).unwrap().winner().unwrap().device,
4578 DeviceLocation::Cpu,
4579 "equal-cost ties break toward the decision device end-to-end",
4580 );
4581 }
4582 }
4583
4584 #[test]
4588 fn dp_chain_connects_through_view_passthroughs() {
4589 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4590 let mut table = KernelBindingTable::new();
4591 register_unary_f32(
4595 &mut table,
4596 OpKind::NegElementwise,
4597 BackendId::Cpu,
4598 noop_kernel,
4599 cost_800,
4600 );
4601 register_unary_f32(
4602 &mut table,
4603 OpKind::NegElementwise,
4604 BackendId::Cuda,
4605 noop_kernel_b,
4606 cost_100,
4607 );
4608
4609 let mut g = Graph::new();
4610 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4611 let n1 = push_f32(&mut g, Op::Neg, vec![c], &[4]);
4612 let r = push_f32(
4613 &mut g,
4614 Op::Reshape(Shape::from_dims(&[2, 2])),
4615 vec![n1],
4616 &[2, 2],
4617 );
4618 let n2 = push_f32(&mut g, Op::Neg, vec![r], &[2, 2]);
4619 let n3 = push_f32(&mut g, Op::Neg, vec![n2], &[2, 2]);
4620 let order = topo_order(&g, n3);
4621
4622 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4623 if dev == DeviceLocation::Cpu {
4624 vec![BackendId::Cpu]
4625 } else {
4626 vec![BackendId::Cuda]
4627 }
4628 };
4629 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4630 if dev == DeviceLocation::Cpu {
4631 vec![(BackendId::Cuda, cuda0)]
4632 } else {
4633 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4634 }
4635 };
4636 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4637 (id == c).then_some(DeviceLocation::Cpu)
4638 };
4639 let est = FlatEstimator { latency_ns: 1_000 };
4640 let cpu_caps_val = cpu_caps();
4641 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4642 let opts = PlanOptions::new()
4643 .with_pinned_device(DeviceLocation::Cpu)
4644 .with_placements_for_device(&placements_fn)
4645 .with_fallback_placements_for(&fallback_fn)
4646 .with_capabilities_for(&caps_fn)
4647 .with_transfer_estimator(&est)
4648 .with_input_residency(&residency_fn);
4649 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4650
4651 for id in [n1, n2, n3] {
4655 assert_eq!(
4656 plan.alternatives(id).unwrap().winner().unwrap().device,
4657 cuda0,
4658 "the chain must not break at the Reshape pass-through",
4659 );
4660 }
4661 assert!(
4662 plan.alternatives(r).is_none(),
4663 "Reshape carries no plan entry"
4664 );
4665 }
4666
4667 #[cfg(feature = "telemetry")]
4672 mod telemetry_wiring {
4673 use super::*;
4674 use crate::telemetry::{
4675 Contiguity, FdxOperandDesc, HwStamp, StructureKeyProvider, StructureKeyToken,
4676 TelemetryConfig, TelemetryHooks, TelemetryMode, TelemetrySink,
4677 };
4678 use std::sync::Mutex;
4679
4680 struct StubProvider;
4684 impl StructureKeyProvider for StubProvider {
4685 fn structure_key(
4686 &self,
4687 op_class: &str,
4688 operands: &[FdxOperandDesc],
4689 _arch: &str,
4690 ) -> Option<StructureKeyToken> {
4691 Some(StructureKeyToken(format!(
4692 "{op_class}:stub:n={}",
4693 operands.len()
4694 )))
4695 }
4696 }
4697
4698 fn cpu_hw() -> HwStamp {
4699 HwStamp {
4700 compute_capability: None,
4701 hardware_sku: "test-cpu".into(),
4702 driver_version: "n/a".into(),
4703 }
4704 }
4705
4706 fn generic_only_add_table() -> KernelBindingTable {
4711 let mut table = KernelBindingTable::new();
4712 table.register_full_with_source_generic(
4713 OpKind::AddElementwise,
4714 &[DType::F32, DType::F32, DType::F32],
4715 BackendId::Cpu,
4716 noop_kernel,
4717 KernelCaps::strided_input(),
4718 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4719 unknown_cost,
4720 "baracuda-generic-strided",
4721 true, 0, None, );
4725 table
4726 }
4727
4728 #[test]
4740 fn generic_only_cell_emits_one_aggregated_miss_through_compile_plan() {
4741 let table = generic_only_add_table();
4742 let (g, add_id) = build_add_graph();
4743 let order = topo_order(&g, add_id);
4744
4745 let sink = Mutex::new(TelemetrySink::new());
4746 let provider = StubProvider;
4747 let config = TelemetryConfig {
4748 mode: TelemetryMode::Coarse,
4749 out_path: None,
4750 };
4751 let hooks = TelemetryHooks {
4752 config: &config,
4753 sink: &sink,
4754 provider: &provider,
4755 hw: cpu_hw(),
4756 };
4757 let opts = PlanOptions::new()
4758 .without_cost_population()
4759 .with_telemetry(&hooks);
4760 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4761
4762 let sink = sink.into_inner().expect("sink lock");
4763 assert_eq!(
4764 sink.miss_cell_count(),
4765 1,
4766 "a generic-only cell must emit exactly one aggregated miss cell",
4767 );
4768 let recs = sink.miss_records();
4769 assert_eq!(recs.len(), 1);
4770 assert_eq!(
4774 recs[0].wanted,
4775 StructureKeyToken("AddElementwise:stub:n=3".into()),
4776 "the wanted token must reflect the live op_class + operands",
4777 );
4778 assert_eq!(recs[0].fallback.kernel_source, "baracuda-generic-strided");
4779 assert_eq!(recs[0].fallback.op, OpKind::AddElementwise);
4780 assert_eq!(recs[0].fallback.backend, BackendId::Cpu);
4781 assert_eq!(
4782 recs[0].fallback.dtypes,
4783 vec![DType::F32, DType::F32, DType::F32],
4784 );
4785 assert_eq!(recs[0].count, 1);
4786 assert_eq!(recs[0].hw, cpu_hw());
4787 }
4788
4789 #[test]
4795 fn telemetry_off_emits_nothing_and_does_not_change_the_plan() {
4796 let table = generic_only_add_table();
4797 let (g, add_id) = build_add_graph();
4798 let order = topo_order(&g, add_id);
4799
4800 let sink = Mutex::new(TelemetrySink::new());
4801 let provider = StubProvider;
4802 let config = TelemetryConfig::default(); let hooks = TelemetryHooks {
4804 config: &config,
4805 sink: &sink,
4806 provider: &provider,
4807 hw: cpu_hw(),
4808 };
4809 let opts = PlanOptions::new()
4810 .without_cost_population()
4811 .with_telemetry(&hooks);
4812 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4813
4814 assert!(
4815 sink.into_inner().expect("sink lock").is_empty(),
4816 "Off mode must emit nothing",
4817 );
4818 let alts = plan.alternatives(add_id).expect("Add alternatives present");
4820 assert_eq!(alts.len(), 1);
4821 assert_eq!(alts.winner().unwrap().backend, BackendId::Cpu);
4822 }
4823
4824 #[test]
4829 fn specialized_winner_emits_no_miss() {
4830 let mut table = KernelBindingTable::new();
4831 register_add_f32(
4833 &mut table,
4834 BackendId::Cpu,
4835 noop_kernel,
4836 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4837 );
4838 let (g, add_id) = build_add_graph();
4839 let order = topo_order(&g, add_id);
4840
4841 let sink = Mutex::new(TelemetrySink::new());
4842 let provider = StubProvider;
4843 let config = TelemetryConfig {
4844 mode: TelemetryMode::Coarse,
4845 out_path: None,
4846 };
4847 let hooks = TelemetryHooks {
4848 config: &config,
4849 sink: &sink,
4850 provider: &provider,
4851 hw: cpu_hw(),
4852 };
4853 let opts = PlanOptions::new()
4854 .without_cost_population()
4855 .with_telemetry(&hooks);
4856 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4857
4858 let sink = sink.into_inner().expect("sink lock");
4859 assert!(
4860 sink.miss_records().is_empty(),
4861 "a specialized (is_generic=false) winner must emit no miss",
4862 );
4863 assert_eq!(
4867 sink.dispatch_cell_count(),
4868 1,
4869 "a specialized winner still emits its dispatch record",
4870 );
4871 let _ = add_id;
4872 }
4873
4874 fn two_sibling_add_table() -> KernelBindingTable {
4882 let mut table = KernelBindingTable::new();
4883 table.register_full_with_source(
4884 OpKind::AddElementwise,
4885 &[DType::F32, DType::F32, DType::F32],
4886 BackendId::Cpu,
4887 noop_kernel,
4888 KernelCaps::empty(),
4889 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4890 unknown_cost,
4891 "portable-cpu",
4892 );
4893 table.register_full_with_source(
4894 OpKind::AddElementwise,
4895 &[DType::F32, DType::F32, DType::F32],
4896 BackendId::Cpu,
4897 noop_kernel_b,
4898 KernelCaps::empty(),
4899 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4900 unknown_cost,
4901 "aocl",
4902 );
4903 table
4904 }
4905
4906 #[test]
4918 fn detailed_dispatch_record_emitted_with_per_candidate_judge_latency() {
4919 use crate::ranker::HashMapJudge;
4920 use fuel_ir::dispatch::SizeClass;
4921
4922 let table = two_sibling_add_table();
4923 let (g, add_id) = build_add_graph();
4924 let order = topo_order(&g, add_id);
4925
4926 let sc = SizeClass::from_elem_count(3);
4930 let mut judge = HashMapJudge::new();
4931 judge.insert(
4932 OpKind::AddElementwise,
4933 DType::F32,
4934 sc,
4935 BackendId::Cpu,
4936 "portable-cpu",
4937 41_230,
4938 0,
4939 );
4940
4941 let sink = Mutex::new(TelemetrySink::new());
4942 let provider = StubProvider;
4943 let config = TelemetryConfig {
4944 mode: TelemetryMode::Detailed,
4945 out_path: None,
4946 };
4947 let hooks = TelemetryHooks {
4948 config: &config,
4949 sink: &sink,
4950 provider: &provider,
4951 hw: cpu_hw(),
4952 };
4953 let opts = PlanOptions::new()
4954 .without_cost_population()
4955 .with_telemetry(&hooks)
4956 .with_judge(&judge);
4957 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4958
4959 let sink = sink.into_inner().expect("sink lock");
4960 assert_eq!(
4961 sink.dispatch_cell_count(),
4962 1,
4963 "one planned cell ⇒ exactly one aggregated dispatch record",
4964 );
4965 assert_eq!(
4966 sink.miss_cell_count(),
4967 0,
4968 "specialized winners emit no miss"
4969 );
4970 let recs = sink.dispatch_records();
4971 assert_eq!(recs.len(), 1);
4972 let rec = &recs[0];
4973 assert_eq!(rec.chosen.kernel_source, "portable-cpu");
4975 assert_eq!(rec.chosen.op, OpKind::AddElementwise);
4976 assert_eq!(rec.chosen.backend, BackendId::Cpu);
4977 assert_eq!(rec.chosen.dtypes, vec![DType::F32, DType::F32, DType::F32]);
4978 assert_eq!(
4979 rec.chosen.kernel_revision_hash, 0,
4980 "hand-written ⇒ untracked"
4981 );
4982 assert_eq!(rec.count, 1);
4983 assert_eq!(rec.hw, cpu_hw());
4984 assert_eq!(
4987 rec.structure_key,
4988 Some(StructureKeyToken("AddElementwise:stub:n=3".into())),
4989 );
4990 assert_eq!(rec.candidates.len(), 2, "both admitted alternatives appear");
4993 let by_src = |src: &str| {
4994 rec.candidates
4995 .iter()
4996 .find(|c| c.impl_id.kernel_source == src)
4997 .unwrap_or_else(|| panic!("candidate {src} present"))
4998 };
4999 assert_eq!(
5000 by_src("portable-cpu").latency_ns,
5001 Some(41_230),
5002 "the measured winner carries its own ns",
5003 );
5004 assert_eq!(
5005 by_src("aocl").latency_ns,
5006 None,
5007 "the unmeasured sibling is None, never a fabricated 0",
5008 );
5009 }
5010
5011 #[test]
5015 fn coarse_dispatch_record_has_no_candidates() {
5016 let table = two_sibling_add_table();
5017 let (g, add_id) = build_add_graph();
5018 let order = topo_order(&g, add_id);
5019
5020 let sink = Mutex::new(TelemetrySink::new());
5021 let provider = StubProvider;
5022 let config = TelemetryConfig {
5023 mode: TelemetryMode::Coarse,
5024 out_path: None,
5025 };
5026 let hooks = TelemetryHooks {
5027 config: &config,
5028 sink: &sink,
5029 provider: &provider,
5030 hw: cpu_hw(),
5031 };
5032 let opts = PlanOptions::new()
5033 .without_cost_population()
5034 .with_telemetry(&hooks);
5035 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
5036
5037 let sink = sink.into_inner().expect("sink lock");
5038 assert_eq!(
5039 sink.dispatch_cell_count(),
5040 1,
5041 "Coarse still emits the chosen signal"
5042 );
5043 let recs = sink.dispatch_records();
5044 assert!(
5045 recs[0].candidates.is_empty(),
5046 "Coarse omits candidates (no Judge reads)"
5047 );
5048 assert_eq!(recs[0].chosen.kernel_source, "portable-cpu");
5049 assert_eq!(recs[0].count, 1);
5050 }
5051
5052 #[test]
5055 fn telemetry_off_emits_no_dispatch_record() {
5056 let table = two_sibling_add_table();
5057 let (g, add_id) = build_add_graph();
5058 let order = topo_order(&g, add_id);
5059
5060 let sink = Mutex::new(TelemetrySink::new());
5061 let provider = StubProvider;
5062 let config = TelemetryConfig::default(); let hooks = TelemetryHooks {
5064 config: &config,
5065 sink: &sink,
5066 provider: &provider,
5067 hw: cpu_hw(),
5068 };
5069 let opts = PlanOptions::new()
5070 .without_cost_population()
5071 .with_telemetry(&hooks);
5072 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
5073
5074 assert!(
5075 sink.into_inner().expect("sink lock").is_empty(),
5076 "Off emits neither dispatch nor miss",
5077 );
5078 let _ = add_id;
5079 }
5080
5081 struct RecordingProvider {
5090 seen: Mutex<Vec<FdxOperandDesc>>,
5091 }
5092 impl StructureKeyProvider for RecordingProvider {
5093 fn structure_key(
5094 &self,
5095 op_class: &str,
5096 operands: &[FdxOperandDesc],
5097 _arch: &str,
5098 ) -> Option<StructureKeyToken> {
5099 *self.seen.lock().expect("record lock") = operands.to_vec();
5100 Some(StructureKeyToken(format!(
5101 "{op_class}:n={}",
5102 operands.len()
5103 )))
5104 }
5105 }
5106
5107 #[test]
5117 fn structure_key_operand_slice_folds_in_the_output() {
5118 let table = generic_only_add_table();
5119 let (g, add_id) = build_add_graph();
5120 let order = topo_order(&g, add_id);
5121
5122 let sink = Mutex::new(TelemetrySink::new());
5123 let provider = RecordingProvider {
5124 seen: Mutex::new(Vec::new()),
5125 };
5126 let config = TelemetryConfig {
5127 mode: TelemetryMode::Coarse,
5128 out_path: None,
5129 };
5130 let hooks = TelemetryHooks {
5131 config: &config,
5132 sink: &sink,
5133 provider: &provider,
5134 hw: cpu_hw(),
5135 };
5136 let opts = PlanOptions::new()
5137 .without_cost_population()
5138 .with_telemetry(&hooks);
5139 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
5140
5141 let seen = provider.seen.into_inner().expect("record lock");
5142 assert_eq!(
5144 seen.len(),
5145 3,
5146 "operand slice must be node inputs (2) then the output (1)",
5147 );
5148 let out = seen.last().expect("output operand present");
5149 assert_eq!(
5151 out.dtype,
5152 DType::F32,
5153 "output operand carries the node dtype"
5154 );
5155 assert_eq!(
5156 out.shape,
5157 vec![3i64],
5158 "output operand carries the node shape"
5159 );
5160 assert_eq!(
5161 out.contiguity,
5162 Contiguity::Contiguous,
5163 "the Add output is contiguous",
5164 );
5165 let _ = add_id;
5166 }
5167 }
5168}