Skip to content

.to_device()

Copy this tensor to the target device, returning a new leaf Tensor.

Transfers the underlying array to the backend of the target device (e.g. from numpy to cupy when moving from CPU to CUDA). The returned tensor is a new leaf with no gradient history — it is detached from the computation graph of the original tensor.

Parameters:

  • device (str) –

    Target device string, e.g. "cpu" or "cuda:0".

Returns:

  • 'Tensor'

    A new Tensor on the target device with the same dtype and

  • 'Tensor'

    comp_grad as the original.

Raises:

  • ValueError

    If the device string is invalid.

  • RuntimeError

    If this tensor is unrealized. Call .realize() first.

Example

import simplegrad as sg

x = sg.Tensor([1.0, 2.0], device="cpu")
x_gpu = x.to_device("cuda:0")
print(x_gpu.device)  # cuda:0