Skip to main content

fuel_dispatch/
device_registry.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! The device handles found or handed in during one realize (ROADMAP row 137, seam S3 step 3).
3//!
4//! Moved out of `pipelined.rs` (step 3b-3), where it sat in the largest and most-depended-on file of the
5//! crate. `crate::pipelined::DeviceRegistry` still names it.
6
7#[cfg(any(feature = "cuda", feature = "vulkan"))]
8use fuel_ir::DeviceLocation;
9#[cfg(any(feature = "cuda", feature = "vulkan", test))]
10use fuel_ir::probe::DeviceIdentity;
11#[cfg(any(feature = "cuda", feature = "vulkan"))]
12use std::collections::HashMap;
13
14/// The device handles one realize works with, keyed by `DeviceLocation` (ROADMAP row 137, seam S3).
15///
16/// The caller hands the executor the devices it holds (`with_cuda`, `with_vulkan`); the executor asks for the
17/// handle of a place when it allocates on, or copies to, that place. There is no other source: it used to find a
18/// handle by scanning the storage cache for a tensor that lived on the place, which made "a device exists" a
19/// property of "some tensor happens to be on it" and needed 0-byte anchor storages (step 3c removed both). A
20/// place nobody registered is a typed error at the lookup, naming the place.
21#[derive(Default)]
22pub struct DeviceRegistry {
23    #[cfg(feature = "cuda")]
24    cuda: HashMap<DeviceLocation, fuel_cuda_backend::CudaDevice>,
25    #[cfg(feature = "vulkan")]
26    vulkan: HashMap<DeviceLocation, std::sync::Arc<fuel_vulkan_backend::VulkanBackend>>,
27}
28
29/// The one entry whose identity is the same physical GPU as `wanted` (ROADMAP row 137 step 4b), or
30/// `None` when no entry, or more than one, matches. An entry whose identity is unknown never matches
31/// (unknown is not "same"). Never takes the first of several: that would reintroduce the order
32/// dependence this exists to remove.
33#[cfg(any(feature = "cuda", feature = "vulkan", test))]
34fn unique_by_identity<'a, T>(
35    entries: impl IntoIterator<Item = (Option<DeviceIdentity>, &'a T)>,
36    wanted: &DeviceIdentity,
37) -> Option<&'a T> {
38    let mut hits = entries
39        .into_iter()
40        .filter(|(id, _)| id.is_some_and(|i| i.same_physical_device(wanted)))
41        .map(|(_, handle)| handle);
42    let first = hits.next()?;
43    hits.next().is_none().then_some(first)
44}
45
46impl DeviceRegistry {
47    /// An empty registry (the state at the start of every realize).
48    pub fn new() -> Self {
49        Self::default()
50    }
51
52    /// Record the CUDA device a caller already holds, so a realize does not have to find it by scanning the
53    /// storage cache for a tensor that lives there (ROADMAP row 137, seam S3 step 3b). The place is the one
54    /// the device reports for itself.
55    #[cfg(feature = "cuda")]
56    pub fn with_cuda(mut self, device: fuel_cuda_backend::CudaDevice) -> Self {
57        self.cuda.insert(device.location(), device);
58        self
59    }
60
61    /// Record the Vulkan backend a caller already holds (see `Self::with_cuda`); the place is the backend's
62    /// own `gpu_id`.
63    #[cfg(feature = "vulkan")]
64    pub fn with_vulkan(
65        mut self,
66        backend: std::sync::Arc<fuel_vulkan_backend::VulkanBackend>,
67    ) -> Self {
68        self.vulkan.insert(
69            DeviceLocation::Vulkan {
70                gpu_id: backend.gpu_id,
71            },
72            backend,
73        );
74        self
75    }
76
77    /// The CUDA device a caller handed in for `gpu_id`, without looking in any cache. `None` when none was
78    /// registered for that place.
79    #[cfg(feature = "cuda")]
80    pub fn registered_cuda(&self, gpu_id: usize) -> Option<&fuel_cuda_backend::CudaDevice> {
81        self.cuda.get(&DeviceLocation::Cuda { gpu_id })
82    }
83
84    /// The Vulkan backend a caller handed in for `gpu_id`, without looking in any cache. `None` when none
85    /// was registered for that place.
86    #[cfg(feature = "vulkan")]
87    pub fn registered_vulkan(
88        &self,
89        gpu_id: usize,
90    ) -> Option<&std::sync::Arc<fuel_vulkan_backend::VulkanBackend>> {
91        self.vulkan.get(&DeviceLocation::Vulkan { gpu_id })
92    }
93
94    /// The registered Vulkan backend that drives the physical GPU `wanted` names (UUID, else PCI address),
95    /// whatever ordinal this process enumerated it at (ROADMAP row 137 step 4b). `None` when no, or more
96    /// than one, registered backend is that GPU. Nothing is stored: each lookup asks the registered
97    /// backends for their identity.
98    #[cfg(feature = "vulkan")]
99    pub fn registered_vulkan_by_identity(
100        &self,
101        wanted: &DeviceIdentity,
102    ) -> Option<&std::sync::Arc<fuel_vulkan_backend::VulkanBackend>> {
103        unique_by_identity(self.vulkan.values().map(|b| (b.identity(), b)), wanted)
104    }
105
106    /// The registered CUDA device that is the physical GPU `wanted` names (see
107    /// [`Self::registered_vulkan_by_identity`]); the identity may come from another API. `None` also when
108    /// the CUDA identity query itself fails.
109    #[cfg(feature = "cuda")]
110    pub fn registered_cuda_by_identity(
111        &self,
112        wanted: &DeviceIdentity,
113    ) -> Option<&fuel_cuda_backend::CudaDevice> {
114        let ids = fuel_cuda_backend::probe::device_identities().ok()?;
115        unique_by_identity(
116            self.cuda.iter().map(|(place, device)| {
117                let id = match place {
118                    DeviceLocation::Cuda { gpu_id } => ids.get(*gpu_id).copied().flatten(),
119                    _ => None,
120                };
121                (id, device)
122            }),
123            wanted,
124        )
125    }
126
127    /// The CUDA device registered for `gpu_id`, if any.
128    #[cfg(feature = "cuda")]
129    pub(crate) fn cuda(&self, gpu_id: usize) -> Option<fuel_cuda_backend::CudaDevice> {
130        self.registered_cuda(gpu_id).cloned()
131    }
132
133    /// The Vulkan backend registered for `gpu_id`, if any.
134    #[cfg(feature = "vulkan")]
135    pub(crate) fn vulkan(
136        &self,
137        gpu_id: usize,
138    ) -> Option<std::sync::Arc<fuel_vulkan_backend::VulkanBackend>> {
139        self.registered_vulkan(gpu_id).cloned()
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::unique_by_identity;
146    use fuel_ir::probe::DeviceIdentity;
147
148    fn id(b: u8) -> Option<DeviceIdentity> {
149        Some(DeviceIdentity {
150            uuid: Some([b; 16]),
151            pci: None,
152        })
153    }
154
155    #[test]
156    fn finds_the_entry_in_either_registration_order() {
157        let wanted = id(1).unwrap();
158        assert_eq!(
159            unique_by_identity([(id(1), &"a"), (id(2), &"b")], &wanted),
160            Some(&"a")
161        );
162        assert_eq!(
163            unique_by_identity([(id(2), &"b"), (id(1), &"a")], &wanted),
164            Some(&"a")
165        );
166    }
167
168    #[test]
169    fn unknown_entries_never_match_and_no_match_is_none() {
170        let wanted = id(1).unwrap();
171        assert_eq!(unique_by_identity([(None, &"x")], &wanted), None);
172        assert_eq!(unique_by_identity([(id(2), &"b")], &wanted), None);
173        let nobody = DeviceIdentity {
174            uuid: None,
175            pci: None,
176        };
177        assert_eq!(unique_by_identity([(None, &"x")], &nobody), None);
178    }
179
180    #[test]
181    fn two_matches_decline_instead_of_taking_the_first() {
182        let wanted = id(1).unwrap();
183        assert_eq!(
184            unique_by_identity([(id(1), &"a"), (id(2), &"b"), (id(1), &"c")], &wanted),
185            None
186        );
187    }
188}