fn

as_tensor

Tensor
as_tensor(data: object, dtype: DTypeLike = None, device: DeviceLike = None)
source

Convert data to a tensor, avoiding a copy when the source already matches.

Unlike tensor, as_tensor is "best-effort no-copy":

  • If data is already a Tensor with the requested dtype and device, it is returned unchanged.
  • If data is a NumPy array on CPU and dtype matches (or is None), the resulting tensor shares its storage with the array — mutations in either side are reflected in the other.
  • Otherwise the call delegates to tensor, which copies.

Parameters

dataobject
Source data — Python scalar / list, NumPy array, or Tensor.
dtypedtype | str | None
Target element type. None preserves the source dtype.
devicedevice | str | None
Target device. When the source already lives on a different device, a copy across the device boundary is performed.

Returns

Tensor

The input tensor or a freshly-constructed Lucid tensor.

Notes

as_tensor is the right choice in performance-sensitive code paths (e.g. DataLoader collate functions) where the input is already an ndarray and copying would be wasteful. For semantic clarity in library code that should never share storage, use tensor.

Examples

>>> import lucid
>>> import numpy as np
>>> arr = np.array([1.0, 2.0, 3.0])
>>> t = lucid.as_tensor(arr)            # no copy
>>> arr[0] = 99.0
>>> t                                    # reflects the mutation
Tensor([99.,  2.,  3.])
>>> x = lucid.tensor([1, 2, 3])
>>> lucid.as_tensor(x) is x              # already a Tensor, returned as-is
True