Device

Struct Device 

Source
pub struct Device { /* private fields */ }
Expand description

Device representation for tensor operations

A device specifies where tensors are located and where operations should be performed. Each device has a type (CPU or CUDA) and an index (0 for CPU, GPU ID for CUDA). The device system provides thread-safe context management and automatic resource cleanup.

§Fields

  • device_type - The type of device (CPU or CUDA)
  • index - Device index (0 for CPU, GPU ID for CUDA)

§Examples

use train_station::Device;

// Create CPU device
let cpu = Device::cpu();
assert!(cpu.is_cpu());
assert_eq!(cpu.index(), 0);
assert_eq!(cpu.to_string(), "cpu");

// Create CUDA device (when feature enabled)
#[cfg(feature = "cuda")]
{
    if train_station::cuda_is_available() {
        let cuda = Device::cuda(0);
        assert!(cuda.is_cuda());
        assert_eq!(cuda.index(), 0);
        assert_eq!(cuda.to_string(), "cuda:0");
    }
}

§Thread Safety

This type is thread-safe and can be shared between threads. Device contexts are managed per-thread using thread-local storage.

§Memory Layout

The device struct is small and efficient:

  • Size: 16 bytes (8 bytes for enum + 8 bytes for index)
  • Alignment: 8 bytes
  • Copy semantics: Implements Copy for efficient passing

Implementations§

Source§

impl Device

Source

pub fn cpu() -> Self

Create a CPU device

CPU devices always have index 0 and are always available regardless of feature flags or system configuration.

§Returns

A Device representing the CPU (always index 0)

§Examples
use train_station::Device;

let device = Device::cpu();
assert!(device.is_cpu());
assert_eq!(device.index(), 0);
assert_eq!(device.device_type(), train_station::DeviceType::Cpu);
Examples found in repository?
examples/getting_started/tensor_basics.rs (line 201)
179fn demonstrate_utility_functions() {
180    println!("\n--- Utility Functions ---");
181
182    let tensor = Tensor::from_slice(&[1.0, 2.0, 3.0, 4.0], vec![2, 2]).unwrap();
183
184    // Basic properties
185    println!("Shape: {:?}", tensor.shape().dims());
186    println!("Size: {}", tensor.size());
187    println!("Is contiguous: {}", tensor.is_contiguous());
188    println!("Device: {:?}", tensor.device());
189
190    // Mathematical operations
191    let sum = tensor.sum();
192    println!("Sum: {}", sum.value());
193
194    let mean = tensor.mean();
195    println!("Mean: {}", mean.value());
196
197    let norm = tensor.norm();
198    println!("Norm: {}", norm.value());
199
200    // Device placement
201    let cpu_tensor = Tensor::zeros_on_device(vec![3, 3], train_station::Device::cpu());
202    println!(
203        "CPU tensor: shape {:?}, device: {:?}",
204        cpu_tensor.shape().dims(),
205        cpu_tensor.device()
206    );
207}
Source

pub fn cuda(index: usize) -> Self

Create a CUDA device

Creates a device representing a specific CUDA GPU. The device index must be valid for the current system configuration.

§Arguments
  • index - CUDA device index (0-based)
§Returns

A Device representing the specified CUDA device

§Panics

Panics in the following cases:

  • CUDA feature is not enabled (--features cuda not specified)
  • CUDA is not available on the system
  • Device index is out of range (>= number of available devices)
§Examples
use train_station::Device;

// CPU device is always available
let cpu = Device::cpu();

// CUDA device (when feature enabled and available)
#[cfg(feature = "cuda")]
{
    if train_station::cuda_is_available() {
        let device_count = train_station::cuda_device_count();
        if device_count > 0 {
            let cuda = Device::cuda(0);
            assert!(cuda.is_cuda());
            assert_eq!(cuda.index(), 0);
        }
    }
}
Source

pub fn device_type(&self) -> DeviceType

Get the device type

§Returns

The DeviceType enum variant representing this device’s type

§Examples
use train_station::{Device, DeviceType};

let cpu = Device::cpu();
assert_eq!(cpu.device_type(), DeviceType::Cpu);
Source

pub fn index(&self) -> usize

Get the device index

§Returns

The device index (0 for CPU, GPU ID for CUDA)

§Examples
use train_station::Device;

let cpu = Device::cpu();
assert_eq!(cpu.index(), 0);

#[cfg(feature = "cuda")]
{
    if train_station::cuda_is_available() {
        let cuda = Device::cuda(0);
        assert_eq!(cuda.index(), 0);
    }
}
Source

pub fn is_cpu(&self) -> bool

Check if this is a CPU device

§Returns

true if this device represents a CPU, false otherwise

§Examples
use train_station::Device;

let cpu = Device::cpu();
assert!(cpu.is_cpu());
assert!(!cpu.is_cuda());
Source

pub fn is_cuda(&self) -> bool

Check if this is a CUDA device

§Returns

true if this device represents a CUDA GPU, false otherwise

§Examples
use train_station::Device;

let cpu = Device::cpu();
assert!(!cpu.is_cuda());
assert!(cpu.is_cpu());

Trait Implementations§

Source§

impl Clone for Device

Source§

fn clone(&self) -> Device

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Device

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Device

Source§

fn default() -> Self

Create the default device (CPU)

§Returns

A CPU device (same as Device::cpu())

§Examples
use train_station::Device;

let device = Device::default();
assert!(device.is_cpu());
assert_eq!(device, Device::cpu());
Source§

impl Display for Device

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Format the device as a string

§Returns

String representation of the device:

  • "cpu" for CPU devices
  • "cuda:{index}" for CUDA devices
§Examples
use train_station::Device;

let cpu = Device::cpu();
assert_eq!(cpu.to_string(), "cpu");

#[cfg(feature = "cuda")]
{
    if train_station::cuda_is_available() {
        let cuda = Device::cuda(0);
        assert_eq!(cuda.to_string(), "cuda:0");
    }
}
Source§

impl From<DeviceType> for Device

Source§

fn from(device_type: DeviceType) -> Self

Convert DeviceType to Device with index 0

§Arguments
  • device_type - The device type to convert
§Returns

A Device with the specified type and index 0

§Panics

Panics if device_type is DeviceType::Cuda and CUDA is not available or the feature is not enabled.

§Examples
use train_station::{Device, DeviceType};

let cpu_type = DeviceType::Cpu;
let cpu_device = Device::from(cpu_type);
assert!(cpu_device.is_cpu());
assert_eq!(cpu_device.index(), 0);
Source§

impl FromFieldValue for Device

Source§

fn from_field_value( value: FieldValue, field_name: &str, ) -> SerializationResult<Self>

Convert FieldValue to Device for deserialization

§Arguments
  • value - FieldValue containing device object
  • field_name - Name of the field for error reporting
§Returns

Device instance or error if invalid

Source§

impl Hash for Device

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Device

Source§

fn eq(&self, other: &Device) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl ToFieldValue for Device

Source§

fn to_field_value(&self) -> FieldValue

Convert Device to FieldValue for serialization

§Returns

Object containing device type and index

Source§

impl Copy for Device

Source§

impl Eq for Device

Source§

impl StructuralPartialEq for Device

Auto Trait Implementations§

§

impl Freeze for Device

§

impl RefUnwindSafe for Device

§

impl Send for Device

§

impl Sync for Device

§

impl Unpin for Device

§

impl UnwindSafe for Device

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.