Move tensors between devices
Prepare model inputs or parameters for a selected accelerator or CPU.
PyTorch · Module
Converts a tensor to a requested dtype, device, or both. It can also match another tensor's dtype and device, and may avoid copying when no conversion is needed.
Call to with a dtype, device, or another tensor to obtain a tensor configured accordingly. If the requested dtype and device already match, the original tensor is returned; otherwise, PyTorch creates a converted copy. Conversion to an integer dtype disables gradient tracking because integer tensors cannot require gradients.
torch.Tensor.to(*args, **kwargs) → Tensor| Name | Type | Description |
|---|---|---|
dtype | torch.dtype, optional | Target data type for conversion. |
device | torch.device, optional | Target device for the returned tensor. |
non_blocking | bool, optional | Whether the conversion may be performed asynchronously. |
copy | bool, optional | Whether to force creation of a copy. |
memory_format | torch.memory_format, optional | Desired memory format of the returned tensor. |
other | torch.Tensor | Tensor whose dtype and device should be matched. |
A Tensor converted to the requested dtype and/or device, or matching another tensor; it may be the original tensor when no change is required.
Tensor.to to change a tensor's data type, device, or both.requires_grad, since integer tensors cannot participate in gradient tracking.import torch
x = torch.tensor([1.0, 2.0])
y = x.to(dtype=torch.float64, device="cpu")
print(y.dtype)
print(y.device)Creates a floating-point tensor and converts it to float64 on the CPU.
Prepare model inputs or parameters for a selected accelerator or CPU.
Standardize precision before arithmetic or model execution.
Create a tensor with the same dtype and device as an existing reference tensor.
Request asynchronous transfers where the caller can manage synchronization.
Tensor.to do, and what forms of input can it accept?Tensor.to converts a tensor's dtype and/or device. It can receive a dtype, a device with optional dtype, or another tensor whose dtype and device should be matched.
Follow-up: What happens when the requested dtype and device already match? The method returns the original tensor rather than making an unnecessary copy.
non_blocking and copy affect conversion?By default, non_blocking is False, and copy is False. Setting copy=True forces a new tensor even when the source already has the requested dtype and device.
Follow-up: Why might copy=True matter? It guarantees distinct storage, which is useful when callers require an independent tensor object.
Tensor.to?The method preserves the tensor's memory format by default through torch.preserve_format. An explicit memory_format can request the layout for the returned tensor.
Follow-up: What limitation applies to integer conversion? A tensor converted to an integer dtype cannot retain requires_grad=True.
torch.dtypetorch.devicetorch.memory_formattorch.preserve_formatTensor.requires_grad