fuel_ir/probe.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Cross-backend device enumeration — the foundation for Phase 6b's
3//! `probe → judge → dispatch` lifecycle.
4//!
5//! # Why
6//!
7//! Fuel dispatches ops across multiple backends (CPU, reference, CUDA,
8//! Vulkan, later Metal / MKL / AOCL). Each backend may see zero, one,
9//! or many physical devices. A single physical GPU may be reachable
10//! through more than one backend (an NVIDIA card is visible to both
11//! CUDA and Vulkan) and will produce meaningfully different
12//! performance profiles depending on which backend routes it. The
13//! profiling unit — and therefore the dispatch-table key — is not
14//! "backend" but `(backend, device)`.
15//!
16//! This module defines the data types that represent that pair in a
17//! persistence-friendly shape. The actual enumeration logic lives in
18//! each backend crate (a free function `enumerate_devices() ->
19//! Result<Vec<DeviceDescriptor>>`, not a trait method — see "Why a
20//! convention, not a trait" below). A top-level collector in
21//! `fuel-graph-router` (or a future `fuel-judge`) calls every
22//! backend's enumerator and assembles the combined device table.
23//!
24//! # Equivalence classes
25//!
26//! Four identical RTX 4090s through CUDA produce four essentially-
27//! identical performance profiles — the Judge doesn't need to run
28//! four times. Two [`DeviceDescriptor`]s that share an
29//! [`EquivalenceKey`] can share a profile: profile once per key,
30//! apply to every device in the class. Cross-backend equivalence
31//! never holds (CUDA and Vulkan on the same silicon still key
32//! differently because they have different driver paths and
33//! submission overhead).
34//!
35//! # Why a convention, not a trait
36//!
37//! `BackendProbe` *could* be a trait implemented by each backend's
38//! device or storage type. But enumeration is a **static** operation —
39//! it doesn't need a live backend instance, and requiring one creates
40//! a circular bootstrap problem (you can't know which backends exist
41//! until you've enumerated them, but trait impls need types, and the
42//! types may not be loadable if their runtime isn't present). The
43//! cleaner shape is a plain free function per backend crate that can
44//! be called via the crate's public API without constructing any
45//! state. The [`BackendProbe`] trait below is a *documentation anchor*
46//! — a marker trait each backend-crate-level probe function satisfies
47//! in spirit, so the contract is in one place and the collector has
48//! a single import to follow.
49
50use crate::DeviceLocation;
51use crate::error::Result;
52
53#[cfg(feature = "serde")]
54use serde::{Deserialize, Serialize};
55
56/// Identifier for a Fuel backend implementation. Stable across runs
57/// so the Judge's persisted profile tables remain valid when the
58/// process restarts. Adding a new variant is a non-breaking change;
59/// the enum is `#[non_exhaustive]` so downstream pattern matches stay
60/// forward-compatible.
61#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
62#[non_exhaustive]
63#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
64pub enum BackendId {
65 /// `fuel-cpu-backend` — optimized CPU executor (gemm + rayon).
66 /// One descriptor per physical CPU in the current scope; NUMA
67 /// splits are Phase 7b territory.
68 Cpu,
69 /// `fuel-cuda-backend` via baracuda.
70 Cuda,
71 /// `fuel-vulkan-backend` via vulkane.
72 Vulkan,
73 /// `fuel-metal-backend` (future — not yet probe-wired).
74 Metal,
75 // `Aocl` and `Mkl` variants retired 2026-06-08 (backend-extensions
76 // Phase 2). AOCL and oneMKL are now kernel-source extensions of
77 // `BackendId::Cpu` — their kernels register as siblings at the
78 // same binding-table key, distinguished by `BindingEntry::kernel_source`.
79 // See `docs/architecture/05-backend-contract.md` §Trait surface.
80}
81
82impl BackendId {
83 /// A short lowercase identifier suitable for log lines, directory
84 /// paths, and JSON keys. Stable across Fuel versions.
85 pub fn as_str(self) -> &'static str {
86 match self {
87 BackendId::Cpu => "cpu",
88 BackendId::Cuda => "cuda",
89 BackendId::Vulkan => "vulkan",
90 BackendId::Metal => "metal",
91 }
92 }
93}
94
95impl std::fmt::Display for BackendId {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 f.write_str(self.as_str())
98 }
99}
100
101/// Everything a Judge / dispatch table needs to know about a single
102/// `(backend, device)` pair. Constructed by each backend's
103/// `enumerate_devices()` and consumed by the collector + the Judge.
104///
105/// Field layout is stable: adding fields is non-breaking so long as
106/// they're additive (`#[serde(default)]` on new optional fields keeps
107/// older profile files loading).
108#[derive(Debug, Clone, PartialEq, Eq, Hash)]
109#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
110pub struct DeviceDescriptor {
111 /// Which backend this descriptor belongs to.
112 pub backend: BackendId,
113 /// Zero-based index within the backend. For CPU this is always 0
114 /// until NUMA splits arrive; for CUDA/Vulkan it's the device
115 /// ordinal the backend's own API uses.
116 pub device_index: u32,
117 /// Human-readable device name as reported by the driver.
118 /// Examples: `"NVIDIA GeForce RTX 4070"`, `"AMD Radeon RX 7900 XT"`,
119 /// `"Intel(R) Core(TM) i9-14900K"`. Used primarily for logs.
120 pub hardware_sku: String,
121 /// PCI-SIG vendor ID (NVIDIA=0x10DE, AMD=0x1002, Intel=0x8086).
122 /// `0` for CPU entries that don't map to a PCI vendor.
123 pub vendor_id: u32,
124 /// PCI-SIG device ID for discrete hardware; zero for CPU.
125 pub device_id: u32,
126 /// CUDA compute capability, when applicable. `None` for non-CUDA
127 /// entries. Stored as `(major, minor)` — e.g. `(8, 9)` for sm_89.
128 pub compute_capability: Option<(u32, u32)>,
129 /// The **default** lanes per subgroup / wave / warp — the primary
130 /// kernel-specialization axis on every SIMT backend. 32 on NVIDIA,
131 /// 64 on AMD GCN/CDNA, 32 *or* 64 on RDNA, 8/16/32 on Intel.
132 /// `None` when the backend cannot report it (CPU, or a Vulkan
133 /// instance created below 1.1).
134 ///
135 /// **This is the default width a shader sees, NOT the set the
136 /// device supports.** A device may *admit several*: an AMD 610M
137 /// reports a default of 64 while admitting dynamic, 32 and 64.
138 /// Vulkan exposes the pinnable range through
139 /// `SubgroupProperties::size_control`, which is 1.3 core / the EXT
140 /// — unreachable from Fuel's V1_2 instances today, so only the
141 /// default is captured here.
142 ///
143 /// **Consequence if Fuel ever specializes kernels by wave width:
144 /// `Option<u32>` is then the wrong shape**, not merely
145 /// under-documented — a wave32-pinned kernel and a wave64 one are
146 /// different cells, so the descriptor would need *the admissible
147 /// set plus the default*. Mirror vulkane's split
148 /// (`admissible_subgroups()` alongside `default_subgroup`) rather
149 /// than widening this field in place.
150 ///
151 /// Deliberately **not** part of [`EquivalenceKey`]: it is a
152 /// function of `(vendor_id, device_id)`, which the key already
153 /// carries, so including it would add no discriminating power and
154 /// would churn the Judge's cache for nothing.
155 pub subgroup_width: Option<u32>,
156 /// Driver version string as reported by the backend. Cache
157 /// invalidation key: if the driver rev changes, Judge re-runs.
158 pub driver_version: String,
159 /// Total device-visible memory in bytes. Zero if unknown.
160 pub total_memory_bytes: u64,
161 /// Fuel's placement enum for this descriptor. Populated by the
162 /// backend so the router can build `DeviceLocation` handles
163 /// without re-querying.
164 pub location: DeviceLocation,
165}
166
167impl DeviceDescriptor {
168 /// The key the Judge uses to share a profile across identical
169 /// devices. Two descriptors that compare equal here can share a
170 /// single profile entry; the table's runtime dispatch just looks
171 /// up the equivalence key rather than the full descriptor.
172 pub fn equivalence_key(&self) -> EquivalenceKey {
173 EquivalenceKey {
174 backend: self.backend,
175 vendor_id: self.vendor_id,
176 device_id: self.device_id,
177 compute_capability: self.compute_capability,
178 driver_version: self.driver_version.clone(),
179 }
180 }
181}
182
183/// Hash key that groups [`DeviceDescriptor`]s likely to profile
184/// identically. Explicitly **scoped by backend** — a CUDA RTX 4090
185/// and a Vulkan RTX 4090 are the same silicon but different
186/// submission paths, so they never share an equivalence class.
187///
188/// The driver version is part of the key because the same
189/// `(vendor, device, capability)` can perform measurably
190/// differently across driver releases; invalidating on driver
191/// upgrade is cheap insurance.
192#[derive(Debug, Clone, PartialEq, Eq, Hash)]
193#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
194pub struct EquivalenceKey {
195 pub backend: BackendId,
196 pub vendor_id: u32,
197 pub device_id: u32,
198 pub compute_capability: Option<(u32, u32)>,
199 pub driver_version: String,
200}
201
202/// Marker trait documenting the enumeration contract each backend
203/// crate satisfies. **Not dispatch-through** — each backend provides
204/// a plain `pub fn enumerate_devices()` at crate root, and the
205/// collector calls them by name. This trait is a single place to
206/// reference the expected signature.
207///
208/// See the module docs for why this is a convention rather than a
209/// dispatch trait.
210pub trait BackendProbe {
211 /// Enumerate every `(backend, device)` pair this backend can
212 /// currently reach. Empty vec = backend loaded but no usable
213 /// hardware visible (e.g. CUDA runtime present but zero GPUs).
214 /// `Err` = backend could not be probed at all (e.g. driver
215 /// dynamic-load failed).
216 fn enumerate_devices() -> Result<Vec<DeviceDescriptor>>;
217}
218
219impl DeviceLocation {
220 /// The kind of backend that drives this place: the one definition of the mapping
221 /// (`Cpu` to [`BackendId::Cpu`], each GPU variant to its backend, whatever the ordinal).
222 pub fn backend(self) -> BackendId {
223 match self {
224 DeviceLocation::Cpu => BackendId::Cpu,
225 DeviceLocation::Cuda { .. } => BackendId::Cuda,
226 DeviceLocation::Vulkan { .. } => BackendId::Vulkan,
227 DeviceLocation::Metal { .. } => BackendId::Metal,
228 }
229 }
230}
231
232impl BackendId {
233 /// The place a backend's work goes when nothing names a device: GPU ordinal 0, or the CPU.
234 /// The match is exhaustive inside this crate, so adding a `BackendId` variant fails to compile
235 /// here until it is given a default place. The ordinal is a within-process enumeration index,
236 /// not an identity (ROADMAP row 125); this is the one place that default lives.
237 pub fn default_location(self) -> DeviceLocation {
238 match self {
239 BackendId::Cpu => DeviceLocation::Cpu,
240 BackendId::Cuda => DeviceLocation::Cuda { gpu_id: 0 },
241 BackendId::Vulkan => DeviceLocation::Vulkan { gpu_id: 0 },
242 BackendId::Metal => DeviceLocation::Metal { gpu_id: 0 },
243 }
244 }
245}
246
247/// A PCI bus address as the OS and the GPU APIs report it. `function` is `None` when the source
248/// does not say (CUDA reports domain, bus and device number only).
249#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
250#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
251pub struct PciAddress {
252 pub domain: u32,
253 pub bus: u32,
254 pub device: u32,
255 pub function: Option<u32>,
256}
257
258/// What identifies ONE physical GPU across processes and across APIs (ROADMAP row 125). The
259/// enumeration index (`DeviceLocation::{Cuda,Vulkan}.gpu_id`) is only a within-process handle: on
260/// this box the Vulkan order flipped between two runs. Key placement on this, not on the index.
261///
262/// `uuid` is the 16-byte device UUID that Vulkan (`VkPhysicalDeviceIDProperties`), CUDA
263/// (`cuDeviceGetUuid`), NVML and OpenGL agree on. It is `None` when the source could not report one
264/// (and an all-zero value is treated as absent by [`Self::same_physical_device`]: a zeroed join key
265/// reads as a valid UUID that every device shares). `pci` is the bus address, the fallback join key.
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
267#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
268pub struct DeviceIdentity {
269 pub uuid: Option<[u8; 16]>,
270 pub pci: Option<PciAddress>,
271}
272
273impl DeviceIdentity {
274 /// The UUID, if present and not all zero.
275 pub fn usable_uuid(&self) -> Option<[u8; 16]> {
276 self.uuid.filter(|u| u.iter().any(|b| *b != 0))
277 }
278
279 /// Do these two identities name the same physical GPU? UUIDs decide when both sides have a
280 /// usable one (equal means same, different means different). Otherwise the PCI address decides
281 /// (domain, bus and device, plus function when both sides report it). With neither, the answer
282 /// is `false`: unknown is not "same".
283 pub fn same_physical_device(&self, other: &DeviceIdentity) -> bool {
284 if let (Some(a), Some(b)) = (self.usable_uuid(), other.usable_uuid()) {
285 return a == b;
286 }
287 match (self.pci, other.pci) {
288 (Some(a), Some(b)) => {
289 a.domain == b.domain
290 && a.bus == b.bus
291 && a.device == b.device
292 && match (a.function, b.function) {
293 (Some(x), Some(y)) => x == y,
294 _ => true,
295 }
296 }
297 _ => false,
298 }
299 }
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305
306 #[test]
307 fn backend_id_as_str_is_stable() {
308 assert_eq!(BackendId::Cpu.as_str(), "cpu");
309 assert_eq!(BackendId::Cuda.as_str(), "cuda");
310 assert_eq!(BackendId::Vulkan.as_str(), "vulkan");
311 assert_eq!(BackendId::Metal.as_str(), "metal");
312 }
313
314 #[test]
315 fn equivalence_key_collapses_identical_cuda_devices() {
316 let make = |idx: u32| DeviceDescriptor {
317 backend: BackendId::Cuda,
318 device_index: idx,
319 hardware_sku: "NVIDIA GeForce RTX 4090".to_string(),
320 vendor_id: 0x10DE,
321 device_id: 0x2684,
322 compute_capability: Some((8, 9)),
323 subgroup_width: Some(32), // NVIDIA warp
324 driver_version: "550.54.14".to_string(),
325 total_memory_bytes: 25_769_803_776,
326 location: DeviceLocation::Cuda {
327 gpu_id: idx as usize,
328 },
329 };
330 let a = make(0);
331 let b = make(1);
332 // Same silicon, different ordinals → same equivalence class.
333 assert_eq!(a.equivalence_key(), b.equivalence_key());
334 // Different device_index → descriptors still distinct overall.
335 assert_ne!(a, b);
336 }
337
338 #[test]
339 fn equivalence_key_splits_same_silicon_across_backends() {
340 let cuda = DeviceDescriptor {
341 backend: BackendId::Cuda,
342 device_index: 0,
343 hardware_sku: "NVIDIA GeForce RTX 4090".to_string(),
344 vendor_id: 0x10DE,
345 device_id: 0x2684,
346 compute_capability: Some((8, 9)),
347 subgroup_width: Some(32),
348 driver_version: "550.54.14".to_string(),
349 total_memory_bytes: 25_769_803_776,
350 location: DeviceLocation::Cuda { gpu_id: 0 },
351 };
352 let vulkan = DeviceDescriptor {
353 backend: BackendId::Vulkan,
354 device_index: 0,
355 hardware_sku: "NVIDIA GeForce RTX 4090".to_string(),
356 vendor_id: 0x10DE,
357 device_id: 0x2684,
358 compute_capability: None, // Vulkan doesn't expose CUDA CC.
359 subgroup_width: Some(32),
360 driver_version: "550.54.14".to_string(),
361 total_memory_bytes: 25_769_803_776,
362 location: DeviceLocation::Cpu, // placeholder; vulkane uses a different variant
363 };
364 // Same chip, different submission paths → different classes.
365 assert_ne!(cuda.equivalence_key(), vulkan.equivalence_key());
366 }
367
368 #[test]
369 fn equivalence_key_splits_on_driver_version() {
370 let base = DeviceDescriptor {
371 backend: BackendId::Cuda,
372 device_index: 0,
373 hardware_sku: "X".to_string(),
374 vendor_id: 1,
375 device_id: 2,
376 compute_capability: Some((8, 9)),
377 subgroup_width: Some(32),
378 driver_version: "550".to_string(),
379 total_memory_bytes: 0,
380 location: DeviceLocation::Cuda { gpu_id: 0 },
381 };
382 let newer = DeviceDescriptor {
383 driver_version: "560".to_string(),
384 ..base.clone()
385 };
386 assert_ne!(base.equivalence_key(), newer.equivalence_key());
387 }
388
389 /// `subgroup_width` is a function of `(vendor_id, device_id)`, which the
390 /// key already carries, so it must NOT participate in the equivalence
391 /// key — otherwise a backend that learns to report it (or stops) would
392 /// churn every cached Judge profile for no discriminating gain.
393 /// Pins the documented invariant on `DeviceDescriptor::subgroup_width`.
394 #[test]
395 fn equivalence_key_ignores_subgroup_width() {
396 let base = DeviceDescriptor {
397 backend: BackendId::Vulkan,
398 device_index: 0,
399 hardware_sku: "X".to_string(),
400 vendor_id: 1,
401 device_id: 2,
402 compute_capability: None,
403 subgroup_width: None,
404 driver_version: "550".to_string(),
405 total_memory_bytes: 0,
406 location: DeviceLocation::Vulkan { gpu_id: 0 },
407 };
408 let with_width = DeviceDescriptor {
409 subgroup_width: Some(64),
410 ..base.clone()
411 };
412 // Descriptors differ...
413 assert_ne!(base, with_width);
414 // ...but they profile identically, so the key must collapse them.
415 assert_eq!(base.equivalence_key(), with_width.equivalence_key());
416 }
417
418 /// Every GPU ordinal maps to the same backend, and the CPU to the CPU.
419 #[test]
420 fn location_to_backend_ignores_the_ordinal() {
421 assert_eq!(DeviceLocation::Cpu.backend(), BackendId::Cpu);
422 for gpu_id in [0usize, 1, 7] {
423 assert_eq!(DeviceLocation::Cuda { gpu_id }.backend(), BackendId::Cuda);
424 assert_eq!(
425 DeviceLocation::Vulkan { gpu_id }.backend(),
426 BackendId::Vulkan
427 );
428 assert_eq!(DeviceLocation::Metal { gpu_id }.backend(), BackendId::Metal);
429 }
430 }
431
432 /// The default location is ordinal 0 (or the CPU), and mapping it back gives the same backend,
433 /// for every backend this crate knows.
434 #[test]
435 fn default_location_round_trips_for_every_backend() {
436 for b in [
437 BackendId::Cpu,
438 BackendId::Cuda,
439 BackendId::Vulkan,
440 BackendId::Metal,
441 ] {
442 assert_eq!(b.default_location().backend(), b, "{b:?}");
443 }
444 assert_eq!(
445 BackendId::Cuda.default_location(),
446 DeviceLocation::Cuda { gpu_id: 0 }
447 );
448 assert_eq!(BackendId::Cpu.default_location(), DeviceLocation::Cpu);
449 }
450
451 fn ident(uuid: Option<u8>, pci: Option<(u32, u32, u32, Option<u32>)>) -> DeviceIdentity {
452 DeviceIdentity {
453 uuid: uuid.map(|b| [b; 16]),
454 pci: pci.map(|(domain, bus, device, function)| PciAddress {
455 domain,
456 bus,
457 device,
458 function,
459 }),
460 }
461 }
462
463 /// UUIDs decide when both sides have one; the PCI address cannot overrule them.
464 #[test]
465 fn identity_uuid_decides_when_both_sides_have_one() {
466 let a = ident(Some(1), Some((0, 1, 0, None)));
467 assert!(a.same_physical_device(&ident(Some(1), Some((0, 9, 9, None)))));
468 assert!(!a.same_physical_device(&ident(Some(2), Some((0, 1, 0, None)))));
469 }
470
471 /// An all-zero UUID is absent, not a value two devices share (the vulkane V1_0 trap).
472 #[test]
473 fn identity_zero_uuid_is_absent_so_pci_decides() {
474 let zero = DeviceIdentity {
475 uuid: Some([0; 16]),
476 pci: Some(PciAddress {
477 domain: 0,
478 bus: 3,
479 device: 0,
480 function: Some(0),
481 }),
482 };
483 let other_zero_other_bus = DeviceIdentity {
484 uuid: Some([0; 16]),
485 pci: Some(PciAddress {
486 domain: 0,
487 bus: 4,
488 device: 0,
489 function: Some(0),
490 }),
491 };
492 assert!(!zero.same_physical_device(&other_zero_other_bus));
493 assert!(zero.same_physical_device(&zero));
494 }
495
496 /// PCI fallback: a missing function on one side matches (CUDA does not report it); a present,
497 /// different function does not. Neither source having anything is "unknown", not "same".
498 #[test]
499 fn identity_pci_fallback_and_unknown() {
500 let cuda = ident(None, Some((0, 1, 0, None)));
501 assert!(cuda.same_physical_device(&ident(None, Some((0, 1, 0, Some(0))))));
502 assert!(!cuda.same_physical_device(&ident(None, Some((0, 2, 0, Some(0))))));
503 assert!(
504 !ident(Some(1), Some((0, 1, 0, Some(1))))
505 .same_physical_device(&ident(None, Some((0, 1, 0, Some(0)))))
506 );
507 assert!(!ident(None, None).same_physical_device(&ident(None, None)));
508 }
509}