Skip to content

[Feature] A pydantic tensorclass implementation #1342

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Conversation

vmoens
Copy link
Collaborator

@vmoens vmoens commented Jun 11, 2025

Test:

from tensordict.tensorclass_v2 import TensorClass, NestedList
import torch
from torch import Tensor


class MyClass(TensorClass):
    a: int | NestedList[int]  # NonTensorStack
    b: str | NestedList[str]  # Now accepts str or list[str] or list[list[str]] etc
    c: Tensor
    d: str  # MetaData


# Default (empty) batch size
model = MyClass(a=1, b="hello", c=torch.tensor([1.0, 2.0, 3.0]), d="a string")
print(f"{model=}")
print(f"Model attributes: a={model.a}, b={model.b}")
print(f"Model tensor c={model.c}")
print(f"TensorDict contents: {model._tensordict}")
print(f"Default batch_size: {model.batch_size}")

# Integer batch size
model = MyClass(
    a=[1, 2],
    b=["hello", "world"],
    c=torch.tensor([[1.0], [2.0]]),  # 2x1 tensor
    d="a string",
    batch_size=2,
)
print(f"{model=}")
print(f"{model._tensordict=}")
print(f"Integer batch_size: {model.batch_size}")

print(f"{model.to_tensordict()=}")
print(f"{model.cpu()=}")
print(f"{model.to('mps')=}")
print(f"{model.unbind(0)=}")
print(f"{model.split(1)=}")
print(f"{model.chunk(2)=}")

@facebook-github-bot facebook-github-bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Jun 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants