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 off_device: HashMap<NodeId, AlternativeSet>,
67 pub generation: u64,
78}
79
80impl ExecutionPlan {
81 pub fn empty() -> Self {
83 Self {
84 order: Vec::new(),
85 alternatives: HashMap::new(),
86 off_device: HashMap::new(),
87 generation: 0,
88 }
89 }
90
91 pub fn alternatives(&self, node: NodeId) -> Option<&AlternativeSet> {
94 self.alternatives.get(&node)
95 }
96
97 pub fn alternatives_mut(&mut self, node: NodeId) -> Option<&mut AlternativeSet> {
101 self.alternatives.get_mut(&node)
102 }
103
104 pub fn off_device_alternatives(&self, node: NodeId) -> Option<&AlternativeSet> {
107 self.off_device.get(&node)
108 }
109}
110
111pub fn default_device_for(backend: BackendId) -> DeviceLocation {
116 backend.default_location()
117}
118
119pub(crate) fn decision_device_for(
129 graph: &Graph,
130 options: &PlanOptions<'_>,
131 id: NodeId,
132) -> Option<DeviceLocation> {
133 graph
134 .placement(id)
135 .or(options.pinned_device)
136 .or_else(|| graph.target_backend(id).map(default_device_for))
137}
138
139pub(crate) fn candidate_backends_for(
159 graph: &Graph,
160 options: &PlanOptions<'_>,
161 id: NodeId,
162 node: &fuel_graph::Node,
163) -> Vec<BackendId> {
164 let Some(target_device) = decision_device_for(graph, options, id) else {
165 return Vec::new();
166 };
167 let mut backends: Vec<BackendId> = match options.placements_for_device {
168 Some(f) => f(target_device),
169 None => vec![
170 graph
171 .target_backend(id)
172 .unwrap_or_else(|| backend_for_device(target_device)),
173 ],
174 };
175 if node.op.destructive_input().is_none()
180 && let Some(fallback) = options.fallback_placements_for
181 {
182 backends.extend(fallback(target_device).into_iter().map(|(b, _)| b));
183 }
184 let mut unique: Vec<BackendId> = Vec::with_capacity(backends.len());
186 for b in backends {
187 if !unique.contains(&b) {
188 unique.push(b);
189 }
190 }
191 unique
192}
193
194pub fn backend_for_device(loc: DeviceLocation) -> BackendId {
199 loc.backend()
200}
201
202pub struct PlanOptions<'env> {
293 pub precision_requirement: PrecisionRequirement,
296 pub populate_costs: bool,
300 pub placements_for_device: Option<&'env (dyn Fn(DeviceLocation) -> Vec<BackendId> + 'env)>,
303 pub pinned_device: Option<DeviceLocation>,
306 pub fallback_placements_for:
309 Option<&'env (dyn Fn(DeviceLocation) -> Vec<(BackendId, DeviceLocation)> + 'env)>,
310 pub capabilities_for: Option<&'env CapabilitiesLookup<'env>>,
313 pub judge: Option<&'env dyn JudgeOracle>,
319 pub transfer_estimator: Option<&'env dyn TransferEstimator>,
340 pub require_transfer_pricing: bool,
357 pub input_residency: Option<&'env (dyn Fn(NodeId) -> Option<DeviceLocation> + 'env)>,
369 pub reuse_plan: Option<&'env ExecutionPlan>,
386 pub allow_cost_placement: bool,
405 pub device_budget_bytes: Option<usize>,
413 pub device_budget_source: Option<crate::device_budget::BudgetSource>,
417 #[cfg(feature = "telemetry")]
425 pub telemetry: Option<&'env crate::telemetry::TelemetryHooks<'env>>,
426}
427
428impl Default for PlanOptions<'_> {
429 fn default() -> Self {
430 Self {
431 precision_requirement: PrecisionRequirement::default(),
432 populate_costs: true,
433 placements_for_device: None,
434 pinned_device: None,
435 fallback_placements_for: None,
436 capabilities_for: None,
437 judge: None,
438 transfer_estimator: None,
439 require_transfer_pricing: false,
440 input_residency: None,
441 reuse_plan: None,
442 allow_cost_placement: true,
443 device_budget_bytes: None,
444 device_budget_source: None,
445 #[cfg(feature = "telemetry")]
446 telemetry: None,
447 }
448 }
449}
450
451impl<'env> PlanOptions<'env> {
452 pub fn new() -> Self {
454 Self::default()
455 }
456
457 pub fn with_device_budget_bytes(mut self, budget_bytes: usize) -> Self {
459 self.device_budget_bytes = Some(budget_bytes);
460 self
461 }
462
463 pub fn with_resolved_device_budget(
466 mut self,
467 budget: crate::device_budget::ResolvedBudget,
468 ) -> Self {
469 self.device_budget_bytes = Some(budget.bytes);
470 self.device_budget_source = Some(budget.source);
471 self
472 }
473
474 pub fn with_precision_requirement(mut self, req: PrecisionRequirement) -> Self {
476 self.precision_requirement = req;
477 self
478 }
479
480 pub fn without_cost_population(mut self) -> Self {
484 self.populate_costs = false;
485 self
486 }
487
488 pub fn with_placements_for_device(
491 mut self,
492 f: &'env (dyn Fn(DeviceLocation) -> Vec<BackendId> + 'env),
493 ) -> Self {
494 self.placements_for_device = Some(f);
495 self
496 }
497
498 pub fn with_pinned_device(mut self, device: DeviceLocation) -> Self {
503 self.pinned_device = Some(device);
504 self
505 }
506
507 pub fn without_cost_placement(mut self) -> Self {
512 self.allow_cost_placement = false;
513 self
514 }
515
516 pub fn require_transfer_pricing(mut self) -> Self {
524 self.require_transfer_pricing = true;
525 self
526 }
527
528 pub fn with_fallback_placements_for(
537 mut self,
538 f: &'env (dyn Fn(DeviceLocation) -> Vec<(BackendId, DeviceLocation)> + 'env),
539 ) -> Self {
540 self.fallback_placements_for = Some(f);
541 self
542 }
543
544 pub fn with_capabilities_for(mut self, f: &'env CapabilitiesLookup<'env>) -> Self {
547 self.capabilities_for = Some(f);
548 self
549 }
550
551 pub fn with_judge(mut self, judge: &'env dyn JudgeOracle) -> Self {
555 self.judge = Some(judge);
556 self
557 }
558
559 pub fn with_transfer_estimator(mut self, est: &'env dyn TransferEstimator) -> Self {
565 self.transfer_estimator = Some(est);
566 self
567 }
568
569 pub fn with_input_residency(
573 mut self,
574 f: &'env (dyn Fn(NodeId) -> Option<DeviceLocation> + 'env),
575 ) -> Self {
576 self.input_residency = Some(f);
577 self
578 }
579
580 pub fn with_reuse_plan(mut self, base: &'env ExecutionPlan) -> Self {
583 self.reuse_plan = Some(base);
584 self
585 }
586
587 #[cfg(feature = "telemetry")]
593 pub fn with_telemetry(mut self, hooks: &'env crate::telemetry::TelemetryHooks<'env>) -> Self {
594 self.telemetry = Some(hooks);
595 self
596 }
597}
598
599pub fn compile_plan(
682 graph: &Graph,
683 order: &[NodeId],
684 bindings_table: &KernelBindingTable,
685 options: &PlanOptions<'_>,
686) -> Result<ExecutionPlan> {
687 if options.require_transfer_pricing && options.transfer_estimator.is_none() {
695 return Err(Error::Msg(
696 "compile_plan: require_transfer_pricing is set but no transfer \
697 estimator is wired — placement would silently price transfers at \
698 zero (latency-greedy). Wire PlanOptions::with_transfer_estimator(..) \
699 or drop the pricing requirement."
700 .into(),
701 )
702 .bt());
703 }
704
705 let generation = crate::dispatch::topology_generation();
711 let mut alternatives_map = HashMap::with_capacity(order.len());
712 let mut off_device_map: HashMap<NodeId, AlternativeSet> = HashMap::new();
713
714 let mut residency: HashMap<NodeId, DeviceLocation> = HashMap::with_capacity(order.len());
718
719 let mut dp = PlacementDp::new();
722 let mut dp_drafts: HashMap<NodeId, NodeDraft> = HashMap::new();
723
724 for &id in order {
725 let node = graph.node(id);
726
727 if let Some(base) = options.reuse_plan
733 && let Some(set) = base.alternatives(id)
734 {
735 let resident = early_residency(graph, options, id, node)
736 .or_else(|| set.winner().map(|w| w.device));
737 if let Some(loc) = resident {
738 residency.insert(id, loc);
739 }
740 alternatives_map.insert(id, set.clone());
741 continue;
742 }
743
744 let early = early_residency(graph, options, id, node);
747
748 let mut dp_row_opened = false;
749 let winner_device = match build_node_draft(graph, id, node, bindings_table, options)? {
750 Some(draft) => {
751 let devices = distinct_devices(&draft.set);
752 let dp_estimator = options
753 .transfer_estimator
754 .filter(|_| draft.relaxed && early.is_none() && devices.len() >= 2);
755 if let Some(est) = dp_estimator {
756 open_dp_row(
760 &mut dp,
761 graph,
762 id,
763 node,
764 &draft.set,
765 &devices,
766 &residency,
767 est,
768 options.capabilities_for,
769 );
770 dp_drafts.insert(id, draft);
771 dp_row_opened = true;
772 None
773 } else {
774 if let Some(est) = options.transfer_estimator
781 && let [single] = devices.as_slice()
782 {
783 close_open_inputs(&mut dp, graph, node, *single, est, &mut residency);
784 }
785 let mut off = None;
786 let set = finalize_node_greedy(
787 graph,
788 node,
789 draft,
790 bindings_table,
791 options,
792 &residency,
793 &mut off,
794 )?;
795 if let Some(off) = off {
796 off_device_map.insert(id, off);
797 }
798 let dev = set.winner().map(|w| w.device);
799 if devices.len() > 1
803 && let (Some(est), Some(wd)) = (options.transfer_estimator, dev)
804 {
805 close_open_inputs(&mut dp, graph, node, wd, est, &mut residency);
806 }
807 alternatives_map.insert(id, set);
808 dev
809 }
810 }
811 None => {
812 if let fuel_graph::Op::Copy { target } | fuel_graph::Op::Move { target } = node.op
818 && let Some(est) = options.transfer_estimator
819 {
820 close_open_inputs(&mut dp, graph, node, target, est, &mut residency);
821 }
822 None
823 }
824 };
825
826 if dp_row_opened {
827 continue;
831 }
832
833 let resident = early
835 .or(winner_device)
836 .or_else(|| {
837 graph.target_backend(id).map(|b| {
842 options
843 .pinned_device
844 .unwrap_or_else(|| default_device_for(b))
845 })
846 })
847 .or_else(|| {
848 if is_passthrough(node) {
853 node.inputs.first().and_then(|i| residency.get(i)).copied()
854 } else {
855 None
856 }
857 });
858 if let Some(loc) = resident {
859 residency.insert(id, loc);
860 } else if is_passthrough(node) {
861 if let Some(&input) = node.inputs.first() {
867 let root = dp.resolve(input);
868 if let Some(dev) = dp.committed_device(root) {
869 residency.insert(id, dev);
870 } else {
871 dp.add_alias(id, root);
872 }
873 }
874 }
875 }
876
877 if !dp_drafts.is_empty() {
880 let Some(est) = options.transfer_estimator else {
881 return Err(Error::Msg(
884 "compile_plan: placement DP rows exist without a transfer \
885 estimator — internal invariant violated"
886 .into(),
887 )
888 .bt());
889 };
890 let commits = dp.finish(options.pinned_device, |nid| node_bytes(graph, nid), est);
891 for (n, d) in commits {
892 residency.insert(n, d);
893 }
894 for &id in order {
898 if residency.contains_key(&id) {
899 continue;
900 }
901 let node = graph.node(id);
902 if is_passthrough(node)
903 && let Some(&loc) = node.inputs.first().and_then(|i| residency.get(i))
904 {
905 residency.insert(id, loc);
906 }
907 }
908 for &id in order {
913 let Some(draft) = dp_drafts.remove(&id) else {
914 continue;
915 };
916 let chosen = dp.committed_device(id).ok_or_else(|| {
917 Error::Msg(format!(
918 "compile_plan: placement DP left node {:?} uncommitted — \
919 internal invariant violated",
920 id,
921 ))
922 .bt()
923 })?;
924 let node = graph.node(id);
925 let mut set = draft.set;
926 let inputs = priced_inputs_for(graph, node, &residency);
927 apply_inbound_transfer_costs(&mut set, &inputs, est);
928 set.rank_by_composite_cost();
929 let keep: Vec<usize> = set
930 .alternatives()
931 .iter()
932 .enumerate()
933 .filter_map(|(i, c)| (c.device == chosen).then_some(i))
934 .collect();
935 if keep.len() < set.len() {
936 let off_keep: Vec<usize> = (0..set.len()).filter(|i| !keep.contains(i)).collect();
937 let mut off = set.clone();
938 off.retain_indices(&off_keep);
939 off.retain_per_device_frontier(KEEP_PER_DEVICE);
940 off_device_map.insert(id, off);
941 set.retain_indices(&keep);
942 }
943 set.retain_per_device_frontier(KEEP_PER_DEVICE);
949 if set.is_empty() {
950 return Err(missing_binding_error(
953 bindings_table,
954 draft.op_kind,
955 &draft.dtypes,
956 draft.diag_backend,
957 ));
958 }
959 alternatives_map.insert(id, set);
960 }
961 }
962
963 #[cfg(feature = "telemetry")]
968 emit_plan_telemetry(graph, &alternatives_map, bindings_table, options);
969
970 Ok(ExecutionPlan {
971 order: order.to_vec(),
972 alternatives: alternatives_map,
973 off_device: off_device_map,
974 generation,
975 })
976}
977
978#[cfg(feature = "telemetry")]
1003fn emit_plan_telemetry(
1004 graph: &Graph,
1005 alternatives: &HashMap<NodeId, AlternativeSet>,
1006 bindings_table: &KernelBindingTable,
1007 options: &PlanOptions<'_>,
1008) {
1009 use crate::telemetry::{
1010 DispatchRecord, FdxOperandDesc, ImplId, TELEMETRY_SCHEMA_VERSION, detect_miss_precomputed,
1011 };
1012
1013 let Some(hooks) = options.telemetry else {
1015 return;
1016 };
1017 if !hooks.config.is_enabled() {
1018 return;
1019 }
1020 let arch = hooks.arch_tag();
1021 let want_candidates = hooks.config.mode.wants_candidates();
1022
1023 for (&id, set) in alternatives {
1024 let Some(winner) = set.winner() else {
1025 continue;
1026 };
1027 let node = graph.node(id);
1028 let Some(op_kind) = op_to_op_kind(&node.op) else {
1029 continue;
1030 };
1031 let dtypes = build_lookup_dtypes(graph, node);
1032
1033 let winner_ptr = winner.kernel as *const () as usize;
1038 let winner_entry = bindings_table
1039 .lookup_alternatives(op_kind, &dtypes, winner.backend)
1040 .iter()
1041 .find(|e| e.kernel as *const () as usize == winner_ptr)
1042 .copied();
1043 let is_generic = winner_entry.is_some_and(|e| e.is_generic);
1044 let winner_revision = winner_entry.map_or(0, |e| e.kernel_revision_hash);
1045
1046 let mut operands: Vec<FdxOperandDesc> = node
1052 .inputs
1053 .iter()
1054 .map(|&input_id| {
1055 FdxOperandDesc::from_layout(&graph.layout(input_id), graph.node(input_id).dtype)
1056 })
1057 .collect();
1058 operands.push(FdxOperandDesc::from_layout(&graph.layout(id), node.dtype));
1059 let op_class = format!("{op_kind:?}");
1060
1061 if matches!(node.op, fuel_graph::Op::MatMul)
1067 && let [a, b, out] = operands.as_slice()
1068 && let Some(target) = arch.strip_prefix("sm_").map(|cc| format!("cuda:sm{cc}"))
1069 && let Ok(Some(token)) =
1070 crate::telemetry::contraction_facts::matmul_structure_key(a, b, out, &target)
1071 && let Ok(mut sink) = hooks.sink.lock()
1072 {
1073 sink.record_derived_contraction_key(token);
1074 }
1075
1076 let structure_key = hooks.provider.structure_key(&op_class, &operands, &arch);
1080
1081 let chosen = ImplId {
1083 backend: winner.backend,
1084 op: op_kind,
1085 dtypes: dtypes.to_vec(),
1086 kernel_source: winner.kernel_source.to_string(),
1087 kernel_revision_hash: winner_revision,
1088 };
1089
1090 let candidates = if want_candidates {
1093 build_candidates(set, op_kind, &dtypes, bindings_table, options.judge)
1094 } else {
1095 Vec::new()
1096 };
1097
1098 let dispatch = DispatchRecord {
1100 schema: TELEMETRY_SCHEMA_VERSION,
1101 structure_key,
1102 chosen: chosen.clone(),
1103 candidates,
1104 count: 1,
1105 hw: hooks.hw.clone(),
1106 };
1107 if let Ok(mut sink) = hooks.sink.lock() {
1108 sink.record_dispatch(dispatch);
1109 }
1110
1111 if let Some(miss) = detect_miss_precomputed(
1115 is_generic,
1116 chosen,
1117 &op_class,
1118 &operands,
1119 &arch,
1120 hooks.provider,
1121 hooks.hw.clone(),
1122 ) {
1123 if let Ok(mut sink) = hooks.sink.lock() {
1126 sink.record_miss(miss);
1127 }
1128 }
1129 }
1130}
1131
1132#[cfg(feature = "telemetry")]
1141fn build_candidates(
1142 set: &AlternativeSet,
1143 op_kind: OpKind,
1144 dtypes: &[DType],
1145 bindings_table: &KernelBindingTable,
1146 judge: Option<&dyn JudgeOracle>,
1147) -> Vec<crate::telemetry::Candidate> {
1148 use crate::telemetry::{Candidate as TeleCandidate, ImplId};
1149
1150 let ctx = set.context();
1153 set.alternatives()
1154 .iter()
1155 .map(|cand| {
1156 let ptr = cand.kernel as *const () as usize;
1157 let revision = bindings_table
1158 .lookup_alternatives(op_kind, dtypes, cand.backend)
1159 .iter()
1160 .find(|e| e.kernel as *const () as usize == ptr)
1161 .map_or(0, |e| e.kernel_revision_hash);
1162 let impl_id = ImplId {
1163 backend: cand.backend,
1164 op: op_kind,
1165 dtypes: dtypes.to_vec(),
1166 kernel_source: cand.kernel_source.to_string(),
1167 kernel_revision_hash: revision,
1168 };
1169 let latency_ns = match (judge, ctx) {
1170 (Some(j), Some(ctx)) => j.measured_latency_ns(
1171 ctx.op,
1172 ctx.principal_dtype,
1173 ctx.size_class,
1174 cand.backend,
1175 cand.kernel_source,
1176 revision,
1182 ),
1183 _ => None,
1184 };
1185 TeleCandidate {
1186 impl_id,
1187 latency_ns,
1188 }
1189 })
1190 .collect()
1191}
1192
1193pub fn node_needs_plan_entry(op: &fuel_graph::Op) -> bool {
1201 op_to_op_kind(op).is_some()
1202 && !matches!(
1203 op,
1204 fuel_graph::Op::Copy { .. } | fuel_graph::Op::Move { .. }
1205 )
1206}
1207
1208fn is_passthrough(node: &fuel_graph::Node) -> bool {
1212 node.op.is_view_op()
1213 || matches!(
1214 node.op,
1215 fuel_graph::Op::Reshape(_) | fuel_graph::Op::Contiguize
1216 )
1217}
1218
1219fn distinct_devices(set: &AlternativeSet) -> SmallVec<[DeviceLocation; 4]> {
1223 let mut out: SmallVec<[DeviceLocation; 4]> = SmallVec::new();
1224 for c in set.alternatives() {
1225 if !out.contains(&c.device) {
1226 out.push(c.device);
1227 }
1228 }
1229 out
1230}
1231
1232fn node_bytes(graph: &Graph, id: NodeId) -> u64 {
1236 let n = graph.node(id);
1237 (n.shape.elem_count() as u64).saturating_mul(n.dtype.size_in_bytes() as u64)
1238}
1239
1240fn open_dp_row(
1245 dp: &mut PlacementDp,
1246 graph: &Graph,
1247 id: NodeId,
1248 node: &fuel_graph::Node,
1249 set: &AlternativeSet,
1250 devices: &[DeviceLocation],
1251 residency: &HashMap<NodeId, DeviceLocation>,
1252 est: &dyn TransferEstimator,
1253 caps_for: Option<&CapabilitiesLookup<'_>>,
1254) {
1255 let rates_for = |backend: BackendId| -> (f64, f64) {
1264 caps_for
1265 .and_then(|f| f(backend))
1266 .map(|caps| {
1267 (
1268 caps.compute_throughput_flops_per_ns,
1269 caps.mem_bandwidth_bytes_per_ns,
1270 )
1271 })
1272 .unwrap_or_else(|| default_backend_rates(backend))
1273 };
1274 let device_costs: Vec<(DeviceLocation, u64)> = devices
1275 .iter()
1276 .map(|&d| {
1277 let min = set
1278 .alternatives()
1279 .iter()
1280 .filter(|c| c.device == d)
1281 .map(|c| {
1282 let (cr, bw) = rates_for(c.backend);
1283 composite_ns(&c.static_cost, cr, bw)
1284 })
1285 .min()
1286 .unwrap_or(u64::MAX);
1287 (d, min)
1288 })
1289 .collect();
1290
1291 let mut fixed: Vec<(DeviceLocation, u64)> = Vec::new();
1292 let mut chains: Vec<ChainInput> = Vec::new();
1293 for &input in &node.inputs {
1294 let bytes = node_bytes(graph, input);
1295 if let Some(&src) = residency.get(&input) {
1296 fixed.push((src, bytes));
1297 continue;
1298 }
1299 let root = dp.resolve(input);
1300 if dp.is_open(root) {
1301 match chains.iter_mut().find(|ci| ci.producer == root) {
1302 Some(ci) => ci.edge_bytes.push(bytes),
1303 None => chains.push(ChainInput {
1304 producer: root,
1305 edge_bytes: smallvec::smallvec![bytes],
1306 }),
1307 }
1308 } else if let Some(dev) = dp.committed_device(root) {
1309 fixed.push((dev, bytes));
1312 }
1313 }
1316 dp.push_row(id, &device_costs, &fixed, &chains, est);
1317}
1318
1319fn close_open_inputs(
1325 dp: &mut PlacementDp,
1326 graph: &Graph,
1327 node: &fuel_graph::Node,
1328 toward: DeviceLocation,
1329 est: &dyn TransferEstimator,
1330 residency: &mut HashMap<NodeId, DeviceLocation>,
1331) {
1332 for &input in &node.inputs {
1333 if residency.contains_key(&input) {
1334 continue;
1335 }
1336 let root = dp.resolve(input);
1337 if dp.is_open(root) {
1338 let commits = dp.close_toward(root, toward, &[node_bytes(graph, input)], est);
1339 for (n, d) in commits {
1340 residency.insert(n, d);
1341 }
1342 }
1343 if !residency.contains_key(&input)
1344 && let Some(d) = dp.committed_device(root)
1345 {
1346 residency.insert(input, d);
1347 }
1348 }
1349}
1350
1351fn early_residency(
1360 graph: &Graph,
1361 options: &PlanOptions<'_>,
1362 id: NodeId,
1363 node: &fuel_graph::Node,
1364) -> Option<DeviceLocation> {
1365 match node.op {
1366 fuel_graph::Op::Copy { target }
1367 | fuel_graph::Op::Move { target }
1368 | fuel_graph::Op::Alloc { target } => return Some(target),
1369 _ => {}
1370 }
1371 if let Some(loc) = graph.placement(id) {
1372 return Some(loc);
1373 }
1374 options.input_residency.and_then(|f| f(id))
1375}
1376
1377fn priced_inputs_for(
1383 graph: &Graph,
1384 node: &fuel_graph::Node,
1385 residency: &HashMap<NodeId, DeviceLocation>,
1386) -> Vec<(DeviceLocation, u64)> {
1387 node.inputs
1388 .iter()
1389 .filter_map(|&input_id| {
1390 let src = residency.get(&input_id).copied()?;
1391 let in_node = graph.node(input_id);
1392 let bytes = (in_node.shape.elem_count() as u64)
1393 .saturating_mul(in_node.dtype.size_in_bytes() as u64);
1394 Some((src, bytes))
1395 })
1396 .collect()
1397}
1398
1399struct NodeDraft {
1405 set: AlternativeSet,
1406 relaxed: bool,
1409 from_fallback: bool,
1412 costed: bool,
1416 op_kind: OpKind,
1417 dtypes: Vec<DType>,
1418 diag_backend: BackendId,
1419}
1420
1421fn build_node_draft(
1428 graph: &Graph,
1429 id: NodeId,
1430 node: &fuel_graph::Node,
1431 bindings_table: &KernelBindingTable,
1432 options: &PlanOptions<'_>,
1433) -> Result<Option<NodeDraft>> {
1434 if !node_needs_plan_entry(&node.op) {
1450 return Ok(None);
1451 }
1452 let Some(op_kind) = op_to_op_kind(&node.op) else {
1453 return Ok(None);
1455 };
1456
1457 let explicit_backend = graph.target_backend(id);
1461 let target_device = decision_device_for(graph, options, id).ok_or_else(|| {
1462 Error::Msg(format!(
1463 "compile_plan: node {:?} ({:?}) has no device context — \
1464 set PlanOptions::pinned_device, a graph placement, or \
1465 the node's target_backend",
1466 id, node.op,
1467 ))
1468 .bt()
1469 })?;
1470 let diag_backend = explicit_backend.unwrap_or_else(|| backend_for_device(target_device));
1474 let dtypes = build_lookup_dtypes(graph, node);
1475
1476 let placements: Vec<(BackendId, DeviceLocation)> = match options.placements_for_device {
1480 Some(f) => f(target_device)
1481 .into_iter()
1482 .map(|backend| (backend, target_device))
1483 .collect(),
1484 None => vec![(diag_backend, target_device)],
1485 };
1486
1487 let op_params = candidate_default_op_params(graph, node);
1488
1489 let pricing_active = options.transfer_estimator.is_some()
1507 && options.populate_costs
1508 && options.capabilities_for.is_some();
1509 let fallback_allowed =
1510 node.op.destructive_input().is_none() && options.fallback_placements_for.is_some();
1511 let relaxed = options.allow_cost_placement
1512 && pricing_active
1513 && fallback_allowed
1514 && graph.placement(id).is_none();
1515
1516 let mut set;
1517 let mut from_fallback = false;
1518 if relaxed {
1519 let mut merged = placements.clone();
1524 if let Some(fallback) = options.fallback_placements_for {
1525 merged.extend(fallback(target_device));
1526 }
1527 set = enumerate_candidates(op_kind, &dtypes, &merged, &op_params, bindings_table);
1528 } else {
1529 set = enumerate_candidates(op_kind, &dtypes, &placements, &op_params, bindings_table);
1530
1531 if set.is_empty()
1539 && fallback_allowed
1540 && let Some(fallback) = options.fallback_placements_for
1541 {
1542 let fb_placements = fallback(target_device);
1543 if !fb_placements.is_empty() {
1544 set = enumerate_candidates(
1545 op_kind,
1546 &dtypes,
1547 &fb_placements,
1548 &op_params,
1549 bindings_table,
1550 );
1551 from_fallback = !set.is_empty();
1552 }
1553 }
1554 }
1555
1556 if set.is_empty() {
1561 return Err(missing_binding_error(
1562 bindings_table,
1563 op_kind,
1564 &dtypes,
1565 diag_backend,
1566 ));
1567 }
1568
1569 let input_layouts: Vec<fuel_ir::Layout> = node
1571 .inputs
1572 .iter()
1573 .map(|&input_id| graph.layout(input_id))
1574 .collect();
1575 let ctx = FilterContext::new(op_kind, &dtypes, &input_layouts);
1576 let chain = default_chain(options.precision_requirement);
1577 if let Err(err) = apply_filter_chain(&mut set, &chain, &ctx) {
1578 if relaxed || from_fallback || !fallback_allowed {
1587 return Err(err);
1588 }
1589 let Some(fallback) = options.fallback_placements_for else {
1590 return Err(err);
1591 };
1592 let fb_placements = fallback(target_device);
1593 if fb_placements.is_empty() {
1594 return Err(err);
1595 }
1596 let mut fb_set =
1597 enumerate_candidates(op_kind, &dtypes, &fb_placements, &op_params, bindings_table);
1598 if fb_set.is_empty() {
1599 return Err(err);
1600 }
1601 apply_filter_chain(&mut fb_set, &chain, &ctx)?;
1604 set = fb_set;
1605 from_fallback = true;
1606 }
1607
1608 if let Some(&principal_dtype) = dtypes.first() {
1619 let input_shapes: Vec<Shape> = node
1620 .inputs
1621 .iter()
1622 .map(|&input_id| graph.node(input_id).shape.clone())
1623 .collect();
1624 let size_class = SizeClass::for_op(op_kind, &input_shapes);
1625 set.set_context(DecisionContext {
1626 op: op_kind,
1627 principal_dtype,
1628 size_class,
1629 });
1630 }
1631
1632 let costed = if options.populate_costs {
1636 if let Some(caps_for) = options.capabilities_for {
1637 let input_shapes: Vec<Shape> = node
1638 .inputs
1639 .iter()
1640 .map(|&input_id| graph.node(input_id).shape.clone())
1641 .collect();
1642 compute_static_costs(
1643 &mut set,
1644 op_kind,
1645 &dtypes,
1646 &input_shapes,
1647 bindings_table,
1648 caps_for,
1649 options.judge,
1650 );
1651 true
1652 } else {
1653 false
1654 }
1655 } else {
1656 false
1657 };
1658
1659 Ok(Some(NodeDraft {
1660 set,
1661 relaxed,
1662 from_fallback,
1663 costed,
1664 op_kind,
1665 dtypes,
1666 diag_backend,
1667 }))
1668}
1669
1670fn finalize_node_greedy(
1677 graph: &Graph,
1678 node: &fuel_graph::Node,
1679 draft: NodeDraft,
1680 bindings_table: &KernelBindingTable,
1681 options: &PlanOptions<'_>,
1682 residency: &HashMap<NodeId, DeviceLocation>,
1683 off_device_out: &mut Option<AlternativeSet>,
1684) -> Result<AlternativeSet> {
1685 let NodeDraft {
1686 mut set,
1687 relaxed,
1688 from_fallback,
1689 costed,
1690 op_kind,
1691 dtypes,
1692 diag_backend,
1693 } = draft;
1694
1695 if costed {
1696 if let Some(estimator) = options.transfer_estimator {
1702 let inputs = priced_inputs_for(graph, node, residency);
1703 apply_inbound_transfer_costs(&mut set, &inputs, estimator);
1704 }
1705 set.rank_by_composite_cost();
1706 }
1707
1708 if relaxed && let Some(winner_device) = set.winner().map(|c| c.device) {
1719 let keep: Vec<usize> = set
1720 .alternatives()
1721 .iter()
1722 .enumerate()
1723 .filter_map(|(i, c)| (c.device == winner_device).then_some(i))
1724 .collect();
1725 if keep.len() < set.len() {
1726 let off_keep: Vec<usize> = (0..set.len()).filter(|i| !keep.contains(i)).collect();
1728 let mut off = set.clone();
1729 off.retain_indices(&off_keep);
1730 off.retain_per_device_frontier(KEEP_PER_DEVICE);
1731 *off_device_out = Some(off);
1732 set.retain_indices(&keep);
1733 }
1734 }
1735
1736 set.retain_per_device_frontier(KEEP_PER_DEVICE);
1744
1745 if from_fallback && set.len() > 1 {
1752 set.retain_indices(&[0]);
1753 }
1754
1755 if set.is_empty() {
1762 return Err(missing_binding_error(
1763 bindings_table,
1764 op_kind,
1765 &dtypes,
1766 diag_backend,
1767 ));
1768 }
1769
1770 Ok(set)
1771}
1772
1773fn missing_binding_error(
1779 table: &KernelBindingTable,
1780 op: OpKind,
1781 dtypes: &[DType],
1782 backend: BackendId,
1783) -> Error {
1784 let _ = backend;
1789 let (available_backends, supported_combinations) = table.coverage_diagnostic();
1790 Error::NoBackendForOp {
1791 op,
1792 dtypes: dtypes.to_vec(),
1793 available_backends,
1794 supported_combinations,
1795 }
1796 .bt()
1797}
1798
1799fn candidate_default_op_params(
1807 _graph: &Graph,
1808 _node: &fuel_graph::Node,
1809) -> crate::kernel::OpParams {
1810 crate::kernel::OpParams::None
1811}
1812
1813#[cfg(test)]
1814mod tests {
1815 use super::*;
1816 use crate::fused::PrecisionGuarantee;
1817 use crate::kernel::{KernelCaps, OpParams, unknown_cost};
1818 use fuel_graph::{Node, Op, topo_order};
1819 use fuel_ir::backend::{BackendCapabilities, SubstrateClass, TransferPath};
1820 use fuel_ir::{DType, Layout, Result as FuelResult, Shape, StrideVec};
1821 use fuel_memory::Storage;
1822 use smallvec::smallvec;
1823 use std::collections::HashSet;
1824 use std::sync::{Arc, RwLock};
1825
1826 fn noop_kernel(
1827 _i: &[Arc<RwLock<Storage>>],
1828 _o: &mut [Arc<RwLock<Storage>>],
1829 _l: &[Layout],
1830 _p: &OpParams,
1831 ) -> FuelResult<()> {
1832 Ok(())
1833 }
1834
1835 fn noop_kernel_b(
1836 _i: &[Arc<RwLock<Storage>>],
1837 _o: &mut [Arc<RwLock<Storage>>],
1838 _l: &[Layout],
1839 _p: &OpParams,
1840 ) -> FuelResult<()> {
1841 Ok(())
1842 }
1843
1844 fn noop_kernel_c(
1845 _i: &[Arc<RwLock<Storage>>],
1846 _o: &mut [Arc<RwLock<Storage>>],
1847 _l: &[Layout],
1848 _p: &OpParams,
1849 ) -> FuelResult<()> {
1850 Ok(())
1851 }
1852
1853 fn register_add_f32(
1854 table: &mut KernelBindingTable,
1855 backend: BackendId,
1856 kernel: crate::kernel::KernelRef,
1857 precision: PrecisionGuarantee,
1858 ) {
1859 table.register_full(
1860 OpKind::AddElementwise,
1861 &[DType::F32, DType::F32, DType::F32],
1862 backend,
1863 kernel,
1864 KernelCaps::empty(),
1865 precision,
1866 unknown_cost,
1867 );
1868 }
1869
1870 fn build_add_graph() -> (Graph, NodeId) {
1871 let mut g = Graph::new();
1872 let lhs = g.push(Node {
1873 op: Op::Const,
1874 inputs: vec![],
1875 shape: Shape::from_dims(&[3]),
1876 dtype: DType::F32,
1877 });
1878 let rhs = g.push(Node {
1879 op: Op::Const,
1880 inputs: vec![],
1881 shape: Shape::from_dims(&[3]),
1882 dtype: DType::F32,
1883 });
1884 let add = g.push(Node {
1885 op: Op::Add,
1886 inputs: vec![lhs, rhs],
1887 shape: Shape::from_dims(&[3]),
1888 dtype: DType::F32,
1889 });
1890 g.set_target_backend(add, BackendId::Cpu);
1891 (g, add)
1892 }
1893
1894 fn cpu_caps() -> BackendCapabilities {
1895 BackendCapabilities {
1896 backend_id: BackendId::Cpu,
1897 device_location: DeviceLocation::Cpu,
1898 op_dtype_support: HashSet::new(),
1899 required_alignment: 64,
1900 access_granularity_bits: 8,
1901 transfer_paths: vec![(DeviceLocation::Cpu, TransferPath::SameDevice)],
1902 storage_substrate: SubstrateClass::HostBytes,
1903 compute_throughput_flops_per_ns: 1.0,
1904 mem_bandwidth_bytes_per_ns: 4.0,
1905 }
1906 }
1907
1908 #[test]
1909 fn empty_plan_has_no_alternatives() {
1910 let p = ExecutionPlan::empty();
1911 assert!(p.order.is_empty());
1912 assert!(p.alternatives.is_empty());
1913 assert!(p.alternatives(NodeId(0)).is_none());
1914 }
1915
1916 #[test]
1917 fn default_device_per_backend_matches_router_convention() {
1918 assert_eq!(default_device_for(BackendId::Cpu), DeviceLocation::Cpu);
1919 assert_eq!(
1920 default_device_for(BackendId::Cuda),
1921 DeviceLocation::Cuda { gpu_id: 0 },
1922 );
1923 assert_eq!(
1924 default_device_for(BackendId::Vulkan),
1925 DeviceLocation::Vulkan { gpu_id: 0 },
1926 );
1927 }
1928
1929 #[test]
1930 fn compile_plan_skips_view_and_const_nodes() {
1931 let mut table = KernelBindingTable::new();
1932 register_add_f32(
1933 &mut table,
1934 BackendId::Cpu,
1935 noop_kernel,
1936 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1937 );
1938
1939 let mut g = Graph::new();
1940 let lhs = g.push(Node {
1941 op: Op::Const,
1942 inputs: vec![],
1943 shape: Shape::from_dims(&[6]),
1944 dtype: DType::F32,
1945 });
1946 let rhs = g.push(Node {
1947 op: Op::Const,
1948 inputs: vec![],
1949 shape: Shape::from_dims(&[6]),
1950 dtype: DType::F32,
1951 });
1952 let add = g.push(Node {
1953 op: Op::Add,
1954 inputs: vec![lhs, rhs],
1955 shape: Shape::from_dims(&[6]),
1956 dtype: DType::F32,
1957 });
1958 let reshape = g.push(Node {
1959 op: Op::Reshape(Shape::from_dims(&[2, 3])),
1960 inputs: vec![add],
1961 shape: Shape::from_dims(&[2, 3]),
1962 dtype: DType::F32,
1963 });
1964 g.set_target_backend(add, BackendId::Cpu);
1965 g.set_target_backend(reshape, BackendId::Cpu);
1966
1967 let order = topo_order(&g, reshape);
1968 let opts = PlanOptions::new().without_cost_population();
1969 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
1970
1971 assert_eq!(plan.order.len(), 4);
1972 assert_eq!(
1973 plan.alternatives.len(),
1974 1,
1975 "only Add carries an alternative set",
1976 );
1977 let alts = plan.alternatives(add).expect("Add alternatives present");
1978 assert_eq!(alts.len(), 1);
1979 assert!(plan.alternatives(lhs).is_none());
1980 assert!(plan.alternatives(rhs).is_none());
1981 assert!(plan.alternatives(reshape).is_none());
1982 }
1983
1984 #[test]
1985 fn compile_plan_fails_fast_on_missing_binding() {
1986 let table = KernelBindingTable::new();
1987 let mut g = Graph::new();
1988 let lhs = g.push(Node {
1989 op: Op::Const,
1990 inputs: vec![],
1991 shape: Shape::from_dims(&[2, 3]),
1992 dtype: DType::F32,
1993 });
1994 let rhs = g.push(Node {
1995 op: Op::Const,
1996 inputs: vec![],
1997 shape: Shape::from_dims(&[3, 2]),
1998 dtype: DType::F32,
1999 });
2000 let mm = g.push(Node {
2001 op: Op::MatMul,
2002 inputs: vec![lhs, rhs],
2003 shape: Shape::from_dims(&[2, 2]),
2004 dtype: DType::F32,
2005 });
2006 g.set_target_backend(mm, BackendId::Cpu);
2007
2008 let order = topo_order(&g, mm);
2009 let opts = PlanOptions::new().without_cost_population();
2010 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
2011 match err {
2012 Error::NoBackendForOp { op, dtypes, .. } => {
2013 assert_eq!(op, OpKind::MatMul);
2014 assert_eq!(dtypes, vec![DType::F32, DType::F32, DType::F32]);
2015 }
2016 other => panic!("expected NoBackendForOp, got {other:?}"),
2017 }
2018 }
2019
2020 #[test]
2033 fn plan_time_miss_reports_real_coverage_not_empty() {
2034 let bindings = crate::dispatch::global_bindings(); let mut g = Graph::new();
2036 let lhs = g.push(Node {
2037 op: Op::Const,
2038 inputs: vec![],
2039 shape: Shape::from_dims(&[2, 3]),
2040 dtype: DType::F32,
2041 });
2042 let rhs = g.push(Node {
2045 op: Op::Const,
2046 inputs: vec![],
2047 shape: Shape::from_dims(&[3, 2]),
2048 dtype: DType::F64,
2049 });
2050 let mm = g.push(Node {
2051 op: Op::MatMul,
2052 inputs: vec![lhs, rhs],
2053 shape: Shape::from_dims(&[2, 2]),
2054 dtype: DType::F32,
2055 });
2056 g.set_target_backend(mm, BackendId::Cpu);
2057
2058 let order = topo_order(&g, mm);
2059 let opts = PlanOptions::new().without_cost_population();
2060 let err = compile_plan(&g, &order, &bindings, &opts).unwrap_err();
2061 match err {
2062 Error::NoBackendForOp {
2063 op,
2064 dtypes,
2065 available_backends,
2066 supported_combinations,
2067 } => {
2068 assert_eq!(op, OpKind::MatMul);
2069 assert_eq!(
2070 dtypes,
2071 vec![DType::F32, DType::F64, DType::F32],
2072 "the mixed-precision key (F32 activation, F64 weight)",
2073 );
2074 assert!(
2076 available_backends.contains(&BackendId::Cpu),
2077 "a populated table must report Cpu, never []: {available_backends:?}",
2078 );
2079 assert!(
2080 supported_combinations
2081 .iter()
2082 .any(|(b, o, d)| *b == BackendId::Cpu
2083 && *o == OpKind::MatMul
2084 && *d == vec![DType::F32, DType::F32, DType::F32]),
2085 "must show uniform F32 matmul IS registered (so the mixed gap is visible): \
2086 {supported_combinations:?}",
2087 );
2088 }
2089 other => panic!("expected NoBackendForOp, got {other:?}"),
2090 }
2091 }
2092
2093 #[test]
2094 fn compile_plan_legacy_single_backend_uses_target_backend() {
2095 let mut table = KernelBindingTable::new();
2096 register_add_f32(
2097 &mut table,
2098 BackendId::Cpu,
2099 noop_kernel,
2100 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2101 );
2102 register_add_f32(
2106 &mut table,
2107 BackendId::Cuda,
2108 noop_kernel_b,
2109 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2110 );
2111 let (g, add_id) = build_add_graph();
2112 let order = topo_order(&g, add_id);
2113 let opts = PlanOptions::new().without_cost_population();
2114 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2115 let alts = plan.alternatives(add_id).unwrap();
2116 assert_eq!(alts.len(), 1, "legacy mode → single backend → single alt");
2117 assert_eq!(alts.winner().unwrap().backend, BackendId::Cpu);
2118 }
2119
2120 #[test]
2121 fn compile_plan_cross_co_located_via_placements_callback() {
2122 let mut table = KernelBindingTable::new();
2123 register_add_f32(
2124 &mut table,
2125 BackendId::Cpu,
2126 noop_kernel,
2127 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2128 );
2129 register_add_f32(
2130 &mut table,
2131 BackendId::Cuda,
2132 noop_kernel_b,
2133 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2134 );
2135
2136 let (g, add_id) = build_add_graph();
2137 let order = topo_order(&g, add_id);
2138 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2139 if dev == DeviceLocation::Cpu {
2140 vec![BackendId::Cpu, BackendId::Cuda]
2141 } else {
2142 vec![]
2143 }
2144 };
2145 let opts = PlanOptions::new()
2146 .without_cost_population()
2147 .with_placements_for_device(&placements_fn);
2148 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2149 let alts = plan.alternatives(add_id).unwrap();
2150 assert_eq!(
2151 alts.len(),
2152 2,
2153 "cross-co-located mode aggregates Cpu + Aocl alternatives",
2154 );
2155 }
2156
2157 #[test]
2158 fn compile_plan_precision_requirement_filters_via_default_chain() {
2159 let mut table = KernelBindingTable::new();
2160 register_add_f32(
2162 &mut table,
2163 BackendId::Cpu,
2164 noop_kernel,
2165 PrecisionGuarantee {
2166 bit_stable_on_same_hardware: false,
2167 ..PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU
2168 },
2169 );
2170
2171 let (g, add_id) = build_add_graph();
2172 let order = topo_order(&g, add_id);
2173 let opts = PlanOptions::new()
2174 .without_cost_population()
2175 .with_precision_requirement(PrecisionRequirement::BIT_STABLE);
2176 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
2177 match err {
2178 Error::FilterRejected { filter, .. } => {
2179 assert_eq!(filter, "precision-floor");
2180 }
2181 other => panic!("expected FilterRejected, got {other:?}"),
2182 }
2183 let unconstrained = PlanOptions::new().without_cost_population();
2185 let plan = compile_plan(&g, &order, &table, &unconstrained).expect("compile");
2186 assert!(plan.alternatives(add_id).is_some());
2187 let _ = add_id;
2188 }
2189
2190 #[test]
2191 fn compile_plan_with_cost_ranks_cheaper_winner() {
2192 fn cheap_cost(
2193 _: &[Shape],
2194 _: &[DType],
2195 _: &OpParams,
2196 _: &BackendCapabilities,
2197 ) -> crate::fused::CostEstimate {
2198 crate::fused::CostEstimate {
2199 flops: 10,
2200 bytes_moved: 0,
2201 kernel_overhead_ns: 0,
2202 }
2203 }
2204 fn expensive_cost(
2205 _: &[Shape],
2206 _: &[DType],
2207 _: &OpParams,
2208 _: &BackendCapabilities,
2209 ) -> crate::fused::CostEstimate {
2210 crate::fused::CostEstimate {
2211 flops: 1_000_000,
2212 bytes_moved: 0,
2213 kernel_overhead_ns: 0,
2214 }
2215 }
2216 let mut table = KernelBindingTable::new();
2217 table.register_full(
2218 OpKind::AddElementwise,
2219 &[DType::F32, DType::F32, DType::F32],
2220 BackendId::Cpu,
2221 noop_kernel,
2222 KernelCaps::empty(),
2223 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2224 expensive_cost,
2225 );
2226 table.register_full(
2227 OpKind::AddElementwise,
2228 &[DType::F32, DType::F32, DType::F32],
2229 BackendId::Cuda,
2230 noop_kernel_b,
2231 KernelCaps::empty(),
2232 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2233 cheap_cost,
2234 );
2235
2236 let (g, add_id) = build_add_graph();
2237 let order = topo_order(&g, add_id);
2238 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2239 if dev == DeviceLocation::Cpu {
2240 vec![BackendId::Cpu, BackendId::Cuda]
2241 } else {
2242 vec![]
2243 }
2244 };
2245 let cpu_caps_val = cpu_caps();
2246 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
2247 let opts = PlanOptions::new()
2248 .with_placements_for_device(&placements_fn)
2249 .with_capabilities_for(&caps_fn);
2250 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2251 let alts = plan.alternatives(add_id).unwrap();
2252 assert_eq!(alts.len(), 2);
2253 assert_eq!(
2254 alts.winner().unwrap().backend,
2255 BackendId::Cuda,
2256 "cheaper static cost wins after ranking",
2257 );
2258 }
2259
2260 #[test]
2261 fn compile_plan_judge_layer2_can_flip_layer1_winner() {
2262 use crate::ranker::HashMapJudge;
2266 use fuel_ir::dispatch::SizeClass;
2267
2268 fn cpu_layer1(
2269 _: &[Shape],
2270 _: &[DType],
2271 _: &OpParams,
2272 _: &BackendCapabilities,
2273 ) -> crate::fused::CostEstimate {
2274 crate::fused::CostEstimate {
2275 flops: 10,
2276 bytes_moved: 0,
2277 kernel_overhead_ns: 0,
2278 }
2279 }
2280 fn aocl_layer1(
2281 _: &[Shape],
2282 _: &[DType],
2283 _: &OpParams,
2284 _: &BackendCapabilities,
2285 ) -> crate::fused::CostEstimate {
2286 crate::fused::CostEstimate {
2287 flops: 100_000,
2288 bytes_moved: 0,
2289 kernel_overhead_ns: 0,
2290 }
2291 }
2292 let mut table = KernelBindingTable::new();
2293 table.register_full(
2294 OpKind::AddElementwise,
2295 &[DType::F32, DType::F32, DType::F32],
2296 BackendId::Cpu,
2297 noop_kernel,
2298 KernelCaps::empty(),
2299 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2300 cpu_layer1,
2301 );
2302 table.register_full(
2303 OpKind::AddElementwise,
2304 &[DType::F32, DType::F32, DType::F32],
2305 BackendId::Cuda,
2306 noop_kernel_b,
2307 KernelCaps::empty(),
2308 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2309 aocl_layer1,
2310 );
2311
2312 let (g, add_id) = build_add_graph();
2313 let order = topo_order(&g, add_id);
2314 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2315 if dev == DeviceLocation::Cpu {
2316 vec![BackendId::Cpu, BackendId::Cuda]
2317 } else {
2318 vec![]
2319 }
2320 };
2321 let cpu_caps_val = cpu_caps();
2322 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
2323
2324 let sc = SizeClass::from_elem_count(3);
2327 let mut judge = HashMapJudge::new();
2328 judge.insert(
2329 OpKind::AddElementwise,
2330 DType::F32,
2331 sc,
2332 BackendId::Cpu,
2333 "",
2334 5_000,
2335 0,
2336 );
2337 judge.insert(
2338 OpKind::AddElementwise,
2339 DType::F32,
2340 sc,
2341 BackendId::Cuda,
2342 "",
2343 20,
2344 0,
2345 );
2346
2347 let opts = PlanOptions::new()
2348 .with_placements_for_device(&placements_fn)
2349 .with_capabilities_for(&caps_fn)
2350 .with_judge(&judge);
2351
2352 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2353 let alts = plan.alternatives(add_id).unwrap();
2354 assert_eq!(alts.len(), 2);
2355 assert_eq!(
2356 alts.winner().unwrap().backend,
2357 BackendId::Cuda,
2358 "Layer-2 measurement reverses Layer-1 verdict via compile_plan",
2359 );
2360 }
2361
2362 #[test]
2367 fn compile_plan_stamps_decision_context() {
2368 use fuel_ir::dispatch::SizeClass;
2369
2370 let mut table = KernelBindingTable::new();
2371 register_add_f32(
2372 &mut table,
2373 BackendId::Cpu,
2374 noop_kernel,
2375 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2376 );
2377 let (g, add_id) = build_add_graph();
2378 let order = topo_order(&g, add_id);
2379 let opts = PlanOptions::new().without_cost_population();
2380 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2381 let alts = plan.alternatives(add_id).expect("Add alternatives present");
2382 let ctx = alts.context().expect("context stamped");
2383 assert_eq!(ctx.op, OpKind::AddElementwise);
2384 assert_eq!(ctx.principal_dtype, DType::F32);
2385 assert_eq!(ctx.size_class, SizeClass::from_elem_count(3));
2387 }
2388
2389 #[test]
2398 fn compile_plan_retains_per_device_frontier_no_top_n() {
2399 let mut table = KernelBindingTable::new();
2400 register_add_f32(
2403 &mut table,
2404 BackendId::Cpu,
2405 noop_kernel,
2406 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2407 );
2408 register_add_f32(
2409 &mut table,
2410 BackendId::Cuda,
2411 noop_kernel_b,
2412 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2413 );
2414 register_add_f32(
2415 &mut table,
2416 BackendId::Vulkan,
2417 noop_kernel_c,
2418 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2419 );
2420
2421 let (g, add_id) = build_add_graph();
2422 let order = topo_order(&g, add_id);
2423 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2424 if dev == DeviceLocation::Cpu {
2425 vec![BackendId::Cpu, BackendId::Cuda, BackendId::Vulkan]
2426 } else {
2427 vec![]
2428 }
2429 };
2430 let opts = PlanOptions::new()
2431 .without_cost_population()
2432 .with_placements_for_device(&placements_fn);
2433 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2434 let alts = plan.alternatives(add_id).unwrap();
2435 assert_eq!(
2436 alts.len(),
2437 3,
2438 "all three co-located (device, backend) paths survive — no top-N truncation",
2439 );
2440 }
2441
2442 #[test]
2447 fn compile_plan_pinned_device_matches_stamped_plan() {
2448 let mut table = KernelBindingTable::new();
2449 register_add_f32(
2450 &mut table,
2451 BackendId::Cpu,
2452 noop_kernel,
2453 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2454 );
2455
2456 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2457 if dev == DeviceLocation::Cpu {
2458 vec![BackendId::Cpu]
2459 } else {
2460 vec![]
2461 }
2462 };
2463
2464 let (g_stamped, add_stamped) = build_add_graph();
2466 let order_stamped = topo_order(&g_stamped, add_stamped);
2467 let opts_stamped = PlanOptions::new()
2468 .without_cost_population()
2469 .with_placements_for_device(&placements_fn);
2470 let plan_stamped = compile_plan(&g_stamped, &order_stamped, &table, &opts_stamped)
2471 .expect("stamped compile");
2472
2473 let mut g = Graph::new();
2476 let lhs = g.push(Node {
2477 op: Op::Const,
2478 inputs: vec![],
2479 shape: Shape::from_dims(&[3]),
2480 dtype: DType::F32,
2481 });
2482 let rhs = g.push(Node {
2483 op: Op::Const,
2484 inputs: vec![],
2485 shape: Shape::from_dims(&[3]),
2486 dtype: DType::F32,
2487 });
2488 let add = g.push(Node {
2489 op: Op::Add,
2490 inputs: vec![lhs, rhs],
2491 shape: Shape::from_dims(&[3]),
2492 dtype: DType::F32,
2493 });
2494 let order = topo_order(&g, add);
2495 let opts = PlanOptions::new()
2496 .without_cost_population()
2497 .with_placements_for_device(&placements_fn)
2498 .with_pinned_device(DeviceLocation::Cpu);
2499 let plan = compile_plan(&g, &order, &table, &opts).expect("pinned compile");
2500
2501 let a = plan_stamped.alternatives(add_stamped).expect("stamped set");
2502 let b = plan.alternatives(add).expect("pinned set");
2503 assert_eq!(a.len(), b.len(), "same candidate count");
2504 for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
2505 assert_eq!(ca.backend, cb.backend);
2506 assert_eq!(ca.device, cb.device);
2507 assert_eq!(ca.kernel as usize, cb.kernel as usize, "same kernel ref");
2508 assert_eq!(ca.kernel_source, cb.kernel_source);
2509 }
2510 assert_eq!(a.context(), b.context(), "same decision context");
2511 }
2512
2513 #[test]
2517 fn compile_plan_errors_without_any_device_context() {
2518 let mut table = KernelBindingTable::new();
2519 register_add_f32(
2520 &mut table,
2521 BackendId::Cpu,
2522 noop_kernel,
2523 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2524 );
2525 let mut g = Graph::new();
2526 let lhs = g.push(Node {
2527 op: Op::Const,
2528 inputs: vec![],
2529 shape: Shape::from_dims(&[3]),
2530 dtype: DType::F32,
2531 });
2532 let add = g.push(Node {
2533 op: Op::Add,
2534 inputs: vec![lhs, lhs],
2535 shape: Shape::from_dims(&[3]),
2536 dtype: DType::F32,
2537 });
2538 let order = topo_order(&g, add);
2539 let opts = PlanOptions::new().without_cost_population();
2540 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
2541 let msg = format!("{err:?}");
2542 assert!(
2543 msg.contains("no device context"),
2544 "expected the device-context diagnostic, got: {msg}",
2545 );
2546 }
2547
2548 #[test]
2553 fn compile_plan_skips_op_copy_nodes() {
2554 let mut table = KernelBindingTable::new();
2555 register_add_f32(
2556 &mut table,
2557 BackendId::Cpu,
2558 noop_kernel,
2559 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2560 );
2561 table.register_full(
2564 OpKind::Copy,
2565 &[DType::F32, DType::F32],
2566 BackendId::Cpu,
2567 noop_kernel_b,
2568 KernelCaps::empty(),
2569 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2570 unknown_cost,
2571 );
2572
2573 let (mut g, add_id) = build_add_graph();
2574 let copy_id = g.push(Node {
2575 op: Op::Copy {
2576 target: DeviceLocation::Cpu,
2577 },
2578 inputs: vec![add_id],
2579 shape: Shape::from_dims(&[3]),
2580 dtype: DType::F32,
2581 });
2582 g.set_target_backend(copy_id, BackendId::Cpu);
2583 let order = topo_order(&g, copy_id);
2584 let opts = PlanOptions::new()
2585 .without_cost_population()
2586 .with_pinned_device(DeviceLocation::Cpu);
2587 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2588 assert!(plan.alternatives(add_id).is_some(), "Add is planned");
2589 assert!(
2590 plan.alternatives(copy_id).is_none(),
2591 "Op::Copy is residency-determined — no plan entry",
2592 );
2593 }
2594
2595 #[test]
2599 fn compile_plan_skips_op_move_nodes() {
2600 let mut table = KernelBindingTable::new();
2601 register_add_f32(
2602 &mut table,
2603 BackendId::Cpu,
2604 noop_kernel,
2605 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2606 );
2607 table.register_full(
2610 OpKind::Copy,
2611 &[DType::F32, DType::F32],
2612 BackendId::Cpu,
2613 noop_kernel_b,
2614 KernelCaps::empty(),
2615 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2616 unknown_cost,
2617 );
2618
2619 let (mut g, add_id) = build_add_graph();
2620 let move_id = g.push(Node {
2621 op: Op::Move {
2622 target: DeviceLocation::Cpu,
2623 },
2624 inputs: vec![add_id],
2625 shape: Shape::from_dims(&[3]),
2626 dtype: DType::F32,
2627 });
2628 g.set_target_backend(move_id, BackendId::Cpu);
2629 let order = topo_order(&g, move_id);
2630 let opts = PlanOptions::new()
2631 .without_cost_population()
2632 .with_pinned_device(DeviceLocation::Cpu);
2633 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2634 assert!(plan.alternatives(add_id).is_some(), "Add is planned");
2635 assert!(
2636 plan.alternatives(move_id).is_none(),
2637 "Op::Move is residency-determined — no plan entry",
2638 );
2639 }
2640
2641 #[test]
2645 fn compile_plan_fallback_admits_off_device_candidate() {
2646 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2647 let mut table = KernelBindingTable::new();
2648 register_add_f32(
2651 &mut table,
2652 BackendId::Cpu,
2653 noop_kernel,
2654 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2655 );
2656
2657 let mut g = Graph::new();
2658 let lhs = g.push(Node {
2659 op: Op::Const,
2660 inputs: vec![],
2661 shape: Shape::from_dims(&[3]),
2662 dtype: DType::F32,
2663 });
2664 let add = g.push(Node {
2665 op: Op::Add,
2666 inputs: vec![lhs, lhs],
2667 shape: Shape::from_dims(&[3]),
2668 dtype: DType::F32,
2669 });
2670 let order = topo_order(&g, add);
2671
2672 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2673 if dev == cuda0 {
2674 vec![BackendId::Cuda]
2675 } else {
2676 vec![BackendId::Cpu]
2677 }
2678 };
2679 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2680 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
2681 };
2682 let opts = PlanOptions::new()
2683 .without_cost_population()
2684 .with_pinned_device(cuda0)
2685 .with_placements_for_device(&placements_fn)
2686 .with_fallback_placements_for(&fallback_fn);
2687 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2688 let alts = plan.alternatives(add).expect("Add planned via fallback");
2689 assert_eq!(alts.len(), 1, "fallback set frozen to one winner");
2690 let w = alts.winner().unwrap();
2691 assert_eq!(w.backend, BackendId::Cpu);
2692 assert_eq!(w.device, DeviceLocation::Cpu, "off-device placement");
2693 }
2694
2695 #[test]
2701 fn compile_plan_fallback_not_consulted_when_pinned_has_impl() {
2702 let mut table = KernelBindingTable::new();
2703 register_add_f32(
2704 &mut table,
2705 BackendId::Cpu,
2706 noop_kernel,
2707 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2708 );
2709 register_add_f32(
2710 &mut table,
2711 BackendId::Cuda,
2712 noop_kernel_b,
2713 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2714 );
2715 let (g, add_id) = build_add_graph();
2716 let order = topo_order(&g, add_id);
2717 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2718 if dev == DeviceLocation::Cpu {
2719 vec![BackendId::Cpu]
2720 } else {
2721 vec![]
2722 }
2723 };
2724 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2725 panic!(
2726 "fallback consulted although the pinned device has an \
2727 implementation — locality policy violated",
2728 );
2729 };
2730 let opts = PlanOptions::new()
2731 .without_cost_population()
2732 .with_pinned_device(DeviceLocation::Cpu)
2733 .with_placements_for_device(&placements_fn)
2734 .with_fallback_placements_for(&fallback_fn);
2735 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2736 let alts = plan.alternatives(add_id).unwrap();
2737 assert_eq!(alts.len(), 1);
2738 assert_eq!(alts.winner().unwrap().device, DeviceLocation::Cpu);
2739 }
2740
2741 #[test]
2744 fn compile_plan_fallback_denied_for_destructive_ops() {
2745 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2746 let mut table = KernelBindingTable::new();
2747 table.register_full(
2749 OpKind::ReluInplace,
2750 &[DType::F32, DType::F32],
2751 BackendId::Cpu,
2752 noop_kernel,
2753 KernelCaps::empty(),
2754 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2755 unknown_cost,
2756 );
2757 let mut g = Graph::new();
2758 let lhs = g.push(Node {
2759 op: Op::Const,
2760 inputs: vec![],
2761 shape: Shape::from_dims(&[3]),
2762 dtype: DType::F32,
2763 });
2764 let relu = g.push(Node {
2765 op: Op::ReluInplace,
2766 inputs: vec![lhs],
2767 shape: Shape::from_dims(&[3]),
2768 dtype: DType::F32,
2769 });
2770 let order = topo_order(&g, relu);
2771 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2772 if dev == cuda0 {
2773 vec![BackendId::Cuda]
2774 } else {
2775 vec![BackendId::Cpu]
2776 }
2777 };
2778 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2779 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
2780 };
2781 let opts = PlanOptions::new()
2782 .without_cost_population()
2783 .with_pinned_device(cuda0)
2784 .with_placements_for_device(&placements_fn)
2785 .with_fallback_placements_for(&fallback_fn);
2786 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
2787 assert!(
2788 matches!(
2789 err,
2790 Error::NoBackendForOp {
2791 op: OpKind::ReluInplace,
2792 ..
2793 }
2794 ),
2795 "destructive op must NOT fall back off-device; got {err:?}",
2796 );
2797 }
2798
2799 #[test]
2804 fn compile_plan_fallback_freezes_to_single_winner() {
2805 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2806 let vk0 = DeviceLocation::Vulkan { gpu_id: 0 };
2807 let mut table = KernelBindingTable::new();
2808 register_add_f32(
2809 &mut table,
2810 BackendId::Cpu,
2811 noop_kernel,
2812 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2813 );
2814 register_add_f32(
2815 &mut table,
2816 BackendId::Vulkan,
2817 noop_kernel_b,
2818 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2819 );
2820
2821 let mut g = Graph::new();
2822 let lhs = g.push(Node {
2823 op: Op::Const,
2824 inputs: vec![],
2825 shape: Shape::from_dims(&[3]),
2826 dtype: DType::F32,
2827 });
2828 let add = g.push(Node {
2829 op: Op::Add,
2830 inputs: vec![lhs, lhs],
2831 shape: Shape::from_dims(&[3]),
2832 dtype: DType::F32,
2833 });
2834 let order = topo_order(&g, add);
2835 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2836 if dev == cuda0 {
2837 vec![BackendId::Cuda]
2838 } else {
2839 vec![]
2840 }
2841 };
2842 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2843 vec![
2844 (BackendId::Cpu, DeviceLocation::Cpu),
2845 (BackendId::Vulkan, vk0),
2846 ]
2847 };
2848 let opts = PlanOptions::new()
2849 .without_cost_population()
2850 .with_pinned_device(cuda0)
2851 .with_placements_for_device(&placements_fn)
2852 .with_fallback_placements_for(&fallback_fn);
2853 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2854 let alts = plan.alternatives(add).unwrap();
2855 assert_eq!(
2856 alts.len(),
2857 1,
2858 "fallback set must freeze to its single ranked winner",
2859 );
2860 }
2861
2862 struct FlatEstimator {
2865 latency_ns: u64,
2866 }
2867
2868 impl crate::ranker::TransferEstimator for FlatEstimator {
2869 fn estimate_transfer_ns(
2870 &self,
2871 src: DeviceLocation,
2872 dst: DeviceLocation,
2873 _bytes: u64,
2874 ) -> u64 {
2875 if src == dst { 0 } else { self.latency_ns }
2876 }
2877 }
2878
2879 #[test]
2885 fn compile_plan_prices_fallback_by_input_residency() {
2886 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2887 let vk0 = DeviceLocation::Vulkan { gpu_id: 0 };
2888 let mut table = KernelBindingTable::new();
2889 register_add_f32(
2891 &mut table,
2892 BackendId::Cpu,
2893 noop_kernel,
2894 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2895 );
2896 register_add_f32(
2897 &mut table,
2898 BackendId::Vulkan,
2899 noop_kernel_b,
2900 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2901 );
2902
2903 let mut g = Graph::new();
2904 let lhs = g.push(Node {
2905 op: Op::Const,
2906 inputs: vec![],
2907 shape: Shape::from_dims(&[4]),
2908 dtype: DType::F32,
2909 });
2910 let add = g.push(Node {
2911 op: Op::Add,
2912 inputs: vec![lhs, lhs],
2913 shape: Shape::from_dims(&[4]),
2914 dtype: DType::F32,
2915 });
2916 let order = topo_order(&g, add);
2917
2918 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2919 if dev == cuda0 {
2920 vec![BackendId::Cuda]
2921 } else {
2922 vec![]
2923 }
2924 };
2925 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2926 vec![
2927 (BackendId::Cpu, DeviceLocation::Cpu),
2928 (BackendId::Vulkan, vk0),
2929 ]
2930 };
2931 let residency_fn =
2935 move |id: NodeId| -> Option<DeviceLocation> { (id == lhs).then_some(vk0) };
2936 let est = FlatEstimator { latency_ns: 1_000 };
2937 let cpu_caps_val = cpu_caps();
2938 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
2939 let opts = PlanOptions::new()
2940 .with_pinned_device(cuda0)
2941 .with_placements_for_device(&placements_fn)
2942 .with_fallback_placements_for(&fallback_fn)
2943 .with_capabilities_for(&caps_fn)
2944 .with_transfer_estimator(&est)
2945 .with_input_residency(&residency_fn);
2946 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2947 let alts = plan.alternatives(add).expect("Add planned via fallback");
2948 assert_eq!(alts.len(), 1, "fallback narrows to a single winner");
2949 let w = alts.winner().unwrap();
2950 assert_eq!(
2951 w.device, vk0,
2952 "transfer pricing moves the fallback to the inputs' residency",
2953 );
2954 assert_eq!(w.inbound_transfer_ns, 0, "co-resident inputs price zero");
2955 }
2956
2957 fn cost_600(
2960 _: &[Shape],
2961 _: &[DType],
2962 _: &OpParams,
2963 _: &BackendCapabilities,
2964 ) -> crate::fused::CostEstimate {
2965 crate::fused::CostEstimate {
2966 flops: 600,
2967 bytes_moved: 0,
2968 kernel_overhead_ns: 0,
2969 }
2970 }
2971 fn cost_10(
2972 _: &[Shape],
2973 _: &[DType],
2974 _: &OpParams,
2975 _: &BackendCapabilities,
2976 ) -> crate::fused::CostEstimate {
2977 crate::fused::CostEstimate {
2978 flops: 10,
2979 bytes_moved: 0,
2980 kernel_overhead_ns: 0,
2981 }
2982 }
2983 fn cost_15_000(
2987 _: &[Shape],
2988 _: &[DType],
2989 _: &OpParams,
2990 _: &BackendCapabilities,
2991 ) -> crate::fused::CostEstimate {
2992 crate::fused::CostEstimate {
2993 flops: 15_000,
2994 bytes_moved: 0,
2995 kernel_overhead_ns: 0,
2996 }
2997 }
2998 fn cost_10_000_000(
2999 _: &[Shape],
3000 _: &[DType],
3001 _: &OpParams,
3002 _: &BackendCapabilities,
3003 ) -> crate::fused::CostEstimate {
3004 crate::fused::CostEstimate {
3005 flops: 10_000_000,
3006 bytes_moved: 0,
3007 kernel_overhead_ns: 0,
3008 }
3009 }
3010
3011 fn relaxed_plan_with_costs(
3017 cpu_cost: crate::kernel::CostFn,
3018 cuda_cost: crate::kernel::CostFn,
3019 estimator: &FlatEstimator,
3020 ) -> AlternativeSet {
3021 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3022 let mut table = KernelBindingTable::new();
3023 table.register_full(
3024 OpKind::AddElementwise,
3025 &[DType::F32, DType::F32, DType::F32],
3026 BackendId::Cpu,
3027 noop_kernel,
3028 KernelCaps::empty(),
3029 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3030 cpu_cost,
3031 );
3032 table.register_full(
3033 OpKind::AddElementwise,
3034 &[DType::F32, DType::F32, DType::F32],
3035 BackendId::Cuda,
3036 noop_kernel_b,
3037 KernelCaps::empty(),
3038 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3039 cuda_cost,
3040 );
3041
3042 let (g, add_id) = build_add_graph();
3043 let order = topo_order(&g, add_id);
3044 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3045 if dev == DeviceLocation::Cpu {
3046 vec![BackendId::Cpu]
3047 } else {
3048 vec![]
3049 }
3050 };
3051 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3052 vec![(BackendId::Cuda, cuda0)]
3053 };
3054 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3057 let cpu_caps_val = cpu_caps();
3058 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3059 let opts = PlanOptions::new()
3060 .with_pinned_device(DeviceLocation::Cpu)
3061 .with_placements_for_device(&placements_fn)
3062 .with_fallback_placements_for(&fallback_fn)
3063 .with_capabilities_for(&caps_fn)
3064 .with_transfer_estimator(estimator)
3065 .with_input_residency(&residency_fn);
3066 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3067 plan.alternatives(add_id).expect("Add planned").clone()
3068 }
3069
3070 #[test]
3074 fn compile_plan_relaxed_tiny_op_stays_local_when_transfer_dominates() {
3075 let est = FlatEstimator {
3078 latency_ns: 1_000_000,
3079 };
3080 let set = relaxed_plan_with_costs(cost_600, cost_10, &est);
3081 let w = set.winner().unwrap();
3082 assert_eq!(
3083 w.device,
3084 DeviceLocation::Cpu,
3085 "transfer dominates → stay local"
3086 );
3087 assert_eq!(w.inbound_transfer_ns, 0, "local winner pays no transfer");
3088 assert!(
3089 set.alternatives()
3090 .iter()
3091 .all(|c| c.device == DeviceLocation::Cpu),
3092 "off-device siblings pruned after rank",
3093 );
3094 }
3095
3096 #[test]
3129 fn compile_plan_uncapped_gpu_no_longer_wins_by_being_free() {
3130 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3131
3132 fn build_table() -> KernelBindingTable {
3139 let mut table = KernelBindingTable::new();
3140 table.register_full(
3141 OpKind::AddElementwise,
3142 &[DType::F32, DType::F32, DType::F32],
3143 BackendId::Cpu,
3144 noop_kernel,
3145 KernelCaps::empty(),
3146 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3147 cost_600,
3148 );
3149 table.register_full(
3150 OpKind::AddElementwise,
3151 &[DType::F32, DType::F32, DType::F32],
3152 BackendId::Cuda,
3153 noop_kernel_b,
3154 KernelCaps::empty(),
3155 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3156 cost_15_000,
3157 );
3158 table
3159 }
3160
3161 fn winner_device_under(
3169 table: &KernelBindingTable,
3170 cpu_caps_val: &'static BackendCapabilities,
3171 gpu_caps: Option<&'static BackendCapabilities>,
3172 cuda0: DeviceLocation,
3173 ) -> DeviceLocation {
3174 let (g, add_id) = build_add_graph();
3175 let order = topo_order(&g, add_id);
3176 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3177 if dev == DeviceLocation::Cpu {
3178 vec![BackendId::Cpu]
3179 } else {
3180 vec![]
3181 }
3182 };
3183 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3184 vec![(BackendId::Cuda, cuda0)]
3185 };
3186 let residency_fn =
3190 |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3191 let est = FlatEstimator { latency_ns: 100 };
3194 let caps_fn = move |b: BackendId| -> Option<&BackendCapabilities> {
3195 match b {
3196 BackendId::Cpu => Some(cpu_caps_val),
3197 BackendId::Cuda => gpu_caps,
3198 _ => None,
3199 }
3200 };
3201 let opts = PlanOptions::new()
3202 .with_pinned_device(DeviceLocation::Cpu)
3203 .with_placements_for_device(&placements_fn)
3204 .with_fallback_placements_for(&fallback_fn)
3205 .with_capabilities_for(&caps_fn)
3206 .with_transfer_estimator(&est)
3207 .with_input_residency(&residency_fn);
3208 let plan = compile_plan(&g, &order, table, &opts).expect("compile");
3209 plan.alternatives(add_id).unwrap().winner().unwrap().device
3210 }
3211
3212 let table = build_table();
3213 let cpu_caps_val: &'static BackendCapabilities = Box::leak(Box::new(cpu_caps()));
3217
3218 let winner_bug = winner_device_under(&table, cpu_caps_val, None, cuda0);
3222 assert_eq!(
3223 winner_bug, cuda0,
3224 "PRE-FIX: an uncapped CUDA candidate is skipped by \
3225 compute_static_costs, prices at 0 + 200 transfer, and \
3226 spuriously beats the CPU's honest 600 — this IS the bug",
3227 );
3228
3229 let cuda_caps_val: &'static BackendCapabilities = Box::leak(Box::new(
3232 crate::dispatch::derive_backend_caps(BackendId::Cuda, cuda0, &table),
3233 ));
3234 assert!(
3237 cuda_caps_val
3238 .op_dtype_support
3239 .contains(&(OpKind::AddElementwise, DType::F32)),
3240 "derive_backend_caps must mirror the binding table's \
3241 registered (op, output-dtype) pairs for the backend",
3242 );
3243 assert_eq!(cuda_caps_val.backend_id, BackendId::Cuda);
3244 assert_eq!(cuda_caps_val.device_location, cuda0);
3245
3246 let winner_fixed = winner_device_under(&table, cpu_caps_val, Some(cuda_caps_val), cuda0);
3247 assert_eq!(
3248 winner_fixed,
3249 DeviceLocation::Cpu,
3250 "POST-FIX: with GPU caps registered the CUDA candidate is \
3251 costed honestly (15000 FLOPs ÷ 30/ns = 500 ns compute + 200 \
3252 transfer = 700 > CPU 600), so the CPU-pinned realize stays \
3253 on CPU — no spill onto the unseeded GPU",
3254 );
3255 }
3256
3257 #[test]
3274 fn compile_plan_places_large_compute_on_gpu_small_on_cpu_by_throughput() {
3275 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3276
3277 fn winner(cost: crate::kernel::CostFn, cuda0: DeviceLocation) -> DeviceLocation {
3278 let mut table = KernelBindingTable::new();
3279 table.register_full(
3280 OpKind::AddElementwise,
3281 &[DType::F32, DType::F32, DType::F32],
3282 BackendId::Cpu,
3283 noop_kernel,
3284 KernelCaps::empty(),
3285 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3286 cost,
3287 );
3288 table.register_full(
3289 OpKind::AddElementwise,
3290 &[DType::F32, DType::F32, DType::F32],
3291 BackendId::Cuda,
3292 noop_kernel_b,
3293 KernelCaps::empty(),
3294 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3295 cost,
3296 );
3297
3298 let (g, add_id) = build_add_graph();
3299 let order = topo_order(&g, add_id);
3300 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3301 if dev == DeviceLocation::Cpu {
3302 vec![BackendId::Cpu]
3303 } else {
3304 vec![]
3305 }
3306 };
3307 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3308 vec![(BackendId::Cuda, cuda0)]
3309 };
3310 let residency_fn =
3311 |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3312 let est = FlatEstimator { latency_ns: 100 };
3315 let cpu_caps_val = cpu_caps();
3316 let cuda_caps_val =
3317 crate::dispatch::derive_backend_caps(BackendId::Cuda, cuda0, &table);
3318 let caps_fn = |b: BackendId| -> Option<&BackendCapabilities> {
3319 match b {
3320 BackendId::Cpu => Some(&cpu_caps_val),
3321 BackendId::Cuda => Some(&cuda_caps_val),
3322 _ => None,
3323 }
3324 };
3325 let opts = PlanOptions::new()
3326 .with_pinned_device(DeviceLocation::Cpu)
3327 .with_placements_for_device(&placements_fn)
3328 .with_fallback_placements_for(&fallback_fn)
3329 .with_capabilities_for(&caps_fn)
3330 .with_transfer_estimator(&est)
3331 .with_input_residency(&residency_fn);
3332 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3333 plan.alternatives(add_id).unwrap().winner().unwrap().device
3334 }
3335
3336 assert_eq!(
3337 winner(cost_100, cuda0),
3338 DeviceLocation::Cpu,
3339 "SMALL op: the GPU's throughput win on 100 FLOPs (~3 ns) \
3340 can't overcome the 200 ns inbound transfer → stay on CPU",
3341 );
3342 assert_eq!(
3343 winner(cost_10_000_000, cuda0),
3344 cuda0,
3345 "LARGE op: the GPU's throughput win on 10 M FLOPs (~333 k ns) \
3346 dwarfs the 200 ns transfer → move to CUDA. RED under the \
3347 fixed 1-FLOP/ns prior (equal compute-ns → the transfer \
3348 always loses the GPU the placement)",
3349 );
3350 }
3351
3352 #[test]
3363 fn compile_plan_without_cost_placement_keeps_large_op_on_cpu() {
3364 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3365 let mut table = KernelBindingTable::new();
3366 table.register_full(
3367 OpKind::AddElementwise,
3368 &[DType::F32, DType::F32, DType::F32],
3369 BackendId::Cpu,
3370 noop_kernel,
3371 KernelCaps::empty(),
3372 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3373 cost_10_000_000,
3374 );
3375 table.register_full(
3376 OpKind::AddElementwise,
3377 &[DType::F32, DType::F32, DType::F32],
3378 BackendId::Cuda,
3379 noop_kernel_b,
3380 KernelCaps::empty(),
3381 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3382 cost_10_000_000,
3383 );
3384
3385 let (g, add_id) = build_add_graph();
3386 let order = topo_order(&g, add_id);
3387 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3388 if dev == DeviceLocation::Cpu {
3389 vec![BackendId::Cpu]
3390 } else {
3391 vec![]
3392 }
3393 };
3394 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3395 vec![(BackendId::Cuda, cuda0)]
3396 };
3397 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3398 let est = FlatEstimator { latency_ns: 100 };
3399 let cpu_caps_val = cpu_caps();
3400 let cuda_caps_val = crate::dispatch::derive_backend_caps(BackendId::Cuda, cuda0, &table);
3401 let caps_fn = |b: BackendId| -> Option<&BackendCapabilities> {
3402 match b {
3403 BackendId::Cpu => Some(&cpu_caps_val),
3404 BackendId::Cuda => Some(&cuda_caps_val),
3405 _ => None,
3406 }
3407 };
3408 let opts = PlanOptions::new()
3409 .with_pinned_device(DeviceLocation::Cpu)
3410 .with_placements_for_device(&placements_fn)
3411 .with_fallback_placements_for(&fallback_fn)
3412 .with_capabilities_for(&caps_fn)
3413 .with_transfer_estimator(&est)
3414 .with_input_residency(&residency_fn)
3415 .without_cost_placement();
3416 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3417 let set = plan.alternatives(add_id).unwrap();
3418 assert_eq!(
3419 set.winner().unwrap().device,
3420 DeviceLocation::Cpu,
3421 "without_cost_placement: the large GPU-favorable op stays on the \
3422 pinned CPU device (no relaxed cross-device enumeration)",
3423 );
3424 assert!(
3425 set.alternatives()
3426 .iter()
3427 .all(|c| c.device == DeviceLocation::Cpu),
3428 "no off-device candidate enumerated at all",
3429 );
3430 }
3431
3432 #[test]
3437 fn compile_plan_relaxed_huge_op_moves_when_kernel_gap_dominates() {
3438 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3439 let est = FlatEstimator { latency_ns: 1_000 };
3441 let set = relaxed_plan_with_costs(cost_10_000_000, cost_10, &est);
3442 let w = set.winner().unwrap();
3443 assert_eq!(w.device, cuda0, "kernel gap dominates → move");
3444 assert_eq!(
3445 w.inbound_transfer_ns, 2_000,
3446 "the move's two input crossings are priced on the winner",
3447 );
3448 assert!(
3449 set.alternatives().iter().all(|c| c.device == cuda0),
3450 "set pruned to the winner's device",
3451 );
3452 }
3453
3454 #[test]
3459 fn compile_plan_relaxed_zero_signal_ties_stay_local() {
3460 let est = FlatEstimator { latency_ns: 0 };
3461 let set = relaxed_plan_with_costs(unknown_cost, unknown_cost, &est);
3462 assert_eq!(
3463 set.winner().unwrap().device,
3464 DeviceLocation::Cpu,
3465 "ties break toward the decision device",
3466 );
3467 }
3468
3469 #[test]
3473 fn compile_plan_relaxed_single_device_plan_unchanged() {
3474 let mut table = KernelBindingTable::new();
3475 register_add_f32(
3476 &mut table,
3477 BackendId::Cpu,
3478 noop_kernel,
3479 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3480 );
3481 let (g, add_id) = build_add_graph();
3482 let order = topo_order(&g, add_id);
3483 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3484 if dev == DeviceLocation::Cpu {
3485 vec![BackendId::Cpu]
3486 } else {
3487 vec![]
3488 }
3489 };
3490 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> { Vec::new() };
3492 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3493 let cpu_caps_val = cpu_caps();
3494 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3495
3496 let base_opts = PlanOptions::new()
3497 .with_pinned_device(DeviceLocation::Cpu)
3498 .with_placements_for_device(&placements_fn)
3499 .with_fallback_placements_for(&fallback_fn)
3500 .with_capabilities_for(&caps_fn);
3501 let base = compile_plan(&g, &order, &table, &base_opts).expect("base");
3502
3503 let est = FlatEstimator {
3504 latency_ns: 1_000_000,
3505 };
3506 let wired_opts = PlanOptions::new()
3507 .with_pinned_device(DeviceLocation::Cpu)
3508 .with_placements_for_device(&placements_fn)
3509 .with_fallback_placements_for(&fallback_fn)
3510 .with_capabilities_for(&caps_fn)
3511 .with_transfer_estimator(&est)
3512 .with_input_residency(&residency_fn);
3513 let wired = compile_plan(&g, &order, &table, &wired_opts).expect("wired");
3514
3515 let a = base.alternatives(add_id).unwrap();
3516 let b = wired.alternatives(add_id).unwrap();
3517 assert_eq!(a.len(), b.len(), "same candidate count");
3518 for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
3519 assert_eq!(ca.backend, cb.backend);
3520 assert_eq!(ca.device, cb.device);
3521 assert_eq!(ca.kernel as usize, cb.kernel as usize, "same kernel ref");
3522 assert_eq!(ca.static_cost, cb.static_cost, "same Layer-1 cost");
3523 assert_eq!(cb.inbound_transfer_ns, 0, "no transfer term fires");
3524 }
3525 assert_eq!(a.context(), b.context(), "same decision context");
3526 }
3527
3528 #[test]
3533 fn compile_plan_relaxed_respects_explicit_placement_pin() {
3534 let mut table = KernelBindingTable::new();
3535 register_add_f32(
3536 &mut table,
3537 BackendId::Cpu,
3538 noop_kernel,
3539 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3540 );
3541 register_add_f32(
3542 &mut table,
3543 BackendId::Cuda,
3544 noop_kernel_b,
3545 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3546 );
3547 let (mut g, add_id) = build_add_graph();
3548 g.set_placement(add_id, DeviceLocation::Cpu);
3550 let order = topo_order(&g, add_id);
3551 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3552 if dev == DeviceLocation::Cpu {
3553 vec![BackendId::Cpu]
3554 } else {
3555 vec![]
3556 }
3557 };
3558 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3559 panic!(
3560 "fallback consulted for a hard-pinned node — explicit \
3561 placements must not enter the priced relax",
3562 );
3563 };
3564 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3565 let est = FlatEstimator { latency_ns: 0 };
3566 let cpu_caps_val = cpu_caps();
3567 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3568 let opts = PlanOptions::new()
3569 .with_pinned_device(DeviceLocation::Cpu)
3570 .with_placements_for_device(&placements_fn)
3571 .with_fallback_placements_for(&fallback_fn)
3572 .with_capabilities_for(&caps_fn)
3573 .with_transfer_estimator(&est)
3574 .with_input_residency(&residency_fn);
3575 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3576 assert_eq!(
3577 plan.alternatives(add_id).unwrap().winner().unwrap().device,
3578 DeviceLocation::Cpu,
3579 );
3580 }
3581
3582 #[test]
3585 fn compile_plan_relaxed_destructive_never_moves() {
3586 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3587 let mut table = KernelBindingTable::new();
3588 table.register_full(
3589 OpKind::ReluInplace,
3590 &[DType::F32, DType::F32],
3591 BackendId::Cpu,
3592 noop_kernel,
3593 KernelCaps::empty(),
3594 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3595 cost_600,
3596 );
3597 table.register_full(
3598 OpKind::ReluInplace,
3599 &[DType::F32, DType::F32],
3600 BackendId::Cuda,
3601 noop_kernel_b,
3602 KernelCaps::empty(),
3603 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3604 cost_10,
3605 );
3606 let mut g = Graph::new();
3607 let lhs = g.push(Node {
3608 op: Op::Const,
3609 inputs: vec![],
3610 shape: Shape::from_dims(&[3]),
3611 dtype: DType::F32,
3612 });
3613 let relu = g.push(Node {
3614 op: Op::ReluInplace,
3615 inputs: vec![lhs],
3616 shape: Shape::from_dims(&[3]),
3617 dtype: DType::F32,
3618 });
3619 let order = topo_order(&g, relu);
3620 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3621 if dev == DeviceLocation::Cpu {
3622 vec![BackendId::Cpu]
3623 } else {
3624 vec![]
3625 }
3626 };
3627 let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3628 vec![(BackendId::Cuda, cuda0)]
3629 };
3630 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3631 let est = FlatEstimator { latency_ns: 0 };
3632 let cpu_caps_val = cpu_caps();
3633 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3634 let opts = PlanOptions::new()
3635 .with_pinned_device(DeviceLocation::Cpu)
3636 .with_placements_for_device(&placements_fn)
3637 .with_fallback_placements_for(&fallback_fn)
3638 .with_capabilities_for(&caps_fn)
3639 .with_transfer_estimator(&est)
3640 .with_input_residency(&residency_fn);
3641 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3642 assert_eq!(
3643 plan.alternatives(relu).unwrap().winner().unwrap().device,
3644 DeviceLocation::Cpu,
3645 "destructive op stays on the device owning its mutation target",
3646 );
3647 }
3648
3649 #[test]
3654 fn compile_plan_filter_rejected_pinned_device_falls_back() {
3655 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3656 let mut table = KernelBindingTable::new();
3657 register_add_f32(
3660 &mut table,
3661 BackendId::Cuda,
3662 noop_kernel_b,
3663 PrecisionGuarantee {
3664 bit_stable_on_same_hardware: false,
3665 ..PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU
3666 },
3667 );
3668 register_add_f32(
3669 &mut table,
3670 BackendId::Cpu,
3671 noop_kernel,
3672 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3673 );
3674 let mut g = Graph::new();
3675 let lhs = g.push(Node {
3676 op: Op::Const,
3677 inputs: vec![],
3678 shape: Shape::from_dims(&[3]),
3679 dtype: DType::F32,
3680 });
3681 let add = g.push(Node {
3682 op: Op::Add,
3683 inputs: vec![lhs, lhs],
3684 shape: Shape::from_dims(&[3]),
3685 dtype: DType::F32,
3686 });
3687 let order = topo_order(&g, add);
3688 let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
3689 if dev == cuda0 {
3690 vec![BackendId::Cuda]
3691 } else {
3692 vec![]
3693 }
3694 };
3695 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3696 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
3697 };
3698 let opts = PlanOptions::new()
3699 .without_cost_population()
3700 .with_pinned_device(cuda0)
3701 .with_placements_for_device(&placements_fn)
3702 .with_fallback_placements_for(&fallback_fn)
3703 .with_precision_requirement(PrecisionRequirement::BIT_STABLE);
3704 let plan = compile_plan(&g, &order, &table, &opts)
3705 .expect("filter-rejected pin falls back instead of erroring");
3706 let alts = plan.alternatives(add).expect("Add planned via fallback");
3707 assert_eq!(alts.len(), 1, "fallback set frozen to one winner");
3708 let w = alts.winner().unwrap();
3709 assert_eq!(w.backend, BackendId::Cpu);
3710 assert_eq!(w.device, DeviceLocation::Cpu);
3711 assert!(
3712 w.precision.bit_stable_on_same_hardware,
3713 "the admissible off-device sibling won",
3714 );
3715 }
3716
3717 #[test]
3722 fn compile_plan_without_estimator_prices_nothing() {
3723 let mut table = KernelBindingTable::new();
3724 register_add_f32(
3725 &mut table,
3726 BackendId::Cpu,
3727 noop_kernel,
3728 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3729 );
3730 let (g, add_id) = build_add_graph();
3731 let order = topo_order(&g, add_id);
3732 let cpu_caps_val = cpu_caps();
3733 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3734 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3735
3736 let base_opts = PlanOptions::new().with_capabilities_for(&caps_fn);
3737 let base = compile_plan(&g, &order, &table, &base_opts).expect("base");
3738
3739 let with_residency = PlanOptions::new()
3740 .with_capabilities_for(&caps_fn)
3741 .with_input_residency(&residency_fn);
3742 let plan = compile_plan(&g, &order, &table, &with_residency).expect("plan");
3743
3744 let a = base.alternatives(add_id).unwrap();
3745 let b = plan.alternatives(add_id).unwrap();
3746 assert_eq!(a.len(), b.len());
3747 for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
3748 assert_eq!(ca.backend, cb.backend);
3749 assert_eq!(ca.device, cb.device);
3750 assert_eq!(ca.kernel as usize, cb.kernel as usize);
3751 assert_eq!(ca.inbound_transfer_ns, 0);
3752 assert_eq!(cb.inbound_transfer_ns, 0);
3753 }
3754 }
3755
3756 #[test]
3762 fn compile_plan_require_transfer_pricing_errors_without_estimator() {
3763 let mut table = KernelBindingTable::new();
3764 register_add_f32(
3765 &mut table,
3766 BackendId::Cpu,
3767 noop_kernel,
3768 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3769 );
3770 let (g, add_id) = build_add_graph();
3771 let order = topo_order(&g, add_id);
3772 let cpu_caps_val = cpu_caps();
3773 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3774
3775 let opts = PlanOptions::new()
3778 .with_capabilities_for(&caps_fn)
3779 .require_transfer_pricing();
3780 let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
3781 let msg = format!("{err:?}");
3782 assert!(
3783 msg.contains("transfer") && (msg.contains("estimator") || msg.contains("pricing")),
3784 "error should name the missing transfer estimator / pricing; got: {msg}",
3785 );
3786 }
3787
3788 #[test]
3791 fn compile_plan_require_transfer_pricing_ok_with_estimator() {
3792 let mut table = KernelBindingTable::new();
3793 register_add_f32(
3794 &mut table,
3795 BackendId::Cpu,
3796 noop_kernel,
3797 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3798 );
3799 let (g, add_id) = build_add_graph();
3800 let order = topo_order(&g, add_id);
3801 let cpu_caps_val = cpu_caps();
3802 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3803 let est = FlatEstimator { latency_ns: 1000 };
3804
3805 let opts = PlanOptions::new()
3806 .with_capabilities_for(&caps_fn)
3807 .with_transfer_estimator(&est)
3808 .require_transfer_pricing();
3809 let plan = compile_plan(&g, &order, &table, &opts)
3810 .expect("require_transfer_pricing WITH an estimator must plan fine");
3811 assert!(plan.alternatives(add_id).is_some());
3812 }
3813
3814 #[test]
3815 fn compile_plan_passes_input_layouts_to_filter_chain() {
3816 let mut table = KernelBindingTable::new();
3820 table.register_full(
3821 OpKind::AddElementwise,
3822 &[DType::F32, DType::F32, DType::F32],
3823 BackendId::Cpu,
3824 noop_kernel,
3825 KernelCaps::empty(),
3826 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3827 unknown_cost,
3828 );
3829 table.register_full(
3830 OpKind::AddElementwise,
3831 &[DType::F32, DType::F32, DType::F32],
3832 BackendId::Cpu,
3833 noop_kernel_b,
3834 KernelCaps::strided_input(),
3835 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3836 unknown_cost,
3837 );
3838
3839 let mut g = Graph::new();
3841 let lhs = g.push(Node {
3842 op: Op::Const,
3843 inputs: vec![],
3844 shape: Shape::from_dims(&[6]),
3845 dtype: DType::F32,
3846 });
3847 let strides: StrideVec = smallvec![2isize];
3850 g.set_layout(lhs, Layout::new(Shape::from_dims(&[6]), strides, 0));
3851 let rhs = g.push(Node {
3852 op: Op::Const,
3853 inputs: vec![],
3854 shape: Shape::from_dims(&[6]),
3855 dtype: DType::F32,
3856 });
3857 let add = g.push(Node {
3858 op: Op::Add,
3859 inputs: vec![lhs, rhs],
3860 shape: Shape::from_dims(&[6]),
3861 dtype: DType::F32,
3862 });
3863 g.set_target_backend(add, BackendId::Cpu);
3864 let order = topo_order(&g, add);
3865 let opts = PlanOptions::new().without_cost_population();
3866 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3867 let alts = plan.alternatives(add).unwrap();
3868 assert_eq!(alts.len(), 1);
3871 assert!(alts.winner().unwrap().caps.strided_input);
3872 }
3873
3874 struct BytesEstimator {
3881 latency_ns: u64,
3882 ns_per_byte: u64,
3883 }
3884
3885 impl crate::ranker::TransferEstimator for BytesEstimator {
3886 fn estimate_transfer_ns(
3887 &self,
3888 src: DeviceLocation,
3889 dst: DeviceLocation,
3890 bytes: u64,
3891 ) -> u64 {
3892 if src == dst {
3893 return 0;
3894 }
3895 self.latency_ns
3896 .saturating_add(bytes.saturating_mul(self.ns_per_byte))
3897 }
3898 }
3899
3900 fn cost_50(
3901 _: &[Shape],
3902 _: &[DType],
3903 _: &OpParams,
3904 _: &BackendCapabilities,
3905 ) -> crate::fused::CostEstimate {
3906 crate::fused::CostEstimate {
3907 flops: 50,
3908 bytes_moved: 0,
3909 kernel_overhead_ns: 0,
3910 }
3911 }
3912 fn cost_100(
3913 _: &[Shape],
3914 _: &[DType],
3915 _: &OpParams,
3916 _: &BackendCapabilities,
3917 ) -> crate::fused::CostEstimate {
3918 crate::fused::CostEstimate {
3919 flops: 100,
3920 bytes_moved: 0,
3921 kernel_overhead_ns: 0,
3922 }
3923 }
3924 fn cost_300(
3925 _: &[Shape],
3926 _: &[DType],
3927 _: &OpParams,
3928 _: &BackendCapabilities,
3929 ) -> crate::fused::CostEstimate {
3930 crate::fused::CostEstimate {
3931 flops: 300,
3932 bytes_moved: 0,
3933 kernel_overhead_ns: 0,
3934 }
3935 }
3936 fn cost_800(
3937 _: &[Shape],
3938 _: &[DType],
3939 _: &OpParams,
3940 _: &BackendCapabilities,
3941 ) -> crate::fused::CostEstimate {
3942 crate::fused::CostEstimate {
3943 flops: 800,
3944 bytes_moved: 0,
3945 kernel_overhead_ns: 0,
3946 }
3947 }
3948 fn cost_5000(
3949 _: &[Shape],
3950 _: &[DType],
3951 _: &OpParams,
3952 _: &BackendCapabilities,
3953 ) -> crate::fused::CostEstimate {
3954 crate::fused::CostEstimate {
3955 flops: 5000,
3956 bytes_moved: 0,
3957 kernel_overhead_ns: 0,
3958 }
3959 }
3960 fn cost_100_000(
3961 _: &[Shape],
3962 _: &[DType],
3963 _: &OpParams,
3964 _: &BackendCapabilities,
3965 ) -> crate::fused::CostEstimate {
3966 crate::fused::CostEstimate {
3967 flops: 100_000,
3968 bytes_moved: 0,
3969 kernel_overhead_ns: 0,
3970 }
3971 }
3972
3973 fn register_unary_f32(
3975 table: &mut KernelBindingTable,
3976 op: OpKind,
3977 backend: BackendId,
3978 kernel: crate::kernel::KernelRef,
3979 cost: crate::kernel::CostFn,
3980 ) {
3981 table.register_full(
3982 op,
3983 &[DType::F32, DType::F32],
3984 backend,
3985 kernel,
3986 KernelCaps::empty(),
3987 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3988 cost,
3989 );
3990 }
3991
3992 fn push_f32(g: &mut Graph, op: Op, inputs: Vec<NodeId>, dims: &[usize]) -> NodeId {
3993 g.push(Node {
3994 op,
3995 inputs,
3996 shape: Shape::from_dims(dims),
3997 dtype: DType::F32,
3998 })
3999 }
4000
4001 #[test]
4016 fn dp_mid_sequence_gpu_segment_beats_all_cpu_and_all_gpu() {
4017 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4018 let mut table = KernelBindingTable::new();
4019 register_unary_f32(
4020 &mut table,
4021 OpKind::SqrElementwise,
4022 BackendId::Cpu,
4023 noop_kernel,
4024 cost_100,
4025 );
4026 register_unary_f32(
4027 &mut table,
4028 OpKind::SqrElementwise,
4029 BackendId::Cuda,
4030 noop_kernel_b,
4031 cost_5000,
4032 );
4033 register_unary_f32(
4034 &mut table,
4035 OpKind::NegElementwise,
4036 BackendId::Cpu,
4037 noop_kernel,
4038 cost_800,
4039 );
4040 register_unary_f32(
4041 &mut table,
4042 OpKind::NegElementwise,
4043 BackendId::Cuda,
4044 noop_kernel_b,
4045 cost_100,
4046 );
4047
4048 let mut g = Graph::new();
4049 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4050 let n1 = push_f32(&mut g, Op::Sqr, vec![c], &[4]);
4051 let n2 = push_f32(&mut g, Op::Neg, vec![n1], &[4]);
4052 let n3 = push_f32(&mut g, Op::Neg, vec![n2], &[4]);
4053 let n4 = push_f32(&mut g, Op::Neg, vec![n3], &[4]);
4054 let n5 = push_f32(&mut g, Op::Sqr, vec![n4], &[4]);
4055 let order = topo_order(&g, n5);
4056
4057 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4058 if dev == DeviceLocation::Cpu {
4059 vec![BackendId::Cpu]
4060 } else {
4061 vec![BackendId::Cuda]
4062 }
4063 };
4064 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4065 if dev == DeviceLocation::Cpu {
4066 vec![(BackendId::Cuda, cuda0)]
4067 } else {
4068 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4069 }
4070 };
4071 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4072 (id == c).then_some(DeviceLocation::Cpu)
4073 };
4074 let est = FlatEstimator { latency_ns: 1_000 };
4075 let cpu_caps_val = cpu_caps();
4076 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4077 let opts = PlanOptions::new()
4078 .with_pinned_device(DeviceLocation::Cpu)
4079 .with_placements_for_device(&placements_fn)
4080 .with_fallback_placements_for(&fallback_fn)
4081 .with_capabilities_for(&caps_fn)
4082 .with_transfer_estimator(&est)
4083 .with_input_residency(&residency_fn);
4084 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4085
4086 let dev_of = |id: NodeId| plan.alternatives(id).unwrap().winner().unwrap().device;
4087 assert_eq!(
4088 dev_of(n1),
4089 DeviceLocation::Cpu,
4090 "GPU-hostile entry stays CPU"
4091 );
4092 assert_eq!(dev_of(n2), cuda0, "segment start migrates");
4093 assert_eq!(dev_of(n3), cuda0, "segment interior stays GPU");
4094 assert_eq!(dev_of(n4), cuda0, "segment end stays GPU");
4095 assert_eq!(dev_of(n5), DeviceLocation::Cpu, "GPU-hostile exit returns");
4096
4097 let inbound = |id: NodeId| {
4101 plan.alternatives(id)
4102 .unwrap()
4103 .winner()
4104 .unwrap()
4105 .inbound_transfer_ns
4106 };
4107 assert_eq!(
4108 inbound(n2),
4109 1_000,
4110 "entry crossing priced on the first GPU op"
4111 );
4112 assert_eq!(inbound(n3), 0);
4113 assert_eq!(inbound(n4), 0);
4114 assert_eq!(inbound(n5), 1_000, "exit crossing priced on the return op");
4115
4116 for id in [n1, n2, n3, n4, n5] {
4119 let d = dev_of(id);
4120 assert!(
4121 plan.alternatives(id)
4122 .unwrap()
4123 .alternatives()
4124 .iter()
4125 .all(|c| c.device == d),
4126 "set pruned to the DP-committed device",
4127 );
4128 }
4129 }
4130
4131 #[test]
4147 fn dp_fused_op_loses_when_stranding_exceeds_local_win() {
4148 use fuel_graph::registry::{FusedOpParams, FusedOps};
4149
4150 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4151 let mut table = KernelBindingTable::new();
4152 register_unary_f32(
4153 &mut table,
4154 OpKind::NegElementwise,
4155 BackendId::Cpu,
4156 noop_kernel,
4157 cost_100_000,
4158 );
4159 register_unary_f32(
4160 &mut table,
4161 OpKind::NegElementwise,
4162 BackendId::Cuda,
4163 noop_kernel_b,
4164 cost_100,
4165 );
4166 register_unary_f32(
4167 &mut table,
4168 OpKind::SoftmaxLastDim,
4169 BackendId::Cpu,
4170 noop_kernel,
4171 cost_300,
4172 );
4173 register_unary_f32(
4174 &mut table,
4175 OpKind::SoftmaxLastDim,
4176 BackendId::Cuda,
4177 noop_kernel_b,
4178 cost_100,
4179 );
4180 register_unary_f32(
4182 &mut table,
4183 OpKind::SqrElementwise,
4184 BackendId::Cpu,
4185 noop_kernel,
4186 cost_100,
4187 );
4188
4189 let mut g = Graph::new();
4190 let c = push_f32(&mut g, Op::Const, vec![], &[1]);
4191 let n1 = push_f32(&mut g, Op::Neg, vec![c], &[1]);
4192 let f = push_f32(
4193 &mut g,
4194 Op::Fused(FusedOps::SOFTMAX_LAST_DIM, FusedOpParams::SoftmaxLastDim),
4195 vec![n1],
4196 &[256],
4197 );
4198 let n2 = push_f32(&mut g, Op::Sqr, vec![f], &[256]);
4199 let order = topo_order(&g, n2);
4200
4201 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4202 if dev == DeviceLocation::Cpu {
4203 vec![BackendId::Cpu]
4204 } else {
4205 vec![BackendId::Cuda]
4206 }
4207 };
4208 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4209 if dev == DeviceLocation::Cpu {
4210 vec![(BackendId::Cuda, cuda0)]
4211 } else {
4212 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4213 }
4214 };
4215 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4216 (id == c).then_some(DeviceLocation::Cpu)
4217 };
4218 let est = BytesEstimator {
4219 latency_ns: 10,
4220 ns_per_byte: 1,
4221 };
4222 let cpu_caps_val = cpu_caps();
4223 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4224 let opts = PlanOptions::new()
4225 .with_pinned_device(DeviceLocation::Cpu)
4226 .with_placements_for_device(&placements_fn)
4227 .with_fallback_placements_for(&fallback_fn)
4228 .with_capabilities_for(&caps_fn)
4229 .with_transfer_estimator(&est)
4230 .with_input_residency(&residency_fn);
4231 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4232
4233 let dev_of = |id: NodeId| plan.alternatives(id).unwrap().winner().unwrap().device;
4234 assert_eq!(dev_of(n1), cuda0, "the huge-win producer migrates");
4235 assert_eq!(
4236 dev_of(f),
4237 DeviceLocation::Cpu,
4238 "the locally-faster fused op stays where its output is needed",
4239 );
4240 assert_eq!(dev_of(n2), DeviceLocation::Cpu);
4241 assert!(
4242 plan.alternatives(f)
4243 .unwrap()
4244 .alternatives()
4245 .iter()
4246 .all(|c| c.device == DeviceLocation::Cpu),
4247 "fused set pruned to the committed device",
4248 );
4249 }
4250
4251 #[test]
4259 fn dp_exit_pricing_keeps_final_op_on_realize_target() {
4260 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4261 let mut table = KernelBindingTable::new();
4262 register_unary_f32(
4263 &mut table,
4264 OpKind::NegElementwise,
4265 BackendId::Cpu,
4266 noop_kernel,
4267 cost_50,
4268 );
4269 register_unary_f32(
4270 &mut table,
4271 OpKind::NegElementwise,
4272 BackendId::Cuda,
4273 noop_kernel_b,
4274 cost_100,
4275 );
4276
4277 let mut g = Graph::new();
4278 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4279 let n = push_f32(&mut g, Op::Neg, vec![c], &[4]);
4280 let order = topo_order(&g, n);
4281
4282 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4283 if dev == DeviceLocation::Cpu {
4284 vec![BackendId::Cpu]
4285 } else {
4286 vec![BackendId::Cuda]
4287 }
4288 };
4289 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4290 if dev == DeviceLocation::Cpu {
4291 vec![(BackendId::Cuda, cuda0)]
4292 } else {
4293 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4294 }
4295 };
4296 let residency_fn =
4297 move |id: NodeId| -> Option<DeviceLocation> { (id == c).then_some(cuda0) };
4298 let est = FlatEstimator { latency_ns: 1_000 };
4299 let cpu_caps_val = cpu_caps();
4300 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4301 let opts = PlanOptions::new()
4302 .with_pinned_device(DeviceLocation::Cpu)
4303 .with_placements_for_device(&placements_fn)
4304 .with_fallback_placements_for(&fallback_fn)
4305 .with_capabilities_for(&caps_fn)
4306 .with_transfer_estimator(&est)
4307 .with_input_residency(&residency_fn);
4308 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4309 let w = plan.alternatives(n).unwrap().winner().unwrap();
4310 assert_eq!(
4311 w.device,
4312 DeviceLocation::Cpu,
4313 "exit pricing flips the locally-winning GPU placement",
4314 );
4315 assert_eq!(
4316 w.inbound_transfer_ns, 1_000,
4317 "the GPU-resident input's crossing is priced on the CPU winner",
4318 );
4319 }
4320
4321 #[test]
4324 fn dp_exit_pricing_does_not_pin_when_kernel_gap_dominates() {
4325 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4326 let mut table = KernelBindingTable::new();
4327 register_unary_f32(
4328 &mut table,
4329 OpKind::NegElementwise,
4330 BackendId::Cpu,
4331 noop_kernel,
4332 cost_10_000_000,
4333 );
4334 register_unary_f32(
4335 &mut table,
4336 OpKind::NegElementwise,
4337 BackendId::Cuda,
4338 noop_kernel_b,
4339 cost_100,
4340 );
4341
4342 let mut g = Graph::new();
4343 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4344 let n = push_f32(&mut g, Op::Neg, vec![c], &[4]);
4345 let order = topo_order(&g, n);
4346
4347 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4348 if dev == DeviceLocation::Cpu {
4349 vec![BackendId::Cpu]
4350 } else {
4351 vec![BackendId::Cuda]
4352 }
4353 };
4354 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4355 if dev == DeviceLocation::Cpu {
4356 vec![(BackendId::Cuda, cuda0)]
4357 } else {
4358 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4359 }
4360 };
4361 let residency_fn =
4362 move |id: NodeId| -> Option<DeviceLocation> { (id == c).then_some(cuda0) };
4363 let est = FlatEstimator { latency_ns: 1_000 };
4364 let cpu_caps_val = cpu_caps();
4365 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4366 let opts = PlanOptions::new()
4367 .with_pinned_device(DeviceLocation::Cpu)
4368 .with_placements_for_device(&placements_fn)
4369 .with_fallback_placements_for(&fallback_fn)
4370 .with_capabilities_for(&caps_fn)
4371 .with_transfer_estimator(&est)
4372 .with_input_residency(&residency_fn);
4373 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4374 assert_eq!(
4375 plan.alternatives(n).unwrap().winner().unwrap().device,
4376 cuda0
4377 );
4378 }
4379
4380 #[test]
4386 fn dp_single_device_plan_equals_greedy_plan() {
4387 let mut table = KernelBindingTable::new();
4388 register_add_f32(
4389 &mut table,
4390 BackendId::Cpu,
4391 noop_kernel,
4392 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4393 );
4394 register_add_f32(
4395 &mut table,
4396 BackendId::Cuda,
4397 noop_kernel_b,
4398 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4399 );
4400 let (g, add_id) = build_add_graph();
4401 let order = topo_order(&g, add_id);
4402 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4405 if dev == DeviceLocation::Cpu {
4406 vec![BackendId::Cpu, BackendId::Cuda]
4407 } else {
4408 vec![]
4409 }
4410 };
4411 let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> { Vec::new() };
4412 let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
4413 let cpu_caps_val = cpu_caps();
4414 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4415
4416 let base_opts = PlanOptions::new()
4417 .with_placements_for_device(&placements_fn)
4418 .with_capabilities_for(&caps_fn);
4419 let base = compile_plan(&g, &order, &table, &base_opts).expect("base");
4420
4421 let est = FlatEstimator {
4422 latency_ns: 1_000_000,
4423 };
4424 let wired_opts = PlanOptions::new()
4425 .with_placements_for_device(&placements_fn)
4426 .with_fallback_placements_for(&fallback_fn)
4427 .with_capabilities_for(&caps_fn)
4428 .with_transfer_estimator(&est)
4429 .with_input_residency(&residency_fn);
4430 let wired = compile_plan(&g, &order, &table, &wired_opts).expect("wired");
4431
4432 assert_eq!(base.alternatives.len(), wired.alternatives.len());
4433 let a = base.alternatives(add_id).unwrap();
4434 let b = wired.alternatives(add_id).unwrap();
4435 assert_eq!(a.len(), b.len(), "same candidate count");
4436 for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
4437 assert_eq!(ca.backend, cb.backend);
4438 assert_eq!(ca.device, cb.device);
4439 assert_eq!(ca.kernel as usize, cb.kernel as usize, "same kernel ref");
4440 assert_eq!(ca.static_cost, cb.static_cost, "same Layer-1 cost");
4441 assert_eq!(cb.inbound_transfer_ns, 0, "no transfer term fires");
4442 }
4443 assert_eq!(a.context(), b.context(), "same decision context");
4444 }
4445
4446 fn run_diamond_regime(latency_ns: u64, expect: DeviceLocation) {
4450 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4451 let mut table = KernelBindingTable::new();
4452 for op in [
4453 OpKind::NegElementwise,
4454 OpKind::SqrElementwise,
4455 OpKind::ReluElementwise,
4456 ] {
4457 register_unary_f32(&mut table, op, BackendId::Cpu, noop_kernel, cost_100);
4458 register_unary_f32(&mut table, op, BackendId::Cuda, noop_kernel_b, cost_10);
4459 }
4460 table.register_full(
4461 OpKind::AddElementwise,
4462 &[DType::F32, DType::F32, DType::F32],
4463 BackendId::Cpu,
4464 noop_kernel,
4465 KernelCaps::empty(),
4466 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4467 cost_100,
4468 );
4469 table.register_full(
4470 OpKind::AddElementwise,
4471 &[DType::F32, DType::F32, DType::F32],
4472 BackendId::Cuda,
4473 noop_kernel_b,
4474 KernelCaps::empty(),
4475 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4476 cost_10,
4477 );
4478
4479 let mut g = Graph::new();
4480 let c0 = push_f32(&mut g, Op::Const, vec![], &[4]);
4481 let a = push_f32(&mut g, Op::Neg, vec![c0], &[4]);
4482 let b = push_f32(&mut g, Op::Sqr, vec![a], &[4]);
4483 let c2 = push_f32(&mut g, Op::Relu, vec![a], &[4]);
4484 let d = push_f32(&mut g, Op::Add, vec![b, c2], &[4]);
4485 let order = topo_order(&g, d);
4486
4487 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4488 if dev == DeviceLocation::Cpu {
4489 vec![BackendId::Cpu]
4490 } else {
4491 vec![BackendId::Cuda]
4492 }
4493 };
4494 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4495 if dev == DeviceLocation::Cpu {
4496 vec![(BackendId::Cuda, cuda0)]
4497 } else {
4498 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4499 }
4500 };
4501 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4502 (id == c0).then_some(DeviceLocation::Cpu)
4503 };
4504 let est = FlatEstimator { latency_ns };
4505 let cpu_caps_val = cpu_caps();
4506 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4507 let opts = PlanOptions::new()
4508 .with_pinned_device(DeviceLocation::Cpu)
4509 .with_placements_for_device(&placements_fn)
4510 .with_fallback_placements_for(&fallback_fn)
4511 .with_capabilities_for(&caps_fn)
4512 .with_transfer_estimator(&est)
4513 .with_input_residency(&residency_fn);
4514 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4515 for id in [a, b, c2, d] {
4516 assert_eq!(
4517 plan.alternatives(id).unwrap().winner().unwrap().device,
4518 expect,
4519 "diamond join must commit a consistent placement",
4520 );
4521 }
4522 }
4523
4524 #[test]
4529 fn dp_diamond_join_merges_consistently() {
4530 run_diamond_regime(1_000_000, DeviceLocation::Cpu);
4532 run_diamond_regime(0, DeviceLocation::Cuda { gpu_id: 0 });
4534 }
4535
4536 #[test]
4542 fn dp_thousand_node_chain_plans_within_sanity_bound() {
4543 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4544 let mut table = KernelBindingTable::new();
4545 register_unary_f32(
4548 &mut table,
4549 OpKind::NegElementwise,
4550 BackendId::Cpu,
4551 noop_kernel,
4552 cost_100,
4553 );
4554 register_unary_f32(
4555 &mut table,
4556 OpKind::NegElementwise,
4557 BackendId::Cuda,
4558 noop_kernel_b,
4559 cost_100,
4560 );
4561
4562 let mut g = Graph::new();
4563 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4564 let mut prev = c;
4565 let mut nodes = Vec::with_capacity(1000);
4566 for _ in 0..1000 {
4567 let n = push_f32(&mut g, Op::Neg, vec![prev], &[4]);
4568 nodes.push(n);
4569 prev = n;
4570 }
4571 let order = topo_order(&g, prev);
4572
4573 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4574 if dev == DeviceLocation::Cpu {
4575 vec![BackendId::Cpu]
4576 } else {
4577 vec![BackendId::Cuda]
4578 }
4579 };
4580 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4581 if dev == DeviceLocation::Cpu {
4582 vec![(BackendId::Cuda, cuda0)]
4583 } else {
4584 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4585 }
4586 };
4587 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4588 (id == c).then_some(DeviceLocation::Cpu)
4589 };
4590 let est = FlatEstimator { latency_ns: 10 };
4591 let cpu_caps_val = cpu_caps();
4592 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4593 let opts = PlanOptions::new()
4594 .with_pinned_device(DeviceLocation::Cpu)
4595 .with_placements_for_device(&placements_fn)
4596 .with_fallback_placements_for(&fallback_fn)
4597 .with_capabilities_for(&caps_fn)
4598 .with_transfer_estimator(&est)
4599 .with_input_residency(&residency_fn);
4600
4601 let start = std::time::Instant::now();
4602 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4603 let elapsed = start.elapsed();
4604 assert!(
4605 elapsed.as_secs() < 5,
4606 "1000-node DP plan took {elapsed:?} — pathological scaling",
4607 );
4608
4609 assert_eq!(plan.alternatives.len(), 1000);
4610 for &n in &nodes {
4611 assert_eq!(
4612 plan.alternatives(n).unwrap().winner().unwrap().device,
4613 DeviceLocation::Cpu,
4614 "equal-cost ties break toward the decision device end-to-end",
4615 );
4616 }
4617 }
4618
4619 #[test]
4623 fn dp_chain_connects_through_view_passthroughs() {
4624 let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4625 let mut table = KernelBindingTable::new();
4626 register_unary_f32(
4630 &mut table,
4631 OpKind::NegElementwise,
4632 BackendId::Cpu,
4633 noop_kernel,
4634 cost_800,
4635 );
4636 register_unary_f32(
4637 &mut table,
4638 OpKind::NegElementwise,
4639 BackendId::Cuda,
4640 noop_kernel_b,
4641 cost_100,
4642 );
4643
4644 let mut g = Graph::new();
4645 let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4646 let n1 = push_f32(&mut g, Op::Neg, vec![c], &[4]);
4647 let r = push_f32(
4648 &mut g,
4649 Op::Reshape(Shape::from_dims(&[2, 2])),
4650 vec![n1],
4651 &[2, 2],
4652 );
4653 let n2 = push_f32(&mut g, Op::Neg, vec![r], &[2, 2]);
4654 let n3 = push_f32(&mut g, Op::Neg, vec![n2], &[2, 2]);
4655 let order = topo_order(&g, n3);
4656
4657 let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4658 if dev == DeviceLocation::Cpu {
4659 vec![BackendId::Cpu]
4660 } else {
4661 vec![BackendId::Cuda]
4662 }
4663 };
4664 let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4665 if dev == DeviceLocation::Cpu {
4666 vec![(BackendId::Cuda, cuda0)]
4667 } else {
4668 vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4669 }
4670 };
4671 let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4672 (id == c).then_some(DeviceLocation::Cpu)
4673 };
4674 let est = FlatEstimator { latency_ns: 1_000 };
4675 let cpu_caps_val = cpu_caps();
4676 let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4677 let opts = PlanOptions::new()
4678 .with_pinned_device(DeviceLocation::Cpu)
4679 .with_placements_for_device(&placements_fn)
4680 .with_fallback_placements_for(&fallback_fn)
4681 .with_capabilities_for(&caps_fn)
4682 .with_transfer_estimator(&est)
4683 .with_input_residency(&residency_fn);
4684 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4685
4686 for id in [n1, n2, n3] {
4690 assert_eq!(
4691 plan.alternatives(id).unwrap().winner().unwrap().device,
4692 cuda0,
4693 "the chain must not break at the Reshape pass-through",
4694 );
4695 }
4696 assert!(
4697 plan.alternatives(r).is_none(),
4698 "Reshape carries no plan entry"
4699 );
4700 }
4701
4702 #[cfg(feature = "telemetry")]
4707 mod telemetry_wiring {
4708 use super::*;
4709 use crate::telemetry::{
4710 Contiguity, FdxOperandDesc, HwStamp, StructureKeyProvider, StructureKeyToken,
4711 TelemetryConfig, TelemetryHooks, TelemetryMode, TelemetrySink,
4712 };
4713 use std::sync::Mutex;
4714
4715 struct StubProvider;
4719 impl StructureKeyProvider for StubProvider {
4720 fn structure_key(
4721 &self,
4722 op_class: &str,
4723 operands: &[FdxOperandDesc],
4724 _arch: &str,
4725 ) -> Option<StructureKeyToken> {
4726 Some(StructureKeyToken(format!(
4727 "{op_class}:stub:n={}",
4728 operands.len()
4729 )))
4730 }
4731 }
4732
4733 fn cpu_hw() -> HwStamp {
4734 HwStamp {
4735 compute_capability: None,
4736 hardware_sku: "test-cpu".into(),
4737 driver_version: "n/a".into(),
4738 }
4739 }
4740
4741 #[test]
4746 fn a_matmul_node_reaches_the_contraction_derivation() {
4747 let mut table = KernelBindingTable::new();
4748 table.register_full_with_source_generic(
4749 OpKind::MatMul,
4750 &[DType::F32, DType::F32, DType::F32],
4751 BackendId::Cpu,
4752 noop_kernel,
4753 KernelCaps::strided_input(),
4754 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4755 unknown_cost,
4756 "test-matmul",
4757 false,
4758 0,
4759 None,
4760 );
4761 let mut g = Graph::new();
4762 let mut konst = |dims: &[usize]| {
4763 g.push(Node {
4764 op: Op::Const,
4765 inputs: vec![],
4766 shape: Shape::from_dims(dims),
4767 dtype: DType::F32,
4768 })
4769 };
4770 let (lhs, rhs) = (konst(&[8, 64]), konst(&[64, 16]));
4771 let mm = g.push(Node {
4772 op: Op::MatMul,
4773 inputs: vec![lhs, rhs],
4774 shape: Shape::from_dims(&[8, 16]),
4775 dtype: DType::F32,
4776 });
4777 let order = topo_order(&g, mm);
4778 let sink = Mutex::new(TelemetrySink::new());
4779 let provider = StubProvider;
4780 let config = TelemetryConfig {
4781 mode: TelemetryMode::Coarse,
4782 out_path: None,
4783 };
4784 let hw = HwStamp {
4785 compute_capability: Some((8, 9)),
4786 hardware_sku: "test-cuda".into(),
4787 driver_version: "n/a".into(),
4788 };
4789 let hooks = TelemetryHooks {
4790 config: &config,
4791 sink: &sink,
4792 provider: &provider,
4793 hw,
4794 };
4795 let opts = PlanOptions::new()
4796 .without_cost_population()
4797 .with_pinned_device(DeviceLocation::Cpu)
4798 .with_telemetry(&hooks);
4799 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4800 let keys = sink
4801 .into_inner()
4802 .expect("sink lock")
4803 .derived_contraction_keys();
4804 assert_eq!(keys.len(), 1, "{keys:?}");
4805 assert!(keys[0].0.starts_with("sk8|ctr|f32|cuda:sm89|"), "{keys:?}");
4806 assert_eq!(keys[0].1, 1);
4807 }
4808
4809 fn generic_only_add_table() -> KernelBindingTable {
4814 let mut table = KernelBindingTable::new();
4815 table.register_full_with_source_generic(
4816 OpKind::AddElementwise,
4817 &[DType::F32, DType::F32, DType::F32],
4818 BackendId::Cpu,
4819 noop_kernel,
4820 KernelCaps::strided_input(),
4821 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4822 unknown_cost,
4823 "baracuda-generic-strided",
4824 true, 0, None, );
4828 table
4829 }
4830
4831 #[test]
4843 fn generic_only_cell_emits_one_aggregated_miss_through_compile_plan() {
4844 let table = generic_only_add_table();
4845 let (g, add_id) = build_add_graph();
4846 let order = topo_order(&g, add_id);
4847
4848 let sink = Mutex::new(TelemetrySink::new());
4849 let provider = StubProvider;
4850 let config = TelemetryConfig {
4851 mode: TelemetryMode::Coarse,
4852 out_path: None,
4853 };
4854 let hooks = TelemetryHooks {
4855 config: &config,
4856 sink: &sink,
4857 provider: &provider,
4858 hw: cpu_hw(),
4859 };
4860 let opts = PlanOptions::new()
4861 .without_cost_population()
4862 .with_telemetry(&hooks);
4863 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4864
4865 let sink = sink.into_inner().expect("sink lock");
4866 assert_eq!(
4867 sink.miss_cell_count(),
4868 1,
4869 "a generic-only cell must emit exactly one aggregated miss cell",
4870 );
4871 let recs = sink.miss_records();
4872 assert_eq!(recs.len(), 1);
4873 assert_eq!(
4877 recs[0].wanted,
4878 StructureKeyToken("AddElementwise:stub:n=3".into()),
4879 "the wanted token must reflect the live op_class + operands",
4880 );
4881 assert_eq!(recs[0].fallback.kernel_source, "baracuda-generic-strided");
4882 assert_eq!(recs[0].fallback.op, OpKind::AddElementwise);
4883 assert_eq!(recs[0].fallback.backend, BackendId::Cpu);
4884 assert_eq!(
4885 recs[0].fallback.dtypes,
4886 vec![DType::F32, DType::F32, DType::F32],
4887 );
4888 assert_eq!(recs[0].count, 1);
4889 assert_eq!(recs[0].hw, cpu_hw());
4890 }
4891
4892 #[test]
4898 fn telemetry_off_emits_nothing_and_does_not_change_the_plan() {
4899 let table = generic_only_add_table();
4900 let (g, add_id) = build_add_graph();
4901 let order = topo_order(&g, add_id);
4902
4903 let sink = Mutex::new(TelemetrySink::new());
4904 let provider = StubProvider;
4905 let config = TelemetryConfig::default(); let hooks = TelemetryHooks {
4907 config: &config,
4908 sink: &sink,
4909 provider: &provider,
4910 hw: cpu_hw(),
4911 };
4912 let opts = PlanOptions::new()
4913 .without_cost_population()
4914 .with_telemetry(&hooks);
4915 let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4916
4917 assert!(
4918 sink.into_inner().expect("sink lock").is_empty(),
4919 "Off mode must emit nothing",
4920 );
4921 let alts = plan.alternatives(add_id).expect("Add alternatives present");
4923 assert_eq!(alts.len(), 1);
4924 assert_eq!(alts.winner().unwrap().backend, BackendId::Cpu);
4925 }
4926
4927 #[test]
4932 fn specialized_winner_emits_no_miss() {
4933 let mut table = KernelBindingTable::new();
4934 register_add_f32(
4936 &mut table,
4937 BackendId::Cpu,
4938 noop_kernel,
4939 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4940 );
4941 let (g, add_id) = build_add_graph();
4942 let order = topo_order(&g, add_id);
4943
4944 let sink = Mutex::new(TelemetrySink::new());
4945 let provider = StubProvider;
4946 let config = TelemetryConfig {
4947 mode: TelemetryMode::Coarse,
4948 out_path: None,
4949 };
4950 let hooks = TelemetryHooks {
4951 config: &config,
4952 sink: &sink,
4953 provider: &provider,
4954 hw: cpu_hw(),
4955 };
4956 let opts = PlanOptions::new()
4957 .without_cost_population()
4958 .with_telemetry(&hooks);
4959 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4960
4961 let sink = sink.into_inner().expect("sink lock");
4962 assert!(
4963 sink.miss_records().is_empty(),
4964 "a specialized (is_generic=false) winner must emit no miss",
4965 );
4966 assert_eq!(
4970 sink.dispatch_cell_count(),
4971 1,
4972 "a specialized winner still emits its dispatch record",
4973 );
4974 let _ = add_id;
4975 }
4976
4977 fn two_sibling_add_table() -> KernelBindingTable {
4985 let mut table = KernelBindingTable::new();
4986 table.register_full_with_source(
4987 OpKind::AddElementwise,
4988 &[DType::F32, DType::F32, DType::F32],
4989 BackendId::Cpu,
4990 noop_kernel,
4991 KernelCaps::empty(),
4992 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4993 unknown_cost,
4994 "portable-cpu",
4995 );
4996 table.register_full_with_source(
4997 OpKind::AddElementwise,
4998 &[DType::F32, DType::F32, DType::F32],
4999 BackendId::Cpu,
5000 noop_kernel_b,
5001 KernelCaps::empty(),
5002 PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
5003 unknown_cost,
5004 "aocl",
5005 );
5006 table
5007 }
5008
5009 #[test]
5021 fn detailed_dispatch_record_emitted_with_per_candidate_judge_latency() {
5022 use crate::ranker::HashMapJudge;
5023 use fuel_ir::dispatch::SizeClass;
5024
5025 let table = two_sibling_add_table();
5026 let (g, add_id) = build_add_graph();
5027 let order = topo_order(&g, add_id);
5028
5029 let sc = SizeClass::from_elem_count(3);
5033 let mut judge = HashMapJudge::new();
5034 judge.insert(
5035 OpKind::AddElementwise,
5036 DType::F32,
5037 sc,
5038 BackendId::Cpu,
5039 "portable-cpu",
5040 41_230,
5041 0,
5042 );
5043
5044 let sink = Mutex::new(TelemetrySink::new());
5045 let provider = StubProvider;
5046 let config = TelemetryConfig {
5047 mode: TelemetryMode::Detailed,
5048 out_path: None,
5049 };
5050 let hooks = TelemetryHooks {
5051 config: &config,
5052 sink: &sink,
5053 provider: &provider,
5054 hw: cpu_hw(),
5055 };
5056 let opts = PlanOptions::new()
5057 .without_cost_population()
5058 .with_telemetry(&hooks)
5059 .with_judge(&judge);
5060 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
5061
5062 let sink = sink.into_inner().expect("sink lock");
5063 assert_eq!(
5064 sink.dispatch_cell_count(),
5065 1,
5066 "one planned cell ⇒ exactly one aggregated dispatch record",
5067 );
5068 assert_eq!(
5069 sink.miss_cell_count(),
5070 0,
5071 "specialized winners emit no miss"
5072 );
5073 let recs = sink.dispatch_records();
5074 assert_eq!(recs.len(), 1);
5075 let rec = &recs[0];
5076 assert_eq!(rec.chosen.kernel_source, "portable-cpu");
5078 assert_eq!(rec.chosen.op, OpKind::AddElementwise);
5079 assert_eq!(rec.chosen.backend, BackendId::Cpu);
5080 assert_eq!(rec.chosen.dtypes, vec![DType::F32, DType::F32, DType::F32]);
5081 assert_eq!(
5082 rec.chosen.kernel_revision_hash, 0,
5083 "hand-written ⇒ untracked"
5084 );
5085 assert_eq!(rec.count, 1);
5086 assert_eq!(rec.hw, cpu_hw());
5087 assert_eq!(
5090 rec.structure_key,
5091 Some(StructureKeyToken("AddElementwise:stub:n=3".into())),
5092 );
5093 assert_eq!(rec.candidates.len(), 2, "both admitted alternatives appear");
5096 let by_src = |src: &str| {
5097 rec.candidates
5098 .iter()
5099 .find(|c| c.impl_id.kernel_source == src)
5100 .unwrap_or_else(|| panic!("candidate {src} present"))
5101 };
5102 assert_eq!(
5103 by_src("portable-cpu").latency_ns,
5104 Some(41_230),
5105 "the measured winner carries its own ns",
5106 );
5107 assert_eq!(
5108 by_src("aocl").latency_ns,
5109 None,
5110 "the unmeasured sibling is None, never a fabricated 0",
5111 );
5112 }
5113
5114 #[test]
5118 fn coarse_dispatch_record_has_no_candidates() {
5119 let table = two_sibling_add_table();
5120 let (g, add_id) = build_add_graph();
5121 let order = topo_order(&g, add_id);
5122
5123 let sink = Mutex::new(TelemetrySink::new());
5124 let provider = StubProvider;
5125 let config = TelemetryConfig {
5126 mode: TelemetryMode::Coarse,
5127 out_path: None,
5128 };
5129 let hooks = TelemetryHooks {
5130 config: &config,
5131 sink: &sink,
5132 provider: &provider,
5133 hw: cpu_hw(),
5134 };
5135 let opts = PlanOptions::new()
5136 .without_cost_population()
5137 .with_telemetry(&hooks);
5138 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
5139
5140 let sink = sink.into_inner().expect("sink lock");
5141 assert_eq!(
5142 sink.dispatch_cell_count(),
5143 1,
5144 "Coarse still emits the chosen signal"
5145 );
5146 let recs = sink.dispatch_records();
5147 assert!(
5148 recs[0].candidates.is_empty(),
5149 "Coarse omits candidates (no Judge reads)"
5150 );
5151 assert_eq!(recs[0].chosen.kernel_source, "portable-cpu");
5152 assert_eq!(recs[0].count, 1);
5153 }
5154
5155 #[test]
5158 fn telemetry_off_emits_no_dispatch_record() {
5159 let table = two_sibling_add_table();
5160 let (g, add_id) = build_add_graph();
5161 let order = topo_order(&g, add_id);
5162
5163 let sink = Mutex::new(TelemetrySink::new());
5164 let provider = StubProvider;
5165 let config = TelemetryConfig::default(); let hooks = TelemetryHooks {
5167 config: &config,
5168 sink: &sink,
5169 provider: &provider,
5170 hw: cpu_hw(),
5171 };
5172 let opts = PlanOptions::new()
5173 .without_cost_population()
5174 .with_telemetry(&hooks);
5175 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
5176
5177 assert!(
5178 sink.into_inner().expect("sink lock").is_empty(),
5179 "Off emits neither dispatch nor miss",
5180 );
5181 let _ = add_id;
5182 }
5183
5184 struct RecordingProvider {
5193 seen: Mutex<Vec<FdxOperandDesc>>,
5194 }
5195 impl StructureKeyProvider for RecordingProvider {
5196 fn structure_key(
5197 &self,
5198 op_class: &str,
5199 operands: &[FdxOperandDesc],
5200 _arch: &str,
5201 ) -> Option<StructureKeyToken> {
5202 *self.seen.lock().expect("record lock") = operands.to_vec();
5203 Some(StructureKeyToken(format!(
5204 "{op_class}:n={}",
5205 operands.len()
5206 )))
5207 }
5208 }
5209
5210 #[test]
5220 fn structure_key_operand_slice_folds_in_the_output() {
5221 let table = generic_only_add_table();
5222 let (g, add_id) = build_add_graph();
5223 let order = topo_order(&g, add_id);
5224
5225 let sink = Mutex::new(TelemetrySink::new());
5226 let provider = RecordingProvider {
5227 seen: Mutex::new(Vec::new()),
5228 };
5229 let config = TelemetryConfig {
5230 mode: TelemetryMode::Coarse,
5231 out_path: None,
5232 };
5233 let hooks = TelemetryHooks {
5234 config: &config,
5235 sink: &sink,
5236 provider: &provider,
5237 hw: cpu_hw(),
5238 };
5239 let opts = PlanOptions::new()
5240 .without_cost_population()
5241 .with_telemetry(&hooks);
5242 let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
5243
5244 let seen = provider.seen.into_inner().expect("record lock");
5245 assert_eq!(
5247 seen.len(),
5248 3,
5249 "operand slice must be node inputs (2) then the output (1)",
5250 );
5251 let out = seen.last().expect("output operand present");
5252 assert_eq!(
5254 out.dtype,
5255 DType::F32,
5256 "output operand carries the node dtype"
5257 );
5258 assert_eq!(
5259 out.shape,
5260 vec![3i64],
5261 "output operand carries the node shape"
5262 );
5263 assert_eq!(
5264 out.contiguity,
5265 Contiguity::Contiguous,
5266 "the Add output is contiguous",
5267 );
5268 let _ = add_id;
5269 }
5270 }
5271}