Skip to content

Devices

Device management utilities for PyTorch tensors.

This module provides device selection (CPU by default, accelerators on request) and tensor coercion.

get_device(device=None)

Get the appropriate PyTorch device.

The default is the CPU. Accelerators are opt-in: pass "auto" for the first available of CUDA, MPS and CPU, or name the device. (Up to 1.1.0 None meant "auto"; on the laptops where it was measured the CPU was 6-30x faster than MPS for the online detector, and the offline detector cannot run on MPS at all, so the automatic choice was a poor default.)

Parameters:

Name Type Description Default
device str, torch.device, or None

Desired device. None selects the CPU; "auto" selects the best available device.

None

Returns:

Type Description
device

The selected device.

Examples:

>>> get_device()
device(type='cpu')
>>> device = get_device("auto")  # CUDA, then MPS, then CPU
>>> device = get_device("cuda:0")  # a specific GPU

to_tensor(data, device=None, dtype=None)

Convert data to PyTorch tensor on specified device.

Without an explicit dtype, floating-point input keeps its precision: float64 NumPy arrays, Python floats and float64 tensors stay float64, float32 stays float32. Integer and boolean input becomes float32, and complex input stays complex (so detectors can reject it). On MPS, which has no float64, real input becomes float32. Non-tensor input is always copied, so the result never aliases the caller's array or list (a tensor already on the right device and dtype is returned as is). (Versions up to 1.1.0 made everything float32, so a float64 NumPy series far from zero lost its low digits before any detector saw it.)

Parameters:

Name Type Description Default
data array - like

Input data to convert to tensor.

required
device str, torch.device, or None

Target device for the tensor.

None
dtype dtype

Desired data type for the tensor; overrides the rule above.

None

Returns:

Type Description
Tensor

Converted tensor on the specified device.

Examples:

>>> import numpy as np
>>> to_tensor(np.array([1, 2, 3]), device="cpu").dtype
torch.float32
>>> to_tensor(np.array([1.5, 2.5]), device="cpu").dtype
torch.float64
>>> tensor = to_tensor(np.array([1.5]), device='cuda', dtype=torch.float32)

ensure_tensor(data, device=None)

Ensure data is a PyTorch tensor, converting if necessary.

Parameters:

Name Type Description Default
data array - like or Tensor

Input data.

required
device str, torch.device, or None

Target device for the tensor.

None

Returns:

Type Description
Tensor

Tensor on the specified device.

get_device_info()

Get information about available devices.

Returns:

Type Description
dict

Dictionary containing device information.

Examples:

>>> info = get_device_info()
>>> print(f"CUDA available: {info['cuda_available']}")
>>> print(f"Device count: {info['device_count']}")