1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Device Registry — Physical device tracking with backend preference
//!
//! This module provides deduplication of physical devices that may appear
//! multiple times through different backends (Vulkan, `OpenCL`, Metal, DX12).
//!
//! **Problem**: wgpu with `Backends::all()` returns the same physical GPU
//! as multiple adapters (e.g., RTX 3090 via Vulkan AND `OpenCL`).
//!
//! **Solution**: Track physical devices by (vendor, `device_id`) and aggregate
//! their backend capabilities. Prefer Vulkan for ecoPrimals workloads.
//!
//! # Example
//!
//! ```rust,ignore
//! use barracuda::device::registry::DeviceRegistry;
//!
//! let registry = DeviceRegistry::discover();
//!
//! // Get unique physical devices (deduplicated)
//! for device in registry.physical_devices() {
//! tracing::info!("{}: {} backends available",
//! device.name,
//! device.backends.len()
//! );
//! }
//!
//! // Get the best adapter for a physical device (prefers Vulkan)
//! let device = registry.get_preferred_adapter(0)?;
//! ```
use std::collections::HashMap;
use std::fmt::Write;
use std::sync::OnceLock;
/// Global device registry (lazily initialized on first access).
static GLOBAL_REGISTRY: OnceLock<DeviceRegistry> = OnceLock::new();
/// Backend preference order for ecoPrimals (Vulkan preferred for f64 support).
/// Vulkan is preferred for cross-platform compatibility and f64 support
const BACKEND_PREFERENCE: &[wgpu::Backend] = &[
wgpu::Backend::Vulkan, // Best f64 support, cross-platform
wgpu::Backend::Metal, // macOS native
wgpu::Backend::Dx12, // Windows native
wgpu::Backend::Gl, // Legacy fallback
wgpu::Backend::BrowserWebGpu, // WASM
];
/// A physical compute device (GPU, NPU, etc.)
///
/// This represents one physical piece of hardware, regardless of how many
/// backends can access it. For example, an RTX 3090 accessible via both
/// Vulkan and OpenGL is ONE `PhysicalDevice` with two backends.
#[derive(Debug, Clone)]
pub struct PhysicalDevice {
/// Unique identifier: (`vendor_id`, `device_id`)
pub id: PhysicalDeviceId,
/// Human-readable device name
pub name: String,
/// Vendor (NVIDIA, AMD, Intel, Apple, etc.)
pub vendor: DeviceVendor,
/// Device type (discrete, integrated, CPU, etc.)
pub device_type: wgpu::DeviceType,
/// Available backends for this device
pub backends: Vec<BackendInfo>,
/// Combined capabilities across all backends
pub capabilities: DeviceCapabilities,
}
/// Unique identifier for a physical device.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PhysicalDeviceId {
/// PCI vendor ID
pub vendor_id: u32,
/// PCI device ID
pub device_id: u32,
/// Normalized device name hash (for deduplication when `device_id` is 0)
pub name_hash: u64,
}
impl PhysicalDeviceId {
/// Build ID from wgpu adapter info.
#[must_use]
pub fn from_adapter_info(info: &wgpu::AdapterInfo) -> Self {
// OpenGL backends sometimes report device_id=0
// In that case, use the device name for deduplication
let name_hash = if info.device == 0 {
// Hash the normalized name (remove backend suffixes like "/PCIe/SSE2")
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
Self::normalize_device_name(&info.name).hash(&mut hasher);
hasher.finish()
} else {
0 // Not used when device_id is valid
};
Self {
vendor_id: info.vendor,
device_id: info.device,
name_hash,
}
}
/// Normalize device name for comparison
/// Removes backend-specific suffixes like "/PCIe/SSE2", "(RADV NAVI21)", etc.
fn normalize_device_name(name: &str) -> String {
// Remove common suffixes
let name = name.trim();
// Remove OpenGL-style suffixes: "NVIDIA GeForce RTX 3090/PCIe/SSE2" -> "NVIDIA GeForce RTX 3090"
let name = if let Some(idx) = name.find("/PCIe") {
&name[..idx]
} else {
name
};
// Remove Vulkan driver info: "AMD Radeon RX 6950 XT (RADV NAVI21)" -> "AMD Radeon RX 6950 XT"
let name = if let Some(idx) = name.find(" (RADV") {
&name[..idx]
} else if let Some(idx) = name.find(" (ACO") {
&name[..idx]
} else {
name
};
name.trim().to_string()
}
/// Check if two IDs likely refer to the same physical device
#[must_use]
pub fn likely_same_device(&self, other: &Self) -> bool {
// Same vendor is required
if self.vendor_id != other.vendor_id {
return false;
}
// If both have valid device_id, compare those
if self.device_id != 0 && other.device_id != 0 {
return self.device_id == other.device_id;
}
// If one has device_id=0, compare name hashes
// This handles OpenGL backends that don't report device_id
if self.device_id == 0 || other.device_id == 0 {
// OpenGL and some Vulkan backends report device_id=0. Fall back
// to vendor + name_hash equality which is correct for single-GPU
// and multi-GPU-different-model setups. Identical multi-GPU configs
// (e.g. 2x same card) would need PCI BDF from toadStool for
// disambiguation — handled at the substrate layer, not here.
return self.name_hash == other.name_hash && self.name_hash != 0;
}
false
}
}
/// Information about a specific backend for a device.
#[derive(Debug, Clone)]
pub struct BackendInfo {
/// Graphics API backend (Vulkan, Metal, DX12, etc.)
pub backend: wgpu::Backend,
/// Index in wgpu's adapter list
pub adapter_index: usize,
/// Driver name string
pub driver: String,
/// Driver info string (version, etc.)
pub driver_info: String,
}
/// Aggregated device capabilities
#[derive(Debug, Clone, Default)]
pub struct DeviceCapabilities {
/// Supports f64 (double precision) in shaders
pub f64_shaders: bool,
/// Supports f16 (half precision)
pub f16_shaders: bool,
/// Maximum buffer size (bytes)
pub max_buffer_size: u64,
/// Maximum workgroup size
pub max_workgroup_size: u32,
/// Maximum workgroups per dimension
pub max_workgroups: [u32; 3],
/// Estimated VRAM (bytes), 0 if unknown
pub vram_bytes: u64,
/// Compute capability (NVIDIA-specific, 0.0 if unknown)
pub compute_capability: f32,
}
/// Known device vendors (by PCI vendor ID).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeviceVendor {
/// NVIDIA
Nvidia,
/// AMD
Amd,
/// Intel
Intel,
/// Apple
Apple,
/// Qualcomm
Qualcomm,
/// ARM
Arm,
/// CPU/software rasterizer
Software,
/// Unknown vendor
Unknown,
}
impl DeviceVendor {
/// Map PCI vendor ID to vendor enum.
#[must_use]
pub fn from_vendor_id(id: u32) -> Self {
match id {
0x10DE => Self::Nvidia,
0x1002 => Self::Amd,
0x8086 => Self::Intel,
0x106B => Self::Apple,
0x5143 => Self::Qualcomm,
0x13B5 => Self::Arm,
0 => Self::Software,
_ => Self::Unknown,
}
}
/// Human-readable vendor name.
#[must_use]
pub fn name(&self) -> &'static str {
match self {
Self::Nvidia => "NVIDIA",
Self::Amd => "AMD",
Self::Intel => "Intel",
Self::Apple => "Apple",
Self::Qualcomm => "Qualcomm",
Self::Arm => "ARM",
Self::Software => "Software",
Self::Unknown => "Unknown",
}
}
}
/// Device registry — tracks all physical devices and their backends
#[derive(Debug)]
pub struct DeviceRegistry {
/// Physical devices indexed by their ID
devices: HashMap<PhysicalDeviceId, PhysicalDevice>,
/// Ordered list of device IDs (for stable iteration)
device_order: Vec<PhysicalDeviceId>,
/// Raw adapter infos (for creating devices)
adapter_infos: Vec<wgpu::AdapterInfo>,
}
impl DeviceRegistry {
/// Get or create the global device registry
pub fn global() -> &'static Self {
GLOBAL_REGISTRY.get_or_init(Self::discover)
}
/// Discover all devices and build the registry (async).
///
/// Prefer this over [`discover`] when running inside a tokio context
/// to avoid blocking the executor thread.
pub async fn discover_async() -> Self {
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
backends: wgpu::Backends::all(),
..Default::default()
});
let adapters = instance.enumerate_adapters(wgpu::Backends::all()).await;
let adapter_infos: Vec<wgpu::AdapterInfo> =
adapters.iter().map(wgpu::Adapter::get_info).collect();
Self::build_from_adapters(adapter_infos)
}
/// Discover all devices and build the registry (sync).
///
/// Safe from any context (sync, multi-threaded tokio, or current-thread
/// tokio) via [`crate::runtime::tokio_block_on`].
#[must_use]
pub fn discover() -> Self {
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
backends: wgpu::Backends::all(),
..Default::default()
});
let adapters: Vec<wgpu::Adapter> =
crate::runtime::tokio_block_on(instance.enumerate_adapters(wgpu::Backends::all()));
let adapter_infos: Vec<wgpu::AdapterInfo> =
adapters.iter().map(wgpu::Adapter::get_info).collect();
Self::build_from_adapters(adapter_infos)
}
fn build_from_adapters(adapter_infos: Vec<wgpu::AdapterInfo>) -> Self {
let mut devices: HashMap<PhysicalDeviceId, PhysicalDevice> = HashMap::new();
let mut device_order: Vec<PhysicalDeviceId> = Vec::new();
for (idx, info) in adapter_infos.iter().enumerate() {
let id = PhysicalDeviceId::from_adapter_info(info);
let backend_info = BackendInfo {
backend: info.backend,
adapter_index: idx,
driver: info.driver.clone(),
driver_info: info.driver_info.clone(),
};
// Check if this adapter matches an existing physical device
// This handles the case where OpenGL reports device_id=0
let existing_id = Self::find_matching_device(&devices, &id, info);
if let Some(existing_id) = existing_id {
// Add this backend to existing device
if let Some(device) = devices.get_mut(&existing_id) {
device.backends.push(backend_info);
}
} else {
// New physical device
let vendor = DeviceVendor::from_vendor_id(info.vendor);
let capabilities = Self::probe_capabilities(info);
let device = PhysicalDevice {
id: id.clone(),
name: info.name.clone(),
vendor,
device_type: info.device_type,
backends: vec![backend_info],
capabilities,
};
device_order.push(id.clone());
devices.insert(id, device);
}
}
// Sort backends by preference for each device
for device in devices.values_mut() {
device.backends.sort_by_key(|b| {
BACKEND_PREFERENCE
.iter()
.position(|&pref| pref == b.backend)
.unwrap_or(usize::MAX)
});
}
// Sort devices: discrete GPUs first, then by vendor preference
device_order.sort_by(|a, b| {
let (Some(da), Some(db)) = (devices.get(a), devices.get(b)) else {
return std::cmp::Ordering::Equal;
};
// Discrete GPUs first
let type_ord_a = Self::device_type_order(da.device_type);
let type_ord_b = Self::device_type_order(db.device_type);
if type_ord_a != type_ord_b {
return type_ord_a.cmp(&type_ord_b);
}
// Then by name (stable ordering)
da.name.cmp(&db.name)
});
Self {
devices,
device_order,
adapter_infos,
}
}
/// Find an existing device that matches this adapter
///
/// This handles deduplication when:
/// 1. Same vendor+device ID (straightforward match)
/// 2. Same vendor, one has `device_id=0` (OpenGL quirk), names match
fn find_matching_device(
devices: &HashMap<PhysicalDeviceId, PhysicalDevice>,
new_id: &PhysicalDeviceId,
new_info: &wgpu::AdapterInfo,
) -> Option<PhysicalDeviceId> {
// First, try exact match
if devices.contains_key(new_id) {
return Some(new_id.clone());
}
// If new adapter has device_id=0 (OpenGL quirk), try name-based matching
if new_id.device_id == 0 {
let normalized_name = PhysicalDeviceId::normalize_device_name(&new_info.name);
for (existing_id, existing_device) in devices {
// Same vendor
if existing_id.vendor_id != new_id.vendor_id {
continue;
}
// Check if names match (after normalization)
let existing_normalized =
PhysicalDeviceId::normalize_device_name(&existing_device.name);
if normalized_name == existing_normalized {
return Some(existing_id.clone());
}
// Also check if the new name contains the existing device's base name
// "NVIDIA GeForce RTX 3090/PCIe/SSE2" contains "NVIDIA GeForce RTX 3090"
if normalized_name.contains(&existing_normalized)
|| existing_normalized.contains(&normalized_name)
{
return Some(existing_id.clone());
}
}
}
// If existing device has device_id=0, check if this new adapter matches
for (existing_id, existing_device) in devices {
if existing_id.device_id == 0 && existing_id.vendor_id == new_id.vendor_id {
let normalized_name = PhysicalDeviceId::normalize_device_name(&new_info.name);
let existing_normalized =
PhysicalDeviceId::normalize_device_name(&existing_device.name);
if normalized_name == existing_normalized
|| normalized_name.contains(&existing_normalized)
|| existing_normalized.contains(&normalized_name)
{
return Some(existing_id.clone());
}
}
}
None
}
fn device_type_order(dt: wgpu::DeviceType) -> u8 {
match dt {
wgpu::DeviceType::DiscreteGpu => 0,
wgpu::DeviceType::IntegratedGpu => 1,
wgpu::DeviceType::VirtualGpu => 2,
wgpu::DeviceType::Cpu => 3,
wgpu::DeviceType::Other => 4,
}
}
fn probe_capabilities(info: &wgpu::AdapterInfo) -> DeviceCapabilities {
// Basic capability detection from adapter info
// More detailed probing requires creating a device, which we defer
let vendor = DeviceVendor::from_vendor_id(info.vendor);
// NVIDIA GPUs: compute capability from device ID ranges
let compute_capability = if vendor == DeviceVendor::Nvidia {
Self::nvidia_compute_capability(info.device)
} else {
0.0
};
// f64 support: NVIDIA with CC >= 6.0, AMD GCN+, Intel
let f64_shaders = match vendor {
DeviceVendor::Nvidia => compute_capability >= 6.0,
DeviceVendor::Amd => true, // GCN and later support f64
DeviceVendor::Intel => true, // Most Intel GPUs support f64
DeviceVendor::Apple => false, // Apple GPUs don't support f64
_ => false,
};
DeviceCapabilities {
f64_shaders,
f16_shaders: true, // Most modern GPUs support f16
max_buffer_size: 0, // Requires device creation to probe
max_workgroup_size: 256, // Conservative default
max_workgroups: [65535, 65535, 65535],
vram_bytes: 0, // Not available from adapter info
compute_capability,
}
}
fn nvidia_compute_capability(device_id: u32) -> f32 {
// Approximate compute capability from NVIDIA device ID ranges
// This is heuristic - actual CC requires CUDA query
match device_id >> 4 {
// RTX 40 series (Ada Lovelace) - CC 8.9
0x260..=0x28F => 8.9,
// RTX 30 series (Ampere) - CC 8.6
0x220..=0x25F => 8.6,
// RTX 20 series (Turing) - CC 7.5
0x1E0..=0x21F => 7.5,
// GTX 10 series (Pascal) - CC 6.1
0x1B0..=0x1DF => 6.1,
// GTX 9 series (Maxwell) - CC 5.2
0x130..=0x17F => 5.2,
_ => 6.0, // Conservative default for unknown NVIDIA
}
}
/// Get all unique physical devices (deduplicated)
pub fn physical_devices(&self) -> impl Iterator<Item = &PhysicalDevice> {
self.device_order.iter().map(|id| &self.devices[id])
}
/// Get number of unique physical devices
#[must_use]
pub fn device_count(&self) -> usize {
self.devices.len()
}
/// Get physical device by index (in discovery order)
#[must_use]
pub fn get_device(&self, index: usize) -> Option<&PhysicalDevice> {
self.device_order.get(index).map(|id| &self.devices[id])
}
/// Get physical device by ID
#[must_use]
pub fn get_device_by_id(&self, id: PhysicalDeviceId) -> Option<&PhysicalDevice> {
self.devices.get(&id)
}
/// Get the preferred adapter index for a physical device
///
/// Returns the adapter index for the best backend (Vulkan preferred)
#[must_use]
pub fn get_preferred_adapter_index(&self, device_index: usize) -> Option<usize> {
self.get_device(device_index)
.and_then(|d| d.backends.first())
.map(|b| b.adapter_index)
}
/// Get adapter index for a specific backend on a device
#[must_use]
pub fn get_adapter_for_backend(
&self,
device_index: usize,
backend: wgpu::Backend,
) -> Option<usize> {
self.get_device(device_index).and_then(|d| {
d.backends
.iter()
.find(|b| b.backend == backend)
.map(|b| b.adapter_index)
})
}
/// Get all GPU devices (discrete and integrated)
pub fn gpus(&self) -> impl Iterator<Item = &PhysicalDevice> {
self.physical_devices().filter(|d| {
matches!(
d.device_type,
wgpu::DeviceType::DiscreteGpu | wgpu::DeviceType::IntegratedGpu
)
})
}
/// Get discrete GPUs only
pub fn discrete_gpus(&self) -> impl Iterator<Item = &PhysicalDevice> {
self.physical_devices()
.filter(|d| d.device_type == wgpu::DeviceType::DiscreteGpu)
}
/// Get devices that support f64
pub fn f64_capable(&self) -> impl Iterator<Item = &PhysicalDevice> {
self.physical_devices()
.filter(|d| d.capabilities.f64_shaders)
}
/// Get raw adapter info by index (for wgpu device creation)
#[must_use]
pub fn get_adapter_info(&self, index: usize) -> Option<&wgpu::AdapterInfo> {
self.adapter_infos.get(index)
}
/// Get all raw adapter infos
#[must_use]
pub fn all_adapter_infos(&self) -> &[wgpu::AdapterInfo] {
&self.adapter_infos
}
/// Generate a hardware report
#[must_use]
pub fn report(&self) -> String {
let mut report = String::new();
report.push_str("=== Device Registry Report ===\n\n");
let _ = write!(
report,
"Physical devices: {} (from {} adapters)\n\n",
self.device_count(),
self.adapter_infos.len()
);
for (idx, device) in self.physical_devices().enumerate() {
let _ = writeln!(
report,
"Device {}: {} ({})",
idx,
device.name,
device.vendor.name()
);
let _ = writeln!(report, " Type: {:?}", device.device_type);
let _ = writeln!(
report,
" ID: vendor=0x{:04X}, device=0x{:04X}",
device.id.vendor_id, device.id.device_id
);
let _ = writeln!(report, " f64 support: {}", device.capabilities.f64_shaders);
if device.capabilities.compute_capability > 0.0 {
let _ = writeln!(
report,
" Compute capability: {:.1}",
device.capabilities.compute_capability
);
}
report.push_str(" Backends:\n");
for (bidx, backend) in device.backends.iter().enumerate() {
let preferred = if bidx == 0 { " (preferred)" } else { "" };
let _ = writeln!(
report,
" - {:?}{}: adapter[{}]",
backend.backend, preferred, backend.adapter_index
);
}
report.push('\n');
}
report
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_registry_discovery() {
let registry = DeviceRegistry::discover();
// Should have at least discovered something
// (could be CPU-only in CI environments)
let _ = registry.report();
// Verify no duplicate physical devices
let mut seen_ids = std::collections::HashSet::new();
for device in registry.physical_devices() {
assert!(
seen_ids.insert(device.id.clone()),
"Duplicate physical device: {:?}",
device.id
);
}
}
#[test]
fn test_backend_preference() {
let registry = DeviceRegistry::discover();
for device in registry.physical_devices() {
if device.backends.len() > 1 {
// If multiple backends, Vulkan should be first (if available)
let has_vulkan = device
.backends
.iter()
.any(|b| b.backend == wgpu::Backend::Vulkan);
if has_vulkan {
assert_eq!(
device.backends[0].backend,
wgpu::Backend::Vulkan,
"Vulkan should be preferred backend for {:?}",
device.name
);
}
}
}
}
#[test]
fn test_vendor_detection() {
assert_eq!(DeviceVendor::from_vendor_id(0x10DE), DeviceVendor::Nvidia);
assert_eq!(DeviceVendor::from_vendor_id(0x1002), DeviceVendor::Amd);
assert_eq!(DeviceVendor::from_vendor_id(0x8086), DeviceVendor::Intel);
assert_eq!(DeviceVendor::from_vendor_id(0x106B), DeviceVendor::Apple);
}
}