fuel_tensor/device.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Device abstraction for CPU, CUDA, and Metal backends.
3//!
4//! ```rust
5//! use fuel_tensor::Device;
6//! let dev = Device::cpu();
7//! assert!(dev.is_cpu());
8//! assert_eq!(dev.location(), fuel_tensor::DeviceLocation::Cpu);
9//! ```
10use crate::{DType, HostBuffer, Result, Shape, WithDType};
11use fuel_backend_contract::dyn_backend::DynBackendDevice;
12use fuel_cpu_backend::dyn_impl::CpuBackendDevice;
13use std::sync::Arc;
14
15pub use fuel_ir::DeviceLocation;
16
17/// A device on which tensors can be created and computations performed.
18///
19/// Internally this is an `Arc<dyn DynBackendDevice>` — a trait-object handle
20/// to the concrete backend device. CPU, CUDA, Metal, and arbitrary third-party
21/// backends are all accessed through this single type.
22///
23/// # Example
24///
25/// ```rust
26/// use fuel_tensor::{Device, DType};
27/// use fuel_tensor::lazy::Tensor;
28/// let dev = Device::cpu();
29/// let t = Tensor::zeros((2, 3), DType::F32, &dev)?;
30/// assert_eq!(t.shape().dims(), &[2, 3]);
31/// # Ok::<(), fuel_tensor::Error>(())
32/// ```
33#[derive(Clone, Debug)]
34pub struct Device {
35 pub(crate) inner: Arc<dyn DynBackendDevice>,
36 /// Weight storages uploaded to this device, keyed by the identity of their host array and shared by
37 /// every clone of the `Device` (ROADMAP row 172; see [`crate::const_residency`]).
38 pub(crate) weights: Arc<crate::const_residency::DeviceWeights>,
39}
40
41/// Trait for host array-like values that describe their shape and yield CPU storage.
42///
43/// Implemented for scalars, arrays, slices, and nested vecs up to 4 dimensions.
44/// It lets array-like Rust values report the [`Shape`] their data describes and
45/// materialize into a [`HostBuffer`] — the raw material a lazy tensor is built from.
46///
47/// # Example
48///
49/// ```rust
50/// use fuel_tensor::NdArray;
51/// // Scalars, arrays, and nested arrays all implement `NdArray` and report
52/// // the shape their data describes.
53/// assert_eq!(3.14f32.shape()?.dims(), &[] as &[usize]);
54/// assert_eq!((&[1f32, 2., 3.]).shape()?.dims(), &[3]);
55/// assert_eq!((&[[1f32, 2.], [3., 4.]]).shape()?.dims(), &[2, 2]);
56/// # Ok::<(), fuel_tensor::Error>(())
57/// ```
58pub trait NdArray {
59 /// Returns the shape determined by this array-like value.
60 fn shape(&self) -> Result<Shape>;
61
62 /// Converts this value into CPU storage.
63 fn to_cpu_storage(&self) -> HostBuffer;
64}
65
66impl<S: WithDType> NdArray for S {
67 fn shape(&self) -> Result<Shape> {
68 Ok(Shape::from(()))
69 }
70
71 fn to_cpu_storage(&self) -> HostBuffer {
72 S::to_cpu_storage(&[*self])
73 }
74}
75
76impl<S: WithDType, const N: usize> NdArray for &[S; N] {
77 fn shape(&self) -> Result<Shape> {
78 Ok(Shape::from(self.len()))
79 }
80
81 fn to_cpu_storage(&self) -> HostBuffer {
82 S::to_cpu_storage(self.as_slice())
83 }
84}
85
86impl<S: WithDType> NdArray for &[S] {
87 fn shape(&self) -> Result<Shape> {
88 Ok(Shape::from(self.len()))
89 }
90
91 fn to_cpu_storage(&self) -> HostBuffer {
92 S::to_cpu_storage(self)
93 }
94}
95
96impl<S: WithDType, const N: usize, const M: usize> NdArray for &[[S; N]; M] {
97 fn shape(&self) -> Result<Shape> {
98 Ok(Shape::from((M, N)))
99 }
100
101 fn to_cpu_storage(&self) -> HostBuffer {
102 S::to_cpu_storage_owned(self.concat())
103 }
104}
105
106impl<S: WithDType, const N1: usize, const N2: usize, const N3: usize> NdArray
107 for &[[[S; N3]; N2]; N1]
108{
109 fn shape(&self) -> Result<Shape> {
110 Ok(Shape::from((N1, N2, N3)))
111 }
112
113 fn to_cpu_storage(&self) -> HostBuffer {
114 let mut vec = Vec::with_capacity(N1 * N2 * N3);
115 for i1 in 0..N1 {
116 for i2 in 0..N2 {
117 vec.extend(self[i1][i2])
118 }
119 }
120 S::to_cpu_storage_owned(vec)
121 }
122}
123
124impl<S: WithDType, const N1: usize, const N2: usize, const N3: usize, const N4: usize> NdArray
125 for &[[[[S; N4]; N3]; N2]; N1]
126{
127 fn shape(&self) -> Result<Shape> {
128 Ok(Shape::from((N1, N2, N3, N4)))
129 }
130
131 fn to_cpu_storage(&self) -> HostBuffer {
132 let mut vec = Vec::with_capacity(N1 * N2 * N3 * N4);
133 for i1 in 0..N1 {
134 for i2 in 0..N2 {
135 for i3 in 0..N3 {
136 vec.extend(self[i1][i2][i3])
137 }
138 }
139 }
140 S::to_cpu_storage_owned(vec)
141 }
142}
143
144impl<S: WithDType> NdArray for Vec<S> {
145 fn shape(&self) -> Result<Shape> {
146 Ok(Shape::from(self.len()))
147 }
148
149 fn to_cpu_storage(&self) -> HostBuffer {
150 S::to_cpu_storage(self.as_slice())
151 }
152}
153
154impl<S: WithDType> NdArray for Vec<&[S]> {
155 fn shape(&self) -> Result<Shape> {
156 if self.is_empty() {
157 crate::bail!("empty array")
158 }
159 let n = self.len();
160 let m = self[0].len();
161 for v in self.iter() {
162 if v.len() != m {
163 crate::bail!("two elements have different len {m} {}", v.len())
164 }
165 }
166 Ok(Shape::from((n, m)))
167 }
168
169 fn to_cpu_storage(&self) -> HostBuffer {
170 let data = self.iter().copied().flatten().copied().collect::<Vec<_>>();
171 S::to_cpu_storage_owned(data)
172 }
173}
174
175impl<S: WithDType> NdArray for Vec<Vec<S>> {
176 fn shape(&self) -> Result<Shape> {
177 if self.is_empty() {
178 crate::bail!("empty array")
179 }
180 let n = self.len();
181 let m = self[0].len();
182 for v in self.iter() {
183 if v.len() != m {
184 crate::bail!("two elements have different len {m} {}", v.len())
185 }
186 }
187 Ok(Shape::from((n, m)))
188 }
189
190 fn to_cpu_storage(&self) -> HostBuffer {
191 let len: usize = self.iter().map(|v| v.len()).sum();
192 let mut dst = Vec::with_capacity(len);
193 for v in self.iter() {
194 dst.extend(v.iter().copied());
195 }
196 S::to_cpu_storage_owned(dst)
197 }
198}
199
200impl<S: WithDType> NdArray for Vec<Vec<Vec<S>>> {
201 fn shape(&self) -> Result<Shape> {
202 if self.is_empty() {
203 crate::bail!("empty array")
204 }
205 let shape0 = self[0].shape()?;
206 let n = self.len();
207 for v in self.iter() {
208 let shape = v.shape()?;
209 if shape != shape0 {
210 crate::bail!("two elements have different shapes {shape:?} {shape0:?}")
211 }
212 }
213 Ok(Shape::from([[n].as_slice(), shape0.dims()].concat()))
214 }
215
216 fn to_cpu_storage(&self) -> HostBuffer {
217 if self.is_empty() {
218 return S::to_cpu_storage_owned(vec![]);
219 }
220 let len: usize = self
221 .iter()
222 .map(|v| v.iter().map(|v| v.len()).sum::<usize>())
223 .sum();
224 let mut dst = Vec::with_capacity(len);
225 for v1 in self.iter() {
226 for v2 in v1.iter() {
227 dst.extend(v2.iter().copied());
228 }
229 }
230 S::to_cpu_storage_owned(dst)
231 }
232}
233
234impl<S: WithDType> NdArray for Vec<Vec<Vec<Vec<S>>>> {
235 fn shape(&self) -> Result<Shape> {
236 if self.is_empty() {
237 crate::bail!("empty array")
238 }
239 let shape0 = self[0].shape()?;
240 let n = self.len();
241 for v in self.iter() {
242 let shape = v.shape()?;
243 if shape != shape0 {
244 crate::bail!("two elements have different shapes {shape:?} {shape0:?}")
245 }
246 }
247 Ok(Shape::from([[n].as_slice(), shape0.dims()].concat()))
248 }
249
250 fn to_cpu_storage(&self) -> HostBuffer {
251 let len: usize = self
252 .iter()
253 .map(|v| {
254 v.iter()
255 .map(|v| v.iter().map(|v| v.len()).sum::<usize>())
256 .sum::<usize>()
257 })
258 .sum();
259 let mut dst = Vec::with_capacity(len);
260 for v1 in self.iter() {
261 for v2 in v1.iter() {
262 for v3 in v2.iter() {
263 dst.extend(v3.iter().copied());
264 }
265 }
266 }
267 S::to_cpu_storage_owned(dst)
268 }
269}
270
271impl Device {
272 /// Returns a CPU device.
273 ///
274 /// # Example
275 ///
276 /// ```rust
277 /// use fuel_tensor::Device;
278 /// let dev = Device::cpu();
279 /// assert!(dev.is_cpu());
280 /// ```
281 pub fn cpu() -> Self {
282 Device {
283 inner: Arc::new(CpuBackendDevice),
284 weights: Arc::new(crate::const_residency::DeviceWeights::new()),
285 }
286 }
287
288 /// Creates a device backed by a custom [`DynBackendDevice`].
289 ///
290 /// The device uses dynamic dispatch for all operations, enabling
291 /// third-party backends without modifying `fuel-core`.
292 pub fn custom(device: Arc<dyn DynBackendDevice>) -> Self {
293 Device {
294 inner: device,
295 weights: Arc::new(crate::const_residency::DeviceWeights::new()),
296 }
297 }
298
299 /// Counters of this device's weight residency: how many weight `Const`s were served from an
300 /// earlier upload, how many were uploaded, how many were evicted and how many are resident now.
301 /// Shared by every clone of this `Device`; always zero on a CPU device.
302 pub fn weight_residency_stats(&self) -> crate::const_residency::WeightResidencyStats {
303 self.weights
304 .0
305 .lock()
306 .unwrap_or_else(|p| p.into_inner())
307 .stats()
308 }
309
310 /// **The unload call.** Drop every resident weight upload of this device, so the card gets the
311 /// model's memory back at once. Call it when a model is unloaded or replaced and the process goes on
312 /// using the device: without it a dropped model's weights are only evicted at the next seeding on
313 /// this device (see [`crate::const_residency`]), and one that is still loaded is only evicted when
314 /// the byte cap forces it out. The next realize that needs a weight uploads it again. Storages a
315 /// running realize (or a held decode session) still holds stay alive until it ends.
316 pub fn clear_weight_residency(&self) {
317 self.weights
318 .0
319 .lock()
320 .unwrap_or_else(|p| p.into_inner())
321 .clear();
322 }
323
324 /// Borrow the underlying `Arc<dyn DynBackendDevice>`.
325 ///
326 /// Phase 7.5 work item G2: fuel-graph's slot-populating
327 /// constructors (`Tensor::from_f32`, `const_f32_like`, etc.) take
328 /// a `&Arc<dyn DynBackendDevice>` so they can allocate Storage on
329 /// the right device without depending on fuel-core. Callers that
330 /// hold a `&fuel_tensor::Device` thread it through with
331 /// `dev.as_dyn()`.
332 pub fn as_dyn(&self) -> &Arc<dyn DynBackendDevice> {
333 &self.inner
334 }
335
336 /// Returns `true` if this is a custom (third-party) device.
337 pub fn is_custom(&self) -> bool {
338 !self.is_cpu() && !self.is_cuda() && !self.is_metal()
339 }
340
341 /// Sets the random seed for this device's random number generator.
342 pub fn set_seed(&self, seed: u64) -> Result<()> {
343 self.inner.set_seed_dyn(seed)
344 }
345
346 /// Returns the current random seed for this device.
347 pub fn get_current_seed(&self) -> Result<u64> {
348 self.inner.get_current_seed_dyn()
349 }
350
351 /// Returns `true` if both devices refer to the same physical device.
352 ///
353 /// # Example
354 ///
355 /// ```rust
356 /// use fuel_tensor::Device;
357 /// assert!(Device::cpu().same_device(&Device::cpu()));
358 /// ```
359 pub fn same_device(&self, rhs: &Self) -> bool {
360 self.inner.same_device_dyn(&*rhs.inner)
361 }
362
363 /// Returns the physical [`DeviceLocation`] for this device.
364 ///
365 /// # Example
366 ///
367 /// ```rust
368 /// use fuel_tensor::{Device, DeviceLocation};
369 /// assert_eq!(Device::cpu().location(), DeviceLocation::Cpu);
370 /// ```
371 pub fn location(&self) -> DeviceLocation {
372 self.inner.location_dyn()
373 }
374
375 /// Returns `true` if this is the CPU device.
376 ///
377 /// # Example
378 ///
379 /// ```rust
380 /// use fuel_tensor::Device;
381 /// assert!(Device::cpu().is_cpu());
382 /// ```
383 pub fn is_cpu(&self) -> bool {
384 matches!(self.location(), DeviceLocation::Cpu)
385 }
386
387 /// Returns `true` if this is a CUDA device.
388 ///
389 /// # Example
390 ///
391 /// ```rust
392 /// use fuel_tensor::Device;
393 /// assert!(!Device::cpu().is_cuda());
394 /// ```
395 pub fn is_cuda(&self) -> bool {
396 matches!(self.location(), DeviceLocation::Cuda { .. })
397 }
398
399 /// Returns `true` if this is a Metal device.
400 ///
401 /// # Example
402 ///
403 /// ```rust
404 /// use fuel_tensor::Device;
405 /// assert!(!Device::cpu().is_metal());
406 /// ```
407 pub fn is_metal(&self) -> bool {
408 matches!(self.location(), DeviceLocation::Metal { .. })
409 }
410
411 /// Returns `true` if this device has native BF16 support.
412 ///
413 /// # Example
414 ///
415 /// ```rust
416 /// use fuel_tensor::Device;
417 /// // CPU does not have native BF16 support
418 /// assert!(!Device::cpu().supports_bf16());
419 /// ```
420 pub fn supports_bf16(&self) -> bool {
421 self.inner.supports_bf16()
422 }
423
424 /// Returns [`DType::BF16`] if supported, otherwise [`DType::F32`].
425 ///
426 /// # Example
427 ///
428 /// ```rust
429 /// use fuel_tensor::{Device, DType};
430 /// assert_eq!(Device::cpu().bf16_default_to_f32(), DType::F32);
431 /// ```
432 pub fn bf16_default_to_f32(&self) -> DType {
433 if self.supports_bf16() {
434 DType::BF16
435 } else {
436 DType::F32
437 }
438 }
439
440 /// Synchronizes the device, waiting for all pending operations to complete.
441 ///
442 /// This is a no-op on CPU.
443 ///
444 /// ```rust
445 /// use fuel_tensor::Device;
446 /// Device::cpu().synchronize()?;
447 /// # Ok::<(), fuel_tensor::Error>(())
448 /// ```
449 pub fn synchronize(&self) -> Result<()> {
450 self.inner.synchronize_dyn()
451 }
452}