fn
as_tensor
→Tensoras_tensor(data: object, dtype: DTypeLike = None, device: DeviceLike = None)Convert data to a tensor, avoiding a copy when the source already matches.
Unlike tensor, as_tensor is "best-effort no-copy":
- If
datais already aTensorwith the requesteddtypeanddevice, it is returned unchanged. - If
datais a NumPy array on CPU anddtypematches (or isNone), 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
dataobjectSource data — Python scalar / list, NumPy array, or Tensor.
dtypedtype | str | NoneTarget element type.
None preserves the source dtype.devicedevice | str | NoneTarget device. When the source already lives on a different device,
a copy across the device boundary is performed.
Returns
TensorThe 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