Device-aware allocation
Select CPU or an available accelerator before creating tensors and models.
PyTorch · Function
torch.device identifies where a tensor is or will be allocated. It supports device strings, type-plus-index construction, accelerator-relative integer indices, and temporary default-device contexts.
torch.device describes where a tensor is allocated or resides. Create one from a device string, a type plus ordinal, or an ordinal that uses the current accelerator type; it can also temporarily control the default allocation device in a context manager.
torch.device(device=None, index=None)| Name | Type | Description |
|---|---|---|
device | torch.device | str | int | Device specification: a string, a device type with an ordinal, or an ordinal using the current accelerator type. |
index | int | Optional device ordinal when the device type is supplied separately. |
A torch.device object representing the selected device.
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = torch.randn(2, 3, device=device)
print(x.device)Selects CUDA when available, otherwise CPU, then allocates a tensor on that device.
Select CPU or an available accelerator before creating tensors and models.
Temporarily make device-unspecified tensor constructors allocate on a chosen device.
Inspect where an existing tensor resides during debugging or device checks.
torch.device represents the device on which a tensor is or will be allocated. It contains a device type and optionally a device ordinal, such as cpu, cuda, mps, xpu, xla, or meta.
Follow-up: What does torch.device("cuda") mean? It refers to the current CUDA device, and remains tied to the current device rather than a fixed ordinal.
It accepts a device string, a device type with an ordinal, or an integer ordinal. An integer uses the current accelerator type, so it requires an accelerator to be detected.
Follow-up: Why can torch.device(0) fail? It raises RuntimeError when no accelerator is currently detected.
Used as a context manager, torch.device temporarily changes the default device for tensor allocations made inside the block. This is useful when code constructs tensors without passing device explicitly.
Follow-up: How does this differ from torch.set_default_device? The context-manager form is temporary, whereas torch.set_default_device changes the default globally.
torch.Tensor.devicetorch.cuda.current_devicetorch.cuda.set_devicetorch.set_default_device