A dict[str, torch.Tensor] that behaves like one tensor.
Actively maintained. Last release 3 weeks ago, commits in 22 of the last 26 weeks. A safe choice.
pip install tensordictTensorDict
A dict[str, torch.Tensor] that behaves like one tensor.
PyTorch code that handles groups of tensors, such as a training batch, a particle system, or a batch of graphs, usually repeats every operation for every tensor, and nested dicts need recursion. A TensorDict holds the group as one object:
batch = TensorDict(
{"image": images, "label": labels, "text": {"tokens": tokens, "mask": mask}},
batch_size=[32], # Optionally, TensorDicts can be batched
)
batch = batch.to("cuda") # moves every tensor, nested ones too
train, val = batch[:24], batch[24:] # slices every tensor
shuffled = batch[torch.randperm(len(batch))] # one permutation for all of them
pairs = torch.stack([batch, batch]) # batch_size [2, 32]
batch["text", "mask"] # nested keys are tuples
flat = batch.flatten_keys(".") # keys: image, label, text.tokens, text.mask
batch["score"] = torch.ones(31) # RuntimeError: batch dimension mismatch
The tensors share their leading dimensions, the batch size, so indexing,
reshaping, stacking, .to(device), saving, and torch.compile apply to all of
them at once.
TensorClass does the same for a class with typed fields and methods, like a dataclass. A method written once runs on one item or on a batch of any shape, and compiles:
import torch
from tensordict import TensorClass
class Particles(TensorClass):
pos: torch.Tensor # [*batch, 3]
vel: torch.Tensor # [*batch, 3]
mass: torch.Tensor # [*batch]
def step(self, force: torch.Tensor, dt: float) -> "Particles":
vel = self.vel + dt * force / self.mass.unsqueeze(-1)
return Particles(pos=self.pos + dt * vel, vel=vel, mass=self.mass, batch_size=self.batch_size)
# 64 systems of 1,000 particles each
systems = Particles(pos=torch.randn(64, 1000, 3), vel=torch.zeros(64, 1000, 3),
mass=torch.ones(64, 1000), batch_size=[64, 1000])
systems = systems.step(torch.randn(64, 1000, 3), dt=0.01) # all 64 systems
one = systems[0].step(torch.randn(1000, 3), dt=0.01) # one system
print(type(one).__name__, one.batch_size) # Particles torch.Size([1000])
pairs = torch.stack([systems, systems]) # batch_size [2, 64, 1000]
step = torch.compile(Particles.step, fullgraph=True)
systems = step(systems, torch.randn(64, 1000, 3), 0.01)
systems = systems.to("cuda" if torch.cuda.is_available() else "cpu") # moves every field