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/// Why [`resolve_identity_ordinal`] found no single device.
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub enum IdentityResolveError {
305 /// No enumerated device is the wanted physical GPU (including: the wanted identity carries
306 /// neither a usable UUID nor a PCI address, since unknown is never "same").
307 NoMatch,
308 /// More than one enumerated device claims to be the wanted GPU (their ordinals, ascending).
309 /// Guessing the first would reintroduce the order dependence this exists to remove.
310 Ambiguous(Vec<usize>),
311}
312
313/// Resolve a [`DeviceIdentity`] to the enumeration ordinal of THIS process (ROADMAP row 137,
314/// step 4a). `enumerated[i]` is the identity of the device the process enumerates at ordinal `i`.
315/// The answer is a within-process handle and must not be stored: the next process or build may
316/// enumerate in a different order, which is the reason to ask by identity at all.
317pub fn resolve_identity_ordinal(
318 wanted: &DeviceIdentity,
319 enumerated: &[DeviceIdentity],
320) -> std::result::Result<usize, IdentityResolveError> {
321 let hits: Vec<usize> = enumerated
322 .iter()
323 .enumerate()
324 .filter(|(_, id)| wanted.same_physical_device(id))
325 .map(|(i, _)| i)
326 .collect();
327 match hits.as_slice() {
328 [] => Err(IdentityResolveError::NoMatch),
329 [one] => Ok(*one),
330 _ => Err(IdentityResolveError::Ambiguous(hits)),
331 }
332}
333
334/// Why a device-selector string is not a [`DeviceIdentity`] (ROADMAP row 125, part 2).
335#[derive(Debug, Clone, PartialEq, Eq)]
336pub enum IdentityParseError {
337 /// The string is empty or only whitespace.
338 Empty,
339 /// It looks like a UUID (32 hex digits, dashes optional) but is not one.
340 BadUuid,
341 /// An all-zero UUID names no device (it reads as absent), so it is refused here rather than
342 /// resolving to "no match" later.
343 ZeroUuid,
344 /// It looks like a PCI address but is not `[domain:]bus:device[.function]` in hex.
345 BadPci,
346}
347
348impl std::fmt::Display for IdentityParseError {
349 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
350 f.write_str(match self {
351 Self::Empty => "empty device selector",
352 Self::BadUuid => {
353 "not a device UUID (want 8-4-4-4-12 hex digits, optional `GPU-` prefix)"
354 }
355 Self::ZeroUuid => "an all-zero UUID names no device",
356 Self::BadPci => "not a PCI address (want [domain:]bus:device[.function], hex)",
357 })
358 }
359}
360
361impl std::error::Error for IdentityParseError {}
362
363/// Parse a device selector a person can type: a UUID (`05c56c06-f951-3d45-5c8a-c76bbcb1deaa`, the
364/// `GPU-` form `nvidia-smi -L` prints, or 32 bare hex digits) or a PCI address
365/// (`01:00.0`, `0000:01:00.0`, `01:00`; hex, the function optional). The result is a
366/// [`DeviceIdentity`] for the `*_by_identity` constructors; a UUID sets only `uuid`, a PCI address
367/// only `pci`, so the match is made on exactly what the caller named.
368impl std::str::FromStr for DeviceIdentity {
369 type Err = IdentityParseError;
370
371 fn from_str(text: &str) -> std::result::Result<Self, Self::Err> {
372 let t = text.trim();
373 if t.is_empty() {
374 return Err(IdentityParseError::Empty);
375 }
376 let bare = t
377 .strip_prefix("GPU-")
378 .or_else(|| t.strip_prefix("gpu-"))
379 .or_else(|| t.strip_prefix("MIG-"))
380 .unwrap_or(t);
381 // A PCI address has a `:`; a UUID never does.
382 if bare.contains(':') {
383 return parse_pci(bare).map(|pci| DeviceIdentity {
384 uuid: None,
385 pci: Some(pci),
386 });
387 }
388 let hex: String = bare.chars().filter(|c| *c != '-').collect();
389 if hex.len() != 32 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
390 return Err(IdentityParseError::BadUuid);
391 }
392 let mut uuid = [0u8; 16];
393 for (i, byte) in uuid.iter_mut().enumerate() {
394 *byte = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16)
395 .map_err(|_| IdentityParseError::BadUuid)?;
396 }
397 if uuid.iter().all(|b| *b == 0) {
398 return Err(IdentityParseError::ZeroUuid);
399 }
400 Ok(DeviceIdentity {
401 uuid: Some(uuid),
402 pci: None,
403 })
404 }
405}
406
407fn parse_pci(text: &str) -> std::result::Result<PciAddress, IdentityParseError> {
408 let hex = |s: &str, max_digits: usize| -> std::result::Result<u32, IdentityParseError> {
409 if s.is_empty() || s.len() > max_digits || !s.chars().all(|c| c.is_ascii_hexdigit()) {
410 return Err(IdentityParseError::BadPci);
411 }
412 u32::from_str_radix(s, 16).map_err(|_| IdentityParseError::BadPci)
413 };
414 let parts: Vec<&str> = text.split(':').collect();
415 let (domain, bus, tail) = match parts.as_slice() {
416 [bus, tail] => (0, hex(bus, 2)?, *tail),
417 [domain, bus, tail] => (hex(domain, 4)?, hex(bus, 2)?, *tail),
418 _ => return Err(IdentityParseError::BadPci),
419 };
420 let (device, function) = match tail.split_once('.') {
421 Some((d, f)) => (hex(d, 2)?, Some(hex(f, 1)?)),
422 None => (hex(tail, 2)?, None),
423 };
424 // PCI device numbers are 5 bits, functions 3 bits.
425 if device > 0x1f || function.is_some_and(|f| f > 7) {
426 return Err(IdentityParseError::BadPci);
427 }
428 Ok(PciAddress {
429 domain,
430 bus,
431 device,
432 function,
433 })
434}
435
436/// Read a device selector from the environment variable `var` (for example `FUEL_CUDA_DEVICE`).
437/// `Ok(None)` when it is unset or empty; an unparsable value is an error naming the variable, never
438/// a silent fall-back to the default device (that would run on the wrong GPU without saying so).
439pub fn identity_from_env(var: &str) -> std::result::Result<Option<DeviceIdentity>, String> {
440 identity_from_value(var, std::env::var(var).ok().as_deref())
441}
442
443/// The pure half of [`identity_from_env`]: `value` is what the variable held, `None` if unset.
444pub fn identity_from_value(
445 var: &str,
446 value: Option<&str>,
447) -> std::result::Result<Option<DeviceIdentity>, String> {
448 match value {
449 Some(v) if !v.trim().is_empty() => v
450 .parse::<DeviceIdentity>()
451 .map(Some)
452 .map_err(|e| format!("{var}={v:?}: {e}")),
453 _ => Ok(None),
454 }
455}
456
457#[cfg(test)]
458mod tests {
459 use super::*;
460
461 fn res_ident(uuid_byte: u8, bus: u32) -> DeviceIdentity {
462 DeviceIdentity {
463 uuid: Some([uuid_byte; 16]),
464 pci: Some(PciAddress {
465 domain: 0,
466 bus,
467 device: 0,
468 function: None,
469 }),
470 }
471 }
472
473 #[test]
474 fn resolver_follows_the_device_across_both_enumeration_orders() {
475 let nv = res_ident(0x11, 1);
476 let amd = res_ident(0x22, 6);
477 // Vulkan-only build order vs CUDA-plus-Vulkan build order (row 125 measurement).
478 let amd_first = [amd, nv];
479 let nv_first = [nv, amd];
480 assert_eq!(resolve_identity_ordinal(&nv, &amd_first), Ok(1));
481 assert_eq!(resolve_identity_ordinal(&nv, &nv_first), Ok(0));
482 assert_eq!(resolve_identity_ordinal(&amd, &amd_first), Ok(0));
483 assert_eq!(resolve_identity_ordinal(&amd, &nv_first), Ok(1));
484 }
485
486 #[test]
487 fn resolver_declines_unknown_absent_and_ambiguous() {
488 let nv = res_ident(0x11, 1);
489 let amd = res_ident(0x22, 6);
490 assert_eq!(
491 resolve_identity_ordinal(&nv, &[amd]),
492 Err(IdentityResolveError::NoMatch)
493 );
494 assert_eq!(
495 resolve_identity_ordinal(&nv, &[]),
496 Err(IdentityResolveError::NoMatch)
497 );
498 // Neither UUID nor PCI: unknown is never "same", even against another unknown.
499 let none = DeviceIdentity {
500 uuid: None,
501 pci: None,
502 };
503 assert_eq!(
504 resolve_identity_ordinal(&none, &[none]),
505 Err(IdentityResolveError::NoMatch)
506 );
507 // An all-zero UUID is absent, so two zeroed devices on different buses stay distinct.
508 let z = |bus| DeviceIdentity {
509 uuid: Some([0; 16]),
510 pci: Some(PciAddress {
511 domain: 0,
512 bus,
513 device: 0,
514 function: None,
515 }),
516 };
517 assert_eq!(resolve_identity_ordinal(&z(1), &[z(6), z(1)]), Ok(1));
518 // Two enumerated entries for the same GPU: refuse rather than take the first.
519 assert_eq!(
520 resolve_identity_ordinal(&nv, &[nv, amd, nv]),
521 Err(IdentityResolveError::Ambiguous(vec![0, 2]))
522 );
523 }
524
525 #[test]
526 fn backend_id_as_str_is_stable() {
527 assert_eq!(BackendId::Cpu.as_str(), "cpu");
528 assert_eq!(BackendId::Cuda.as_str(), "cuda");
529 assert_eq!(BackendId::Vulkan.as_str(), "vulkan");
530 assert_eq!(BackendId::Metal.as_str(), "metal");
531 }
532
533 #[test]
534 fn equivalence_key_collapses_identical_cuda_devices() {
535 let make = |idx: u32| DeviceDescriptor {
536 backend: BackendId::Cuda,
537 device_index: idx,
538 hardware_sku: "NVIDIA GeForce RTX 4090".to_string(),
539 vendor_id: 0x10DE,
540 device_id: 0x2684,
541 compute_capability: Some((8, 9)),
542 subgroup_width: Some(32), // NVIDIA warp
543 driver_version: "550.54.14".to_string(),
544 total_memory_bytes: 25_769_803_776,
545 location: DeviceLocation::Cuda {
546 gpu_id: idx as usize,
547 },
548 };
549 let a = make(0);
550 let b = make(1);
551 // Same silicon, different ordinals → same equivalence class.
552 assert_eq!(a.equivalence_key(), b.equivalence_key());
553 // Different device_index → descriptors still distinct overall.
554 assert_ne!(a, b);
555 }
556
557 #[test]
558 fn equivalence_key_splits_same_silicon_across_backends() {
559 let cuda = DeviceDescriptor {
560 backend: BackendId::Cuda,
561 device_index: 0,
562 hardware_sku: "NVIDIA GeForce RTX 4090".to_string(),
563 vendor_id: 0x10DE,
564 device_id: 0x2684,
565 compute_capability: Some((8, 9)),
566 subgroup_width: Some(32),
567 driver_version: "550.54.14".to_string(),
568 total_memory_bytes: 25_769_803_776,
569 location: DeviceLocation::Cuda { gpu_id: 0 },
570 };
571 let vulkan = DeviceDescriptor {
572 backend: BackendId::Vulkan,
573 device_index: 0,
574 hardware_sku: "NVIDIA GeForce RTX 4090".to_string(),
575 vendor_id: 0x10DE,
576 device_id: 0x2684,
577 compute_capability: None, // Vulkan doesn't expose CUDA CC.
578 subgroup_width: Some(32),
579 driver_version: "550.54.14".to_string(),
580 total_memory_bytes: 25_769_803_776,
581 location: DeviceLocation::Cpu, // placeholder; vulkane uses a different variant
582 };
583 // Same chip, different submission paths → different classes.
584 assert_ne!(cuda.equivalence_key(), vulkan.equivalence_key());
585 }
586
587 #[test]
588 fn equivalence_key_splits_on_driver_version() {
589 let base = DeviceDescriptor {
590 backend: BackendId::Cuda,
591 device_index: 0,
592 hardware_sku: "X".to_string(),
593 vendor_id: 1,
594 device_id: 2,
595 compute_capability: Some((8, 9)),
596 subgroup_width: Some(32),
597 driver_version: "550".to_string(),
598 total_memory_bytes: 0,
599 location: DeviceLocation::Cuda { gpu_id: 0 },
600 };
601 let newer = DeviceDescriptor {
602 driver_version: "560".to_string(),
603 ..base.clone()
604 };
605 assert_ne!(base.equivalence_key(), newer.equivalence_key());
606 }
607
608 /// `subgroup_width` is a function of `(vendor_id, device_id)`, which the
609 /// key already carries, so it must NOT participate in the equivalence
610 /// key — otherwise a backend that learns to report it (or stops) would
611 /// churn every cached Judge profile for no discriminating gain.
612 /// Pins the documented invariant on `DeviceDescriptor::subgroup_width`.
613 #[test]
614 fn equivalence_key_ignores_subgroup_width() {
615 let base = DeviceDescriptor {
616 backend: BackendId::Vulkan,
617 device_index: 0,
618 hardware_sku: "X".to_string(),
619 vendor_id: 1,
620 device_id: 2,
621 compute_capability: None,
622 subgroup_width: None,
623 driver_version: "550".to_string(),
624 total_memory_bytes: 0,
625 location: DeviceLocation::Vulkan { gpu_id: 0 },
626 };
627 let with_width = DeviceDescriptor {
628 subgroup_width: Some(64),
629 ..base.clone()
630 };
631 // Descriptors differ...
632 assert_ne!(base, with_width);
633 // ...but they profile identically, so the key must collapse them.
634 assert_eq!(base.equivalence_key(), with_width.equivalence_key());
635 }
636
637 /// Every GPU ordinal maps to the same backend, and the CPU to the CPU.
638 #[test]
639 fn location_to_backend_ignores_the_ordinal() {
640 assert_eq!(DeviceLocation::Cpu.backend(), BackendId::Cpu);
641 for gpu_id in [0usize, 1, 7] {
642 assert_eq!(DeviceLocation::Cuda { gpu_id }.backend(), BackendId::Cuda);
643 assert_eq!(
644 DeviceLocation::Vulkan { gpu_id }.backend(),
645 BackendId::Vulkan
646 );
647 assert_eq!(DeviceLocation::Metal { gpu_id }.backend(), BackendId::Metal);
648 }
649 }
650
651 /// The default location is ordinal 0 (or the CPU), and mapping it back gives the same backend,
652 /// for every backend this crate knows.
653 #[test]
654 fn default_location_round_trips_for_every_backend() {
655 for b in [
656 BackendId::Cpu,
657 BackendId::Cuda,
658 BackendId::Vulkan,
659 BackendId::Metal,
660 ] {
661 assert_eq!(b.default_location().backend(), b, "{b:?}");
662 }
663 assert_eq!(
664 BackendId::Cuda.default_location(),
665 DeviceLocation::Cuda { gpu_id: 0 }
666 );
667 assert_eq!(BackendId::Cpu.default_location(), DeviceLocation::Cpu);
668 }
669
670 fn ident(uuid: Option<u8>, pci: Option<(u32, u32, u32, Option<u32>)>) -> DeviceIdentity {
671 DeviceIdentity {
672 uuid: uuid.map(|b| [b; 16]),
673 pci: pci.map(|(domain, bus, device, function)| PciAddress {
674 domain,
675 bus,
676 device,
677 function,
678 }),
679 }
680 }
681
682 /// UUIDs decide when both sides have one; the PCI address cannot overrule them.
683 #[test]
684 fn identity_uuid_decides_when_both_sides_have_one() {
685 let a = ident(Some(1), Some((0, 1, 0, None)));
686 assert!(a.same_physical_device(&ident(Some(1), Some((0, 9, 9, None)))));
687 assert!(!a.same_physical_device(&ident(Some(2), Some((0, 1, 0, None)))));
688 }
689
690 /// An all-zero UUID is absent, not a value two devices share (the vulkane V1_0 trap).
691 #[test]
692 fn identity_zero_uuid_is_absent_so_pci_decides() {
693 let zero = DeviceIdentity {
694 uuid: Some([0; 16]),
695 pci: Some(PciAddress {
696 domain: 0,
697 bus: 3,
698 device: 0,
699 function: Some(0),
700 }),
701 };
702 let other_zero_other_bus = DeviceIdentity {
703 uuid: Some([0; 16]),
704 pci: Some(PciAddress {
705 domain: 0,
706 bus: 4,
707 device: 0,
708 function: Some(0),
709 }),
710 };
711 assert!(!zero.same_physical_device(&other_zero_other_bus));
712 assert!(zero.same_physical_device(&zero));
713 }
714
715 /// PCI fallback: a missing function on one side matches (CUDA does not report it); a present,
716 /// different function does not. Neither source having anything is "unknown", not "same".
717 #[test]
718 fn identity_pci_fallback_and_unknown() {
719 let cuda = ident(None, Some((0, 1, 0, None)));
720 assert!(cuda.same_physical_device(&ident(None, Some((0, 1, 0, Some(0))))));
721 assert!(!cuda.same_physical_device(&ident(None, Some((0, 2, 0, Some(0))))));
722 assert!(
723 !ident(Some(1), Some((0, 1, 0, Some(1))))
724 .same_physical_device(&ident(None, Some((0, 1, 0, Some(0)))))
725 );
726 assert!(!ident(None, None).same_physical_device(&ident(None, None)));
727 }
728
729 const NV: &str = "05c56c06-f951-3d45-5c8a-c76bbcb1deaa";
730
731 #[test]
732 fn selector_parses_uuid_in_every_written_form() {
733 let want: DeviceIdentity = NV.parse().unwrap();
734 assert_eq!(want.uuid.unwrap()[0], 0x05);
735 assert_eq!(want.uuid.unwrap()[15], 0xaa);
736 assert_eq!(want.pci, None);
737 assert_eq!(format!("GPU-{NV}").parse::<DeviceIdentity>(), Ok(want));
738 assert_eq!(NV.replace('-', "").parse::<DeviceIdentity>(), Ok(want));
739 assert_eq!(
740 format!(" {}\n", NV.to_uppercase()).parse::<DeviceIdentity>(),
741 Ok(want)
742 );
743 }
744
745 #[test]
746 fn selector_parses_pci_addresses() {
747 let p = |s: &str| s.parse::<DeviceIdentity>().unwrap().pci.unwrap();
748 let a = p("01:00.0");
749 assert_eq!((a.domain, a.bus, a.device, a.function), (0, 1, 0, Some(0)));
750 let b = p("0000:0a:1f.7");
751 assert_eq!(
752 (b.domain, b.bus, b.device, b.function),
753 (0, 0x0a, 0x1f, Some(7))
754 );
755 let c = p("0001:81:00");
756 assert_eq!((c.domain, c.bus, c.device, c.function), (1, 0x81, 0, None));
757 assert_eq!("01:00.0".parse::<DeviceIdentity>().unwrap().uuid, None);
758 }
759
760 #[test]
761 fn selector_refuses_what_is_not_a_device() {
762 use IdentityParseError::*;
763 let e = |s: &str| s.parse::<DeviceIdentity>().unwrap_err();
764 assert_eq!(e(""), Empty);
765 assert_eq!(e(" "), Empty);
766 assert_eq!(e("0"), BadUuid);
767 assert_eq!(e("zzzzzzzz-f951-3d45-5c8a-c76bbcb1deaa"), BadUuid);
768 assert_eq!(e(&NV[..35]), BadUuid);
769 assert_eq!(e("00000000-0000-0000-0000-000000000000"), ZeroUuid);
770 assert_eq!(e("01:00.8"), BadPci); // function is 3 bits
771 assert_eq!(e("01:20.0"), BadPci); // device is 5 bits
772 assert_eq!(e("01:"), BadPci);
773 assert_eq!(e("1:2:3:4"), BadPci);
774 assert_eq!(e("012:00.0"), BadPci); // bus is 2 digits
775 }
776
777 /// A parsed selector resolves through the same matcher the constructors use: the UUID picks
778 /// the right device whatever the enumeration order, and a PCI-only selector falls back to the
779 /// bus address (the iGPU case: no usable UUID).
780 #[test]
781 fn selector_resolves_against_an_enumeration_in_either_order() {
782 let nv: DeviceIdentity = NV.parse().unwrap();
783 let other: DeviceIdentity = "11111111-2222-3333-4444-555555555555".parse().unwrap();
784 assert_eq!(resolve_identity_ordinal(&nv, &[nv, other]), Ok(0));
785 assert_eq!(resolve_identity_ordinal(&nv, &[other, nv]), Ok(1));
786 let gpu = |bus| DeviceIdentity {
787 uuid: None,
788 pci: Some(PciAddress {
789 domain: 0,
790 bus,
791 device: 0,
792 function: None,
793 }),
794 };
795 let want: DeviceIdentity = "0000:03:00.0".parse().unwrap();
796 assert_eq!(resolve_identity_ordinal(&want, &[gpu(1), gpu(3)]), Ok(1));
797 assert_eq!(
798 resolve_identity_ordinal(&want, &[gpu(1), gpu(2)]),
799 Err(IdentityResolveError::NoMatch)
800 );
801 }
802
803 #[test]
804 fn env_selector_is_unset_empty_good_or_a_named_error() {
805 let var = "FUEL_CUDA_DEVICE";
806 assert_eq!(identity_from_value(var, None), Ok(None));
807 assert_eq!(identity_from_value(var, Some(" ")), Ok(None));
808 assert_eq!(
809 identity_from_value(var, Some(NV)),
810 Ok(Some(NV.parse().unwrap()))
811 );
812 let err = identity_from_value(var, Some("not-a-gpu")).unwrap_err();
813 assert!(
814 err.contains(var) && err.contains("not a device UUID"),
815 "{err}"
816 );
817 }
818}