pytrio.types.TensorData
class TensorData(BaseModel):
data: list[float] | list[int]
dtype: Literal["float32", "int64"]
shape: list[int] = Field(default_factory=list)TensorData is the strongly typed numeric tensor exchanged across the SDK boundary, used in Datum.loss_fn_inputs and returned inside ForwardBackwardOutput.loss_fn_outputs (such as output["logprobs"]).
When constructing a Datum, you do not need to wrap inputs manually: the SDK automatically converts numeric Python lists, numpy.ndarray, and torch.Tensor objects into TensorData:
import numpy as np
import pytrio as trio
datum = trio.Datum(
model_input=trio.ModelInput.from_ints([1, 2, 3]),
loss_fn_inputs={
"target_tokens": [2, 3, 4], # converted to int64 TensorData
"weights": np.array([0.0, 1.0, 1.0], np.float32), # converted to float32 TensorData
},
)Fields
| Field | Type | Description |
|---|---|---|
data | list[float] | list[int] | Row-major flattened 1D list of values |
dtype | "float32" | "int64" | Supported dtype; floating arrays are normalized to float32 and integer arrays to int64 |
shape | list[int] | Logical tensor dimensions; inferred as [len(data)] when omitted. Explicit shape=[] represents a rank-0 scalar tensor (useful for local custom-loss inputs) |
Validation rules
- Negative dimensions in
shapeare forbidden, and the product of dimensions must equallen(data). - Non-integer floats are rejected when
dtype="int64". - Automatic conversion accepts only numeric lists, integer/floating
numpy.ndarray, ortorch.Tensor.
Methods
from_numpy
@classmethod
def from_numpy(cls, array: np.ndarray) -> TensorDataConstruct a TensorData from an integer or floating NumPy array (float32 / int64).
to_numpy
def to_numpy(self) -> np.ndarrayRestore a NumPy array with the declared dtype and shape.
from_torch
@classmethod
def from_torch(cls, tensor: "torch.Tensor") -> TensorDataConstruct a TensorData from a PyTorch tensor on any device (calls detach().cpu() and casts to float32 or int64). Raises ImportError if torch is not installed.
tolist
def tolist(self) -> list[object]Return a copy of the flattened 1D value list (len(tensor_data) returns len(self.data)).
logprobs = fwdbwd_result.loss_fn_outputs[0]["logprobs"]
arr = logprobs.to_numpy() # np.ndarray (float32)
vals = logprobs.tolist() # list[float]