as_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 aTensorwhose dtype or device differs, it is converted asTensor.toconverts it, and the result stays connected todata's autograd graph — unliketensor, which copies into a detached leaf. - Anything else — Python data, NumPy arrays — goes through
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
Tensordata itself, a converted copy of it, or a freshly-constructed
Lucid tensor.
Notes
as_tensor is the right choice in code that may be handed either a
Tensor or raw data (e.g. a collate function): a Tensor that already has
the requested dtype and device passes through with no allocation at
all. For semantic clarity in library code that should never share
storage, use tensor.
Examples
>>> import lucid
>>> x = lucid.tensor([1.0, 2.0, 3.0])
>>> lucid.as_tensor(x) is x # already a Tensor, returned as-is
True
>>> lucid.as_tensor(x, dtype=lucid.float64).dtype
lucid.float64
>>> w = lucid.tensor([1.0, 2.0], requires_grad=True)
>>> lucid.as_tensor(w, dtype=lucid.float64).sum().backward()
>>> w.grad # the conversion stays in the graph
tensor([1., 1.])