Skip to content

API

pytrio.types.TensorData

python
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:

python
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 ​

FieldTypeDescription
datalist[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
shapelist[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 shape are forbidden, and the product of dimensions must equal len(data).
  • Non-integer floats are rejected when dtype="int64".
  • Automatic conversion accepts only numeric lists, integer/floating numpy.ndarray, or torch.Tensor.

Methods ​

from_numpy ​

python
@classmethod
def from_numpy(cls, array: np.ndarray) -> TensorData

Construct a TensorData from an integer or floating NumPy array (float32 / int64).

to_numpy ​

python
def to_numpy(self) -> np.ndarray

Restore a NumPy array with the declared dtype and shape.

from_torch ​

python
@classmethod
def from_torch(cls, tensor: "torch.Tensor") -> TensorData

Construct 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 ​

python
def tolist(self) -> list[object]

Return a copy of the flattened 1D value list (len(tensor_data) returns len(self.data)).

python
logprobs = fwdbwd_result.loss_fn_outputs[0]["logprobs"]
arr = logprobs.to_numpy()   # np.ndarray (float32)
vals = logprobs.tolist()    # list[float]