pub struct Device { /* private fields */ }Expand description
A high-level device handle for tensor operations.
Device provides a unified interface to interact with the underlying compute backend.
Autodiff support is a property of the device rather than a separate type parameter.
Enable the autodiff feature to add automatic differentiation support to devices.
§Backend selection
Enable the desired backend via Cargo feature flags, then call the corresponding factory method:
// Default CUDA device (requires the `cuda` feature).
let device = Device::cuda(DeviceIndex::Default);
// CUDA device at hardware index 1.
let device = Device::cuda(1);
// WGPU with explicit selector (requires `wgpu`/`vulkan`/`metal`/`webgpu`).
let device = Device::wgpu(DeviceKind::DiscreteGpu(0));
// Default device for whichever backend is enabled.
let device = Default::default();Available factory methods (each gated by its matching Cargo feature):
Device::cpu, Device::cuda / Device::rocm / Device::libtorch_cuda
(take an integer index or a DeviceIndex), Device::wgpu /
Device::vulkan / Device::metal / Device::webgpu (take a
DeviceKind), Device::flex, Device::ndarray, Device::libtorch,
Device::libtorch_mps, Device::libtorch_vulkan.
§Autodiff
Requires autodiff feature.
Gradient computation is opt-in for a device:
let device = Device::default().autodiff();
// Tensors created on this device will track gradients
let x = Tensor::<1>::from_floats([1.0, 2.0, 3.0], &device);Implementations§
Source§impl Device
impl Device
Sourcepub fn new(device: impl Into<DispatchDevice>) -> Self
pub fn new(device: impl Into<DispatchDevice>) -> Self
Wrap a backend-specific device in a unified Device.
Used by:
- the backend-specific factory methods below (
Device::cuda, etc.) — these are the recommended entry points for downstream code; - burn-tensor’s bridge ops, which already hold a
DispatchDeviceand just need to wrap it; - direct callers (tests, type-erased helpers) that have a concrete backend device type at hand.
Anything convertible into DispatchDevice is accepted, including
DispatchDevice itself.
Sourcepub fn as_dispatch(&self) -> &DispatchDevice
pub fn as_dispatch(&self) -> &DispatchDevice
Borrow the underlying DispatchDevice.
The inverse of Device::new. Useful to backend-extension authors who need to dispatch on
the concrete backend variant (e.g. matching DispatchDevice::Remote(_)).
Source§impl Device
impl Device
Sourcepub fn sync(&self) -> Result<(), ExecutionError>
pub fn sync(&self) -> Result<(), ExecutionError>
Synchronize the device, waiting for all pending operations to complete.
§Errors
Returns an ExecutionError if an operation failed to execute.
Sourcepub fn flush(&self)
pub fn flush(&self)
Flush the device’s pending operations, handing them off for execution without waiting for them to complete.
Backends that buffer work hold registered operations in a local queue until enough
accumulate: the fusion backend batches ops to build optimizations, and the remote backend
batches them before sending them over the network. flush forces that queue out now — the
fusion backend processes its pending optimizations and the remote backend sends its batch to
the server.
Unlike sync, this does not block on results — it only ensures buffered
operations are dispatched instead of sitting idle. Eager backends, which execute each
operation as it is registered, have nothing buffered and treat this as a no-op.
Sourcepub fn seed(&self, seed: u64)
pub fn seed(&self, seed: u64)
Seeds the random number generator for this device.
Seeding before tensor operations that involve randomness (e.g. Tensor::random)
makes those operations reproducible in a single-threaded program.
§Note
Depending on the backend, the seed may be applied globally rather than scoped to this specific device. It is guaranteed that at least this device will be seeded.
§Example
let device = Default::default();
device.seed(42);
let t = Tensor::<1>::random([8], Distribution::Default, &device);Sourcepub fn is_autodiff(&self) -> bool
pub fn is_autodiff(&self) -> bool
Sourcepub fn supports_dtype(&self, dtype: impl Into<DType>) -> bool
pub fn supports_dtype(&self, dtype: impl Into<DType>) -> bool
Returns true if this device supports dtype for general computation:
storage, conversion, and arithmetic.
A type can be less than generally supported — bf16 on a Vulkan device,
for example, is often storable and convertible but has no arithmetic
(SPIR-V’s SPV_KHR_bfloat16 permits only conversions, dot products,
and cooperative-matrix use). Computing in such a type produces
backend-dependent garbage, so check before selecting a reduced
precision:
let dtype = if device.supports_dtype(FloatDType::BF16) {
FloatDType::BF16
} else {
FloatDType::F32
};Sourcepub fn memory_persistent_allocations<Output: Send, Input: Send, Func: Fn(Input) -> Output + Send>(
&self,
input: Input,
func: Func,
) -> Output
pub fn memory_persistent_allocations<Output: Send, Input: Send, Func: Fn(Input) -> Output + Send>( &self, input: Input, func: Func, ) -> Output
Sets the current allocation mode to persistent.
Sourcepub fn memory_cleanup(&self)
pub fn memory_cleanup(&self)
Triggers a memory cleanup on this device.
The amount of memory reclaimed depends on the allocator implementation. Calling this method does not guarantee that any memory will be freed.
Sourcepub fn staging<'a, Iter>(&self, data: Iter)where
Iter: Iterator<Item = &'a mut TensorData>,
pub fn staging<'a, Iter>(&self, data: Iter)where
Iter: Iterator<Item = &'a mut TensorData>,
Prepares the given data for transfer between the CPU and accelerator devices such as GPUs.
Depending on the backend, the data may be transferred to pinned memory or another transfer-optimized format to improve transfer performance.
Sourcepub fn settings(&self) -> DeviceSettings
pub fn settings(&self) -> DeviceSettings
Returns the DeviceSettings for this device.
Settings include the default float and integer data types used when creating tensors on this device.
See configure to configure them.
Sourcepub fn configure(
&mut self,
config: impl Into<DeviceConfig>,
) -> Result<(), DeviceError>
pub fn configure( &mut self, config: impl Into<DeviceConfig>, ) -> Result<(), DeviceError>
Configures the settings for this device.
This configures the dtype used when no explicit type is specified at tensor creation time.
Settings can only be initialized once per device, and must happen before any
tensor is created on the device. The first tensor operation will lock the device
to its defaults, causing subsequent initializations attempt to return
DeviceError::AlreadyInitialized.
§Errors
Returns DeviceError::AlreadyInitialized if settings have already been set
for this device (either by a prior call or because a tensor operation has
already occurred).
§Example
let device = Default::default();
device.configure((FloatDType::F16, IntDType::I32))?
// Float tensors will now use F16
let floats = Tensor::<2>::zeros([2, 3], &device);
// Int tensors will now use I32
let ints = Tensor::<2, Int>::zeros([2, 3], &device);Sourcepub fn enumerate(filter: impl Into<DeviceFilter>) -> Devices
pub fn enumerate(filter: impl Into<DeviceFilter>) -> Devices
Retrieves all available Devices that match the given DeviceType filter.
Local backends (CPU, CUDA, WGPU, …) enumerate the hardware found on the host. The
Remote variant instead lists every device hosted by the
burn-remote server at the given address — it connects to the server to learn how
many devices it exposes:
// Every CUDA device on this machine.
let local = Device::enumerate(DeviceType::Cuda);
// Every device hosted by a remote server.
let remote = Device::enumerate(DeviceType::remote_websocket("ws://host:3000"));
// Filters combine with `|`.
let both = Device::enumerate(DeviceType::Cuda | DeviceType::remote_websocket("ws://host:3000"));Trait Implementations§
impl Eq for Device
Source§impl From<&Device> for TensorCreationOptions
impl From<&Device> for TensorCreationOptions
Source§impl PartialEq for Device
impl PartialEq for Device
Source§fn eq(&self, other: &Self) -> bool
fn eq(&self, other: &Self) -> bool
Compares devices based on hardware identity.
Returns true if both devices represent the same compute resource.
Note that this comparison ignores autodiff and checkpointing settings.
To check if two devices have identical capabilities, check Device::is_autodiff.
Auto Trait Implementations§
impl Freeze for Device
impl RefUnwindSafe for Device
impl Send for Device
impl Sync for Device
impl Unpin for Device
impl UnsafeUnpin for Device
impl UnwindSafe for Device
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more