Rate this Page
★ ★ ★ ★ ★

tensordict: containers and functions#

This page lists the tensordict containers, and the methods that they all share, grouped by task. Each group also lists the functions of the tensordict module for its task. A TensorDict is a dict[str, torch.Tensor] that behaves like one tensor. Its entries share their leading dimensions, the batch size, and an operation such as indexing, reshaping, or to() applies to every entry. For an introduction, see What is TensorDict?.

Containers#

TensorDictBase is the abstract base class of all tensordicts. Its subclasses keep their entries in different places:

MemoryMappedTensor is not a tensordict. It is a tensor whose data is in a file, and the type of the entries of a memory-mapped tensordict.

TensorCollection is the common base class of the tensordicts and the subclasses of TensorClass: the type hint for “a tensordict or a tensorclass”.

Other containers have their own pages: TensorClass, the class form with typed fields and methods, and non-tensor data (tensorclass and non-tensor data), TypedTensorDict (TypedTensorDict), and the key-value stores (Key-value stores and UCXX). To choose one, see Which container should I use?.

TensorDictBase(*args, **kwargs)

The abstract base class of every tensordict.

TensorDict([source, batch_size, device, ...])

A dictionary of tensors that share a batch size.

LazyStackedTensorDict(*tensordicts[, ...])

A stack of tensordicts that keeps each input as a separate tensordict.

PersistentTensorDict(*[, batch_size, ...])

A tensordict whose entries live in an HDF5 file or a Zarr store.

TensorDictParams([parameters, no_convert, lock])

A TensorDict whose entries are registered as the parameters and buffers of an Module.

MemoryMappedTensor(source, *[, dtype, ...])

A CPU tensor whose storage is a file on disk, or anonymous shared memory when no filename is given.

TensorCollection(*args, **kwargs)

The abstract base class of tensordicts and tensorclasses.

Methods by task#

The tables below list the methods of TensorDictBase, with one page for each method. Every tensordict class and every tensorclass has these methods. A class page lists only the methods that the class adds, and the overrides that have their own documentation. When the tensordict module has a function for the same task, the function is in the same group.

Construction and conversion#

Create a tensordict from Python, numpy, or pandas data, and convert a tensordict to other types. Most from_* class methods have a function of the same name in the tensordict module. To read a tensordict from a file, see Saving, loading, and file formats. For the arguments of the constructor, see TensorDict.

Methods

TensorDictBase.from_any(obj, *[, ...])

Converts a dict, tuple, dataclass, array or file to a tensordict, recursively.

TensorDictBase.from_dict(input_dict, *[, ...])

Returns a tensordict built from a dictionary, which can be nested.

TensorDictBase.from_dict_instance(input_dict, *)

Builds a tensordict from a dictionary, with the types of the entries of this tensordict.

TensorDictBase.from_namedtuple(named_tuple, *)

Converts a named tuple to a tensordict whose keys are its field names.

TensorDictBase.from_pandas(dataframe, *[, ...])

Converts a pandas DataFrame to a tensordict, with one entry per column.

TensorDictBase.from_struct_array(struct_array, *)

Converts a NumPy structured array to a tensordict, with one entry per field.

TensorDictBase.from_tuple(obj, *[, ...])

Converts a tuple to a tensordict with the keys "0", "1", ...

TensorDictBase.from_pytree(pytree, *[, ...])

Converts a pytree to a tensordict that to_pytree() converts back.

TensorDictBase.from_dataclass(dataclass, *)

Converts a dataclass instance to a tensordict, with one entry per field.

TensorDictBase.from_list(input, *[, ...])

Builds a tensordict by stacking a list of dicts or tensor collections.

TensorDictBase.from_schema(schema, *[, ...])

Allocates a zero-filled tensordict from a schema of shapes and dtypes.

TensorDictBase.fromkeys(keys[, value])

Creates a tensordict with the same value for every key, like dict.fromkeys().

TensorDictBase.empty([recurse, batch_size, ...])

Returns a new tensordict of the same type, with no tensor leaves.

TensorDictBase.new_empty(*size[, dtype, ...])

Returns a tensordict of batch size size with uninitialized leaves.

TensorDictBase.new_full(size, fill_value, *)

Returns a tensordict of batch size size with every leaf filled with fill_value.

TensorDictBase.new_ones(*size[, dtype, ...])

Returns a tensordict of batch size size with every leaf filled with 1.

TensorDictBase.new_tensor(data, *[, dtype, ...])

Returns a tensordict whose leaves are copies of data, each with the dtype of its leaf.

TensorDictBase.new_zeros(*size[, dtype, ...])

Returns a tensordict of batch size size with every leaf filled with 0.

TensorDictBase.copy()

Returns a shallow copy of the tensordict: a new structure that holds the same leaves.

TensorDictBase.clone([recurse])

Returns a copy of the tensordict, of the same type.

TensorDictBase.to_dict(*[, retain_none, ...])

Returns a nested dictionary with the entries of the tensordict.

TensorDictBase.to_namedtuple([dest_cls])

Converts the tensordict to a named tuple, recursively.

TensorDictBase.to_pandas(*[, separator])

Converts the tensordict to a pandas DataFrame, with one column per leaf.

TensorDictBase.to_pytree()

Rebuilds the pytree that from_pytree() converted to this tensordict.

TensorDictBase.to_struct_array()

Converts the tensordict to a NumPy structured array, with one field per entry.

TensorDictBase.to_tensordict(*[, retain_none])

Returns a TensorDict copy of this tensordict.

TensorDictBase.tolist(*[, convert_nodes, ...])

Returns the elements of the tensordict as nested lists, one level per batch dimension.

TensorDictBase.numpy()

Returns a nested dict of NumPy arrays with the entries of the tensordict.

TensorDictBase.as_tensor()

Returns a tensordict whose leaves are converted with their as_tensor() method, if they have one.

Functions

from_any(obj, *[, auto_batch_size, ...])

Converts a dict, tuple, dataclass, array or file to a tensordict, recursively.

from_dict(d, *[, auto_batch_size, ...])

Converts a dictionary to a tensordict, recursively.

from_namedtuple(named_tuple, *[, ...])

Converts a named tuple to a tensordict whose keys are its field names.

from_pandas(dataframe, *[, auto_batch_size, ...])

Converts a pandas DataFrame to a tensordict, with one entry per column.

from_struct_array(struct_array, *[, ...])

Converts a NumPy structured array to a tensordict, with one entry per field.

from_tuple(obj, *[, auto_batch_size, ...])

Converts a tuple to a tensordict with the keys "0", "1", ...

from_pytree(pytree, *[, batch_size, ...])

Converts a pytree (nested lists, tuples and dicts of tensors) to a tensordict.

fromkeys(keys[, value])

Creates a tensordict with the same value for every key, like dict.fromkeys().

make_tensordict([input_dict, batch_size, ...])

Returns a tensordict built from a dict or from keyword arguments.

Keys, values, and entries#

Read, write, select, and rename the entries of a tensordict. A key is a string, or a tuple of strings that points to an entry of a nested tensordict. NestedKey is the type of these keys. For the rules, see Keys, nested keys, and locking. For values that are not tensors, see Non-tensor data and unbatched entries.

Methods

TensorDictBase.keys([include_nested, ...])

Returns a view of the keys of the tensordict.

TensorDictBase.values([include_nested, ...])

Returns a generator of the values of the tensordict.

TensorDictBase.items([include_nested, ...])

Returns a generator of the (key, value) pairs of the tensordict.

TensorDictBase.sorted_keys

The top-level keys of the tensordict, as a list sorted in alphabetical order.

TensorDictBase.get()

Returns the value stored at key, or default if the key is missing.

TensorDictBase.get_at()

Returns the entry at key, indexed with index.

TensorDictBase.set(key, item[, inplace, ...])

Sets an entry, and returns the tensordict.

TensorDictBase.set_(key, item, *[, non_blocking])

Copies a value into an existing entry, which keeps its storage, and returns self.

TensorDictBase.set_at_(key, value, index, *)

Writes value into the existing entry key at the index index, in place.

TensorDictBase.setdefault(key, default[, ...])

Returns the entry at key, after writing default there if the key is missing.

TensorDictBase.update([input_dict_or_td, ...])

Writes the entries of a dictionary or another tensordict into the tensordict, and returns self.

TensorDictBase.update_([input_dict_or_td, ...])

Copies the entries of a dictionary or tensordict into the existing entries, and returns self.

TensorDictBase.update_at_(input_dict_or_td, idx)

Copies the entries of a dictionary or tensordict into the existing entries at idx.

TensorDictBase.copy_(tensordict[, non_blocking])

Copies the entries of tensordict into the existing entries, and returns self.

TensorDictBase.copy_at_(tensordict, idx[, ...])

Copies the tensors of tensordict into the existing entries at idx, and returns self.

TensorDictBase.replace(*args, **kwargs)

Returns a shallow copy of the tensordict with some entries replaced.

TensorDictBase.pop(key[, default])

Removes an entry from the tensordict and returns its value.

TensorDictBase.popitem()

Removes the last top-level entry and returns it as a (key, value) pair.

TensorDictBase.del_(key)

Deletes an entry of the tensordict in place and returns the tensordict.

TensorDictBase.clear()

Removes every entry of the tensordict and returns self.

TensorDictBase.select(*keys[, inplace, ...])

Returns a tensordict that holds only the entries of keys.

TensorDictBase.exclude(*keys[, inplace])

Returns a tensordict without the entries of keys.

TensorDictBase.split_keys(*key_sets[, ...])

Splits the tensordict into one tensordict per set of keys, plus one for the remaining entries.

TensorDictBase.separates(*keys[, default, ...])

Removes the entries of keys from the tensordict in place, and returns them in a new tensordict.

TensorDictBase.rename_key_(old_key, new_key)

Renames an entry of the tensordict in place and returns the tensordict.

TensorDictBase.rename_keys(mapping, *[, strict])

Returns a tensordict with several keys renamed at once.

TensorDictBase.flatten_keys([separator, ...])

Returns a tensordict with the nested entries moved to the top level, under joined keys.

TensorDictBase.unflatten_keys([separator, ...])

Returns a tensordict with the keys that hold the separator split into nested keys.

TensorDictBase.create_nested(key)

Adds an empty nested tensordict at key, and returns self.

TensorDictBase.depth

the maximum number of levels of nested tensordicts.

TensorDictBase.entry_class(key)

Returns the class of an entry, possibly without reading the entry.

TensorDictBase.get_item_shape(key)

Returns the shape of the entry at key, without reading the entry when possible.

TensorDictBase.is_empty()

Returns True if the tensordict has no leaf.

TensorDictBase.fill_(key, value)

Fills the entry at key with value in place and returns self.

TensorDictBase.set_non_tensor(key, value)

Stores value as non-tensor data at key, and returns self.

TensorDictBase.get_non_tensor(key[, default])

Returns the content of the non-tensor entry at key.

TensorDictBase.is_non_tensor(key)

Returns True if the entry at key is non-tensor data.

TensorDictBase.non_tensor_items([include_nested])

Returns a tuple of the (key, value) pairs of the non-tensor data of the tensordict.

TensorDictBase.filter_non_tensor_data()

Returns a tensordict without the non-tensor entries, nested ones included.

TensorDictBase.filter_empty_()

Removes the nested tensordicts that have no leaf, in place, and returns self.

TensorDictBase.cat_tensors(*keys, out_key[, ...])

Concatenates entries of the tensordict into a new entry, and removes them by default.

TensorDictBase.stack_tensors(*keys, out_key)

Stacks entries of the tensordict into a new entry, and removes them by default.

TensorDictBase.cat_from_tensordict([dim, ...])

Concatenates all the leaves of the tensordict into one tensor, with torch.cat().

TensorDictBase.pack([dim, layout])

Packs all the leaves of a tensordict into one tensor of features.

TensorDictBase.stack_from_tensordict([dim, ...])

Stacks all the leaves of the tensordict into one tensor, with torch.stack().

Classes and functions

NestedKey()

The type of the keys of a tensordict: a string, or a tuple of strings for a nested entry.

PackLayout(keys, shapes[, dim, nested, ...])

The layout of a tensordict packed by pack().

unravel_key(key)

Unravels a nested key into a str or a flat tuple of str.

unravel_key_list(keys)

Unravels every key of a list, as unravel_key() does.

unravel_key_to_tuple(key)

Unravels a nested key into a flat tuple of str.

merge_tensordicts(*tensordicts[, callback_exist])

Merges the entries of several tensordicts into a new tensordict.

Indexing, masking, and splitting#

Index every entry along the batch dimensions at once, and split a tensordict into several tensordicts. td[0] and td[mask] index the batch dimensions. td["key"] returns an entry: see Keys, values, and entries. For the rules, see Batch size, shapes, and indexing.

TensorDictBase.__getitem__()

Returns the entry at a key, or the tensordict indexed along its batch dimensions.

TensorDictBase.__iter__()

Iterates over the first batch dimension of the tensordict.

TensorDictBase.gather(dim, index[, out, inplace])

Gathers values along a batch dimension, as torch.gather() does.

TensorDictBase.masked_fill(mask, value)

Returns a copy of the tensordict with value written into every leaf where mask is True.

TensorDictBase.masked_fill_(mask, value)

Writes value into every leaf where mask is True, in place.

TensorDictBase.masked_select(mask, *[, inplace])

Returns a tensordict with the elements of the batch where mask is True.

TensorDictBase.where(condition, other, *[, ...])

Returns a tensordict with the leaves where condition is True and other elsewhere.

TensorDictBase.split(split_size[, dim])

Splits the tensordict along a batch dimension, as torch.split() does.

TensorDictBase.chunk(chunks[, dim])

Splits the tensordict into chunks pieces along a batch dimension, as torch.chunk() does.

TensorDictBase.tensor_split(indices_or_sections)

Splits the tensordict along a batch dimension, as torch.tensor_split() does.

TensorDictBase.unbind(dim)

Returns a tuple of the tensordicts along a batch dimension, as torch.Tensor.unbind() does.

TensorDictBase.narrow(dim, start, length)

Returns a tensordict narrowed along a batch dimension, as torch.Tensor.narrow() does.

group_by(tensordict, key)

Splits a tensordict into groups of rows that share the value of an entry.

Shape, batch dimensions, and stacking#

Read and change the batch size and the dimension names, reshape and expand a tensordict, and stack or concatenate several tensordicts. These methods change the batch dimensions. The dimensions of each entry after the batch dimensions do not change. See Batch size, shapes, and indexing and Stacking and variable-size data.

Methods

TensorDictBase.batch_size

The batch size of the tensordict, as a torch.Size.

TensorDictBase.batch_dims

The number of batch dimensions, that is len(self.batch_size).

TensorDictBase.shape

the same as batch_size.

TensorDictBase.ndim

The number of batch dimensions, the same as batch_dims.

TensorDictBase.ndimension()

Returns the number of batch dimensions, the same as batch_dims.

TensorDictBase.dim()

Returns the number of batch dimensions, the same as batch_dims.

TensorDictBase.size([dim])

Returns the batch size, or the size of one batch dimension.

TensorDictBase.numel()

Returns the number of elements in the batch, which is the product of batch_size.

TensorDictBase.__len__()

Returns the size of the first batch dimension, or 0 if the tensordict has no batch dimensions.

TensorDictBase.names

The dimension names of the tensordict, one per batch dimension.

TensorDictBase.refine_names(*names)

Names the unnamed batch dimensions, and checks the named ones, in place.

TensorDictBase.rename(*names, **rename_map)

Returns a shallow copy of the tensordict with new names for its batch dimensions.

TensorDictBase.rename_(*names, **rename_map)

Renames the batch dimensions of the tensordict in place and returns self.

TensorDictBase.auto_batch_size_([...])

Sets the batch size to the largest leading shape that all the entries share.

TensorDictBase.reshape(*args, **kwargs)

Returns a tensordict whose batch dimensions are reshaped to shape.

TensorDictBase.view(*shape[, size, batch_size])

Returns a tensordict with a new batch size, whose leaves are views of the original leaves.

TensorDictBase.flatten([start_dim, end_dim, ...])

Returns a tensordict whose batch dimensions start_dim to end_dim are flattened into one.

TensorDictBase.unflatten(dim, ...[, inplace])

Returns a tensordict whose batch dimension dim is split into several.

TensorDictBase.permute(*args, **kwargs)

Returns a tensordict with its batch dimensions permuted, as torch.Tensor.permute() does.

TensorDictBase.transpose(dim0, dim1)

Returns a tensordict with the batch dimensions dim0 and dim1 swapped.

TensorDictBase.swapaxes(axis0, axis1)

Returns a tensordict with two batch dimensions swapped, as transpose() does.

TensorDictBase.swapdims(axis0, axis1)

Returns a tensordict with two batch dimensions swapped, as transpose() does.

TensorDictBase.moveaxis(source, destination)

Returns a tensordict with batch dimensions moved to new positions, as torch.movedim() does.

TensorDictBase.movedim(source, destination)

Returns a tensordict with batch dimensions moved to new positions, as torch.movedim() does.

TensorDictBase.squeeze(*args, **kwargs)

Returns a tensordict without the batch dimensions of size 1.

TensorDictBase.unsqueeze(*args, **kwargs)

Returns a tensordict with a new batch dimension of size 1 at position dim.

TensorDictBase.expand(*args, **kwargs)

Returns a tensordict whose batch dimensions are expanded to shape.

TensorDictBase.expand_as(other)

Returns the tensordict expanded to the shape of other.

TensorDictBase.broadcast_to(shape)

Returns the tensordict broadcast to the batch size shape, as torch.broadcast_to() does.

TensorDictBase.repeat(*repeats[, inplace])

Repeats the batch along each batch dimension, as torch.Tensor.repeat() does.

TensorDictBase.repeat_interleave(repeats[, ...])

Repeats each element of the batch along dim, as torch.Tensor.repeat_interleave() does.

TensorDictBase.tile(dims)

Returns a tensordict whose batch is repeated, as torch.tile() does.

TensorDictBase.flip(dims)

Returns a tensordict with the elements reversed along batch dimensions, as torch.flip() does.

TensorDictBase.fliplr()

Returns a tensordict with the elements reversed along batch dimension 1.

TensorDictBase.flipud()

Returns a tensordict with the elements reversed along batch dimension 0.

TensorDictBase.roll(shifts[, dims, inplace])

Returns a tensordict with the elements rolled along batch dimensions, as torch.roll() does.

TensorDictBase.rot90([k, dims])

Returns a tensordict rotated by 90 degrees in the plane of two batch dimensions.

TensorDictBase.pad(pad_size[, value, ...])

Returns the tensordict padded along its batch dimensions with a constant value.

TensorDictBase.atleast_1d()

Returns the tensordict with at least 1 batch dimension.

TensorDictBase.atleast_2d()

Returns the tensordict with at least 2 batch dimensions.

TensorDictBase.atleast_3d()

Returns the tensordict with at least 3 batch dimensions.

TensorDictBase.contiguous(*[, canonical, ...])

Returns a new tensordict with contiguous leaves.

TensorDictBase.is_contiguous()

True if all the leaves of the tensordict, nested ones included, are contiguous.

TensorDictBase.stack(input[, dim, out])

Stacks tensordicts into one dense tensordict along a new dimension dim.

TensorDictBase.cat(input[, dim, out])

Concatenates tensordicts along an existing batch dimension dim.

TensorDictBase.lazy_stack(input[, dim, out])

Stacks tensordicts into a lazy stack.

TensorDictBase.maybe_dense_stack(input[, ...])

Stacks tensordicts densely if possible, or into a lazy stack otherwise.

TensorDictBase.to_lazystack([dim])

Returns a lazy stack of the slices of the tensordict along dim.

TensorDictBase.densify([layout])

Returns the tensordict with its lazy stacks replaced by dense tensordicts.

TensorDictBase.to_padded_tensor([padding, ...])

Returns a tensordict whose nested-tensor leaves are converted to padded tensors.

Functions

stack(input[, dim, out])

Stacks tensordicts into one dense tensordict along a new dimension dim.

cat(input[, dim, out])

Concatenates tensordicts along an existing batch dimension dim.

lazy_stack(input[, dim, out])

Stacks tensordicts into a lazy stack (LazyStackedTensorDict).

maybe_dense_stack(input[, dim, out])

Stacks tensordicts densely if possible, or into a lazy stack otherwise.

dense_stack_tds(td_list[, dim])

Stacks a list of tensordicts, or the tensordicts of a lazy stack, densely if possible.

pad(tensordict, pad_size[, value, inplace, safe])

Pads all tensors in a tensordict along the batch dimensions with a constant value.

pad_sequence(list_of_tensordicts[, pad_dim, ...])

Pads tensordicts to a common size along one dimension and stacks them densely.

unpad_sequence(padded[, mask, pad_dim])

Splits a padded batch back into its variable-length samples.

collate(batch, *[, pad_keys, nested_keys, ...])

Collates a list of samples into a batch, for DataLoader.

Device, dtype, and memory#

Move a tensordict to a device, cast its entries to another dtype, and control the memory that holds them. See Devices, dtypes, and memory.

Device and memory

TensorDictBase.to(*args, **kwargs)

Returns a tensordict cast to another device, dtype or memory format, or with a new batch size.

TensorDictBase.cpu(**kwargs)

Returns the tensordict on the CPU, as to("cpu", **kwargs) does.

TensorDictBase.cuda([device])

Returns the tensordict on a CUDA device, as to() does.

TensorDictBase.device

The device of the tensordict, or None if it has none.

TensorDictBase.auto_device_()

Sets the device of the tensordict to the device of its leaves, if they all share one.

TensorDictBase.clear_device_()

Sets the device of the tensordict and its sub-tensordicts to None, and returns it.

TensorDictBase.is_cpu

Whether the tensordict has a CPU device (False if it has no device).

TensorDictBase.is_cuda

Whether the tensordict has a CUDA device (False if it has no device).

TensorDictBase.is_meta

Whether the tensordict has a meta device (False if it has no device).

TensorDictBase.pin_memory([num_threads, inplace])

Returns a tensordict whose tensor leaves are in pinned (page-locked) memory.

TensorDictBase.share_memory_()

Moves the leaves to shared memory, locks the tensordict, and returns self.

TensorDictBase.is_shared()

Whether the tensordict is in shared memory.

TensorDictBase.record_stream(stream)

Marks the tensor leaves of the tensordict as used by stream.

TensorDictBase.consolidate([filename, ...])

Copies all the leaves into one contiguous storage, and returns a tensordict of views of it.

TensorDictBase.is_consolidated()

Whether the leaves of the tensordict are views into one storage made by consolidate().

TensorDictBase.from_consolidated(filename)

Reconstructs a tensordict from a file written by consolidate(filename=...).

TensorDictBase.bytes(*[, count_duplicates])

Returns the number of bytes of the tensor leaves.

TensorDictBase.data_ptr(*[, storage])

Returns the data pointers of the leaves, as a tensordict of integers.

TensorDictBase.param_count(*[, count_duplicates])

Returns the total number of elements of the tensor leaves.

TensorDictBase.attrs(*[, fields, num_threads])

Returns a tensordict that describes each tensor leaf with a TensorAttrs.

TensorDictBase.clear_refs_for_compile_()

Clears the record of the last operation of the tensordict and its nested tensordicts.

Dtype

TensorDictBase.dtype

The dtype of the leaves, or None if they have different dtypes or there is no leaf.

TensorDictBase.type(dst_type, *[, cast_filter])

Returns a tensordict whose tensor leaves are cast to dst_type.

TensorDictBase.is_floating_point()

True if every tensor leaf of the tensordict, nested ones included, has a floating-point dtype.

TensorDictBase.bool(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.bool.

TensorDictBase.half(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.float16 (torch.half).

TensorDictBase.float(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.float32 (torch.float).

TensorDictBase.double(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.float64 (torch.double).

TensorDictBase.int(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.int32 (torch.int).

TensorDictBase.bfloat16(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.bfloat16.

TensorDictBase.float16(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.float16.

TensorDictBase.float32(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.float32.

TensorDictBase.float64(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.float64.

TensorDictBase.int8(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.int8.

TensorDictBase.int16(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.int16.

TensorDictBase.int32(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.int32.

TensorDictBase.int64(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.int64.

TensorDictBase.uint8(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.uint8.

TensorDictBase.uint16(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.uint16.

TensorDictBase.uint32(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.uint32.

TensorDictBase.uint64(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.uint64.

TensorDictBase.complex32(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.complex32.

TensorDictBase.complex64(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.complex64.

TensorDictBase.complex128(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.complex128.

to and the dtype shorthands take a cast_filter predicate fn(key, value) -> bool that selects the leaves to cast. The predicates below test the dtype of their last argument, so they serve as a cast_filter and as a test in apply().

Functions

from_consolidated(filename)

Reconstructs a tensordict from a file written by consolidate(filename=...).

is_inexact(*args)

Whether the last argument is a floating-point or complex tensor.

is_floating(*args)

Whether the last argument is a floating-point tensor.

is_integer(*args)

Whether the last argument is an integer tensor (signed or unsigned, not bool).

is_bool(*args)

Whether the last argument is a boolean tensor.

Pointwise math#

Apply arithmetic and elementwise functions to every entry. The Python operators (+, -, *, /, **, ==, &, …) call these methods. A method whose name ends with an underscore, such as add_, writes into the existing tensors: see In-place operations. For broadcasting and for tensordicts with different keys, see Arithmetic, apply, reductions, and gradients.

Arithmetic

TensorDictBase.add(other, *[, alpha, default])

Returns a new tensordict with other, scaled by alpha, added to every leaf.

TensorDictBase.add_(other, *[, alpha])

Adds other, scaled by alpha, to every leaf in place and returns self.

TensorDictBase.sub(other, *[, alpha, default])

Returns a new tensordict with other, scaled by alpha, subtracted from every leaf.

TensorDictBase.sub_(other[, alpha])

Subtracts other, scaled by alpha, from every leaf in place and returns self.

TensorDictBase.rsub(other, *[, alpha, default])

Returns a new tensordict with every leaf, scaled by alpha, subtracted from other.

TensorDictBase.mul(other, *[, default])

Returns a new tensordict with every leaf multiplied by other.

TensorDictBase.mul_(other)

Multiplies every leaf by other in place and returns self.

TensorDictBase.div(other, *[, default])

Returns a new tensordict with every leaf divided by other.

TensorDictBase.div_(other)

Divides every leaf by other in place and returns self.

TensorDictBase.pow(other, *[, default])

Returns a new tensordict with every leaf raised to the power other.

TensorDictBase.pow_(other)

Raises every leaf to the power other in place and returns self.

TensorDictBase.mod(other)

Returns a new tensordict with the remainder of every leaf divided by other.

TensorDictBase.lerp(end, weight)

Returns a new tensordict that interpolates linearly from every leaf (the start) to end.

TensorDictBase.lerp_(end, weight)

Interpolates linearly from every leaf to end in place and returns self.

TensorDictBase.addcdiv(other1, other2[, value])

Returns a new tensordict with value * other1 / other2 added to every leaf.

TensorDictBase.addcdiv_(other1, other2, *[, ...])

Adds value * other1 / other2 to every leaf in place and returns self.

TensorDictBase.addcmul(other1, other2, *[, ...])

Returns a new tensordict with value * other1 * other2 added to every leaf.

TensorDictBase.addcmul_(other1, other2, *[, ...])

Adds value * other1 * other2 to every leaf in place and returns self.

TensorDictBase.clamp([min, max, out])

Returns a new tensordict with every leaf clamped into the range [min, max].

TensorDictBase.clamp_min(other[, default])

Returns a new tensordict with every leaf clamped to at least other.

TensorDictBase.clamp_min_(other)

Clamps every leaf to at least other in place and returns self.

TensorDictBase.clamp_max(other, *[, default])

Returns a new tensordict with every leaf clamped to at most other.

TensorDictBase.clamp_max_(other)

Clamps every leaf to at most other in place and returns self.

TensorDictBase.maximum(other, *[, default])

Returns a new tensordict with the element-wise maximum of every leaf and other.

TensorDictBase.maximum_(other)

Replaces every leaf with its element-wise maximum with other in place and returns self.

TensorDictBase.minimum(other, *[, default])

Returns a new tensordict with the element-wise minimum of every leaf and other.

TensorDictBase.minimum_(other)

Replaces every leaf with its element-wise minimum with other in place and returns self.

TensorDictBase.zero_()

Fills every leaf with zeros in place and returns self.

Elementwise functions

TensorDictBase.abs()

Returns a new tensordict with torch.abs() applied to every leaf.

TensorDictBase.abs_()

Applies torch.abs() to every leaf in place and returns self.

TensorDictBase.neg()

Returns a new tensordict with torch.neg() applied to every leaf.

TensorDictBase.neg_()

Applies torch.neg() to every leaf in place and returns self.

TensorDictBase.reciprocal()

Returns a new tensordict with torch.reciprocal() applied to every leaf.

TensorDictBase.reciprocal_()

Applies torch.reciprocal() to every leaf in place and returns self.

TensorDictBase.sqrt()

Returns a new tensordict with torch.sqrt() applied to every leaf.

TensorDictBase.sqrt_()

Applies torch.sqrt() to every leaf in place and returns self.

TensorDictBase.exp()

Returns a new tensordict with torch.exp() applied to every leaf.

TensorDictBase.exp_()

Applies torch.exp() to every leaf in place and returns self.

TensorDictBase.expm1()

Returns a new tensordict with torch.expm1() applied to every leaf.

TensorDictBase.expm1_()

Applies torch.expm1() to every leaf in place and returns self.

TensorDictBase.log()

Returns a new tensordict with torch.log() applied to every leaf.

TensorDictBase.log_()

Applies torch.log() to every leaf in place and returns self.

TensorDictBase.log10()

Returns a new tensordict with torch.log10() applied to every leaf.

TensorDictBase.log10_()

Applies torch.log10() to every leaf in place and returns self.

TensorDictBase.log1p()

Returns a new tensordict with torch.log1p() applied to every leaf.

TensorDictBase.log1p_()

Applies torch.log1p() to every leaf in place and returns self.

TensorDictBase.log2()

Returns a new tensordict with torch.log2() applied to every leaf.

TensorDictBase.log2_()

Applies torch.log2() to every leaf in place and returns self.

TensorDictBase.sin()

Returns a new tensordict with torch.sin() applied to every leaf.

TensorDictBase.sin_()

Applies torch.sin() to every leaf in place and returns self.

TensorDictBase.cos()

Returns a new tensordict with torch.cos() applied to every leaf.

TensorDictBase.cos_()

Applies torch.cos() to every leaf in place and returns self.

TensorDictBase.tan()

Returns a new tensordict with torch.tan() applied to every leaf.

TensorDictBase.tan_()

Applies torch.tan() to every leaf in place and returns self.

TensorDictBase.asin()

Returns a new tensordict with torch.asin() applied to every leaf.

TensorDictBase.asin_()

Applies torch.asin() to every leaf in place and returns self.

TensorDictBase.acos()

Returns a new tensordict with torch.acos() applied to every leaf.

TensorDictBase.acos_()

Applies torch.acos() to every leaf in place and returns self.

TensorDictBase.atan()

Returns a new tensordict with torch.atan() applied to every leaf.

TensorDictBase.atan_()

Applies torch.atan() to every leaf in place and returns self.

TensorDictBase.sinh()

Returns a new tensordict with torch.sinh() applied to every leaf.

TensorDictBase.sinh_()

Applies torch.sinh() to every leaf in place and returns self.

TensorDictBase.cosh()

Returns a new tensordict with torch.cosh() applied to every leaf.

TensorDictBase.cosh_()

Applies torch.cosh() to every leaf in place and returns self.

TensorDictBase.tanh()

Returns a new tensordict with torch.tanh() applied to every leaf.

TensorDictBase.tanh_()

Applies torch.tanh() to every leaf in place and returns self.

TensorDictBase.sigmoid()

Returns a new tensordict with torch.sigmoid() applied to every leaf.

TensorDictBase.sigmoid_()

Applies torch.sigmoid() to every leaf in place and returns self.

TensorDictBase.erf()

Returns a new tensordict with torch.erf() applied to every leaf.

TensorDictBase.erf_()

Applies torch.erf() to every leaf in place and returns self.

TensorDictBase.erfc()

Returns a new tensordict with torch.erfc() applied to every leaf.

TensorDictBase.erfc_()

Applies torch.erfc() to every leaf in place and returns self.

TensorDictBase.lgamma()

Returns a new tensordict with torch.lgamma() applied to every leaf.

TensorDictBase.lgamma_()

Applies torch.lgamma() to every leaf in place and returns self.

TensorDictBase.ceil()

Returns a new tensordict with torch.ceil() applied to every leaf.

TensorDictBase.ceil_()

Applies torch.ceil() to every leaf in place and returns self.

TensorDictBase.floor()

Returns a new tensordict with torch.floor() applied to every leaf.

TensorDictBase.floor_()

Applies torch.floor() to every leaf in place and returns self.

TensorDictBase.round()

Returns a new tensordict with torch.round() applied to every leaf.

TensorDictBase.round_()

Applies torch.round() to every leaf in place and returns self.

TensorDictBase.trunc()

Returns a new tensordict with torch.trunc() applied to every leaf.

TensorDictBase.trunc_()

Applies torch.trunc() to every leaf in place and returns self.

TensorDictBase.frac()

Returns a new tensordict with torch.frac() applied to every leaf.

TensorDictBase.frac_()

Applies torch.frac() to every leaf in place and returns self.

TensorDictBase.sign()

Returns a new tensordict with torch.sign() applied to every leaf.

TensorDictBase.sign_()

Applies torch.sign() to every leaf in place and returns self.

TensorDictBase.softmax(dim[, dtype])

Returns a new tensordict with torch.softmax() applied to every leaf along a batch dimension.

Comparisons and logical operations

TensorDictBase.__eq__(other)

Compares the tensordict with other leaf by leaf with ==.

TensorDictBase.__ne__(other)

Compares the tensordict with other leaf by leaf with !=.

TensorDictBase.__lt__(other)

Compares the tensordict with other leaf by leaf with <.

TensorDictBase.__le__(other)

Compares the tensordict with other leaf by leaf with <=.

TensorDictBase.__gt__(other)

Compares the tensordict with other leaf by leaf with >.

TensorDictBase.__ge__(other)

Compares the tensordict with other leaf by leaf with >=.

TensorDictBase.__and__(other)

Computes self & other leaf by leaf and returns a new tensordict.

TensorDictBase.__or__(other)

Computes self | other leaf by leaf and returns a new tensordict.

TensorDictBase.__xor__(other)

Computes self ^ other leaf by leaf and returns a new tensordict.

TensorDictBase.__invert__()

Returns ~td, a new tensordict with ~ applied to every leaf.

TensorDictBase.bitwise_and(other, *[, default])

Returns a new tensordict with the bitwise AND of every leaf and other.

TensorDictBase.logical_and(other, *[, default])

Returns a new tensordict with the logical AND of every leaf and other.

TensorDictBase.isfinite()

Returns a new tensordict with torch.isfinite() applied to every leaf.

TensorDictBase.isnan()

Returns a new tensordict with torch.isnan() applied to every leaf.

TensorDictBase.isneginf()

Returns a new tensordict with torch.isneginf() applied to every leaf.

TensorDictBase.isposinf()

Returns a new tensordict with torch.isposinf() applied to every leaf.

TensorDictBase.isreal()

Returns a new tensordict with torch.isreal() applied to every leaf.

Reductions#

Reduce each entry over all its elements, or along batch dimensions with dim. With reduce=True, most reductions return one tensor for the whole tensordict. See Arithmetic, apply, reductions, and gradients.

TensorDictBase.all([dim])

Returns whether every element of every leaf is True (nonzero).

TensorDictBase.any([dim])

Returns whether any element of any leaf is True (nonzero).

TensorDictBase.amax([dim, keepdim, reduce])

Returns the maximum of every leaf, over all its elements or along a batch dimension.

TensorDictBase.amin([dim, keepdim, reduce])

Returns the minimum of every leaf, over all its elements or along a batch dimension.

TensorDictBase.max([dim, keepdim, reduce, ...])

Returns the maximum of every leaf, over all its elements or along a batch dimension.

TensorDictBase.min([dim, keepdim, reduce, ...])

Returns the minimum of every leaf, over all its elements or along a batch dimension.

TensorDictBase.cummax(dim, *[, reduce, ...])

Returns the cumulative maximum of every leaf along a batch dimension.

TensorDictBase.cummin(dim, *[, reduce, ...])

Returns the cumulative minimum of every leaf along a batch dimension.

TensorDictBase.mean([dim, keepdim, dtype, ...])

Returns the mean of every leaf, over all its elements or along batch dimensions.

TensorDictBase.nanmean([dim, keepdim, ...])

Returns the mean of the non-NaN elements of every leaf.

TensorDictBase.sum([dim, keepdim, dtype, ...])

Returns the sum of every leaf, over all its elements or along batch dimensions.

TensorDictBase.nansum([dim, keepdim, dtype, ...])

Returns the sum of the non-NaN elements of every leaf.

TensorDictBase.prod([dim, keepdim, dtype, ...])

Returns the product of every leaf, over all its elements or along a batch dimension.

TensorDictBase.std([dim, keepdim, ...])

Returns the standard deviation of every leaf, over all its elements or along batch dimensions.

TensorDictBase.var([dim, keepdim, ...])

Returns the variance of every leaf, over all its elements or along batch dimensions.

TensorDictBase.quantile(q[, dim, keepdim, ...])

Returns the q-th quantile of every leaf, over all its elements or along a batch dimension.

TensorDictBase.logsumexp([dim, keepdim, out])

Returns the log of the summed exponentials of every leaf along batch dimensions.

TensorDictBase.norm(*[, out, dtype, ...])

Returns a tensordict with the norm of each leaf.

Apply, modules, and gradients#

Apply a function to every entry, and map a function over the batch. Put the parameters of a module in a tensordict and back, and compute gradients. See Arithmetic, apply, reductions, and gradients, Modules: TensorDictModule and tensordict.nn, and torch.compile, torch.func, torch.export, and CUDA graphs.

Methods

TensorDictBase.apply(fn, *others[, ...])

Applies a callable to every leaf and returns a new tensordict with the results.

TensorDictBase.apply_(fn, *others, **kwargs)

Applies a callable to every leaf and writes the results into the existing leaves.

TensorDictBase.named_apply(fn, *others[, ...])

Applies a callable to every leaf and its key, and returns a new tensordict with the results.

TensorDictBase.map(fn[, dim, num_workers, ...])

Applies a function to chunks of the tensordict in worker processes, and gathers the results.

TensorDictBase.map_iter(fn[, dim, ...])

Applies a function to chunks of the tensordict in worker processes, and yields the results.

TensorDictBase.from_module(module[, ...])

Returns a tensordict of the parameters and buffers of a module.

TensorDictBase.from_modules(*modules[, ...])

Stacks the parameters and buffers of several modules in one tensordict.

TensorDictBase.to_module(module, *[, ...])

Writes the content of the tensordict into the parameters and buffers of a module, recursively.

TensorDictBase.backward([gradient, ...])

Computes the gradients of the leaves of the tensordict that require gradients.

TensorDictBase.requires_grad

True if any leaf of the tensordict, nested ones included, requires gradients.

TensorDictBase.requires_grad_([requires_grad])

Sets requires_grad on every tensor leaf in place, and returns the tensordict.

TensorDictBase.detach()

Returns a new tensordict with every tensor leaf detached from the autograd graph.

TensorDictBase.detach_()

Detaches every tensor leaf from the autograd graph in place, and returns the tensordict.

TensorDictBase.grad

A tensordict of the .grad of every leaf, or None if no leaf has one.

TensorDictBase.data

the same storage, without autograd.

TensorDictBase.zero_grad([set_to_none])

Resets the .grad of every leaf, nested ones included, and returns self.

Functions

from_module(module[, as_module, lock, ...])

Returns a locked tensordict that holds the parameters and buffers of a module.

from_modules(*modules[, as_module, lock, ...])

Stacks the parameters and buffers of several modules in one tensordict.

default_is_leaf(cls)

Returns True if a type is a leaf: anything but a tensordict or a tensorclass.

is_leaf_nontensor(cls)

Returns True if a type is a tensor or non-tensor data.

Saving, loading, and file formats#

Save a tensordict to disk and load it again, and write its entries to memory-mapped files. Other methods read and write key-value stores, and HDF5, zarr, CSV, JSON, Parquet, and MDS files, and convert to and from Arrow tables. memmap(return_early=True) returns a TensorDictFuture. See Save and load tensordicts and Large datasets and storage backends.

Methods

TensorDictBase.save([prefix, copy_existing, ...])

Saves the tensordict to disk, and returns a memory-mapped copy of it.

TensorDictBase.load(prefix, *args, **kwargs)

Loads a tensordict that save() or memmap() wrote to disk.

TensorDictBase.dumps([prefix, ...])

Saves the tensordict to disk, and returns a memory-mapped copy of it.

TensorDictBase.memmap([prefix, ...])

Writes every leaf to a memory-mapped file and returns a new tensordict of them.

TensorDictBase.memmap_([prefix, ...])

Writes every leaf to a memory-mapped file in place, and returns self.

TensorDictBase.memmap_like([prefix, ...])

Creates a memory-mapped tensordict with the same keys, shapes and dtypes, without copying the values.

TensorDictBase.memmap_refresh_(*[, allow_pickle])

Reloads the tensordict from its saved_path, and returns self.

TensorDictBase.load_memmap(prefix[, device, ...])

Loads a tensordict that memmap() or save() wrote, from a directory or an archive.

TensorDictBase.load_memmap_(prefix[, ...])

Loads a saved tensordict into the tensordict, and returns self.

TensorDictBase.make_memmap(key, shape, *[, ...])

Adds an uninitialized memory-mapped tensor of shape shape at key, and returns it.

TensorDictBase.make_memmap_from_storage(key, ...)

Adds a memory-mapped tensor at key that reads its data from storage, and returns it.

TensorDictBase.make_memmap_from_tensor(key, ...)

Adds a memory-mapped copy of tensor at key, and returns it.

TensorDictBase.is_memmap()

Whether the tensordict is memory-mapped.

TensorDictBase.saved_path

The directory where a memory-mapped tensordict stores its files, as a Path.

TensorDictBase.state_dict([destination, ...])

Returns the leaves of the tensordict in an OrderedDict, as torch.nn.Module.state_dict() does.

TensorDictBase.load_state_dict(state_dict[, ...])

Loads a state dict, as state_dict() returns it, into the tensordict, and returns self.

TensorDictBase.from_h5(filename, *[, mode, ...])

Opens an HDF5 file as a PersistentTensorDict.

TensorDictBase.to_h5(filename, **kwargs)

Writes the tensordict to a new HDF5 file and returns a tensordict backed by it.

TensorDictBase.from_zarr(filename, *[, ...])

Opens a zarr store as a PersistentTensorDict.

TensorDictBase.to_zarr(filename, *[, ...])

Writes the tensordict to a new zarr store and returns a tensordict backed by it.

TensorDictBase.from_csv(path, *[, ...])

Reads a CSV file into a tensordict, with one entry per column.

TensorDictBase.to_csv(path, *[, separator])

Writes the tensordict to a CSV file, with one column per leaf.

TensorDictBase.from_json(path, *[, ...])

Reads a JSON file of records into a tensordict, with one entry per field.

TensorDictBase.to_json(path, *[, separator, ...])

Writes the tensordict to a JSON file, as an array of records.

TensorDictBase.from_parquet(path, *[, ...])

Reads a Parquet file into a tensordict, with one entry per column.

TensorDictBase.to_parquet(path, *[, separator])

Writes the tensordict to a Parquet file, with one column per leaf.

TensorDictBase.to_mds(*[, columns, ...])

Writes the tensordict to a MosaicML Streaming (MDS) dataset.

TensorDictBase.to_store(*[, backend, host, ...])

Uploads the tensordict to a key-value server and returns a tensordict backed by it.

Functions

save(data[, prefix, copy_existing, ...])

Saves a tensordict to disk, and returns a memory-mapped copy of it.

load(prefix[, device, non_blocking, out, ...])

Loads a tensordict that save() wrote.

memmap(data[, prefix, copy_existing, ...])

Writes every leaf to a memory-mapped file and returns a new tensordict of them.

load_memmap(prefix[, device, non_blocking, ...])

Loads a tensordict that memmap() or save() wrote.

append_memmap(prefix, rows, *[, allow_pickle])

Appends rows to a tensordict saved in a directory, along its first batch dimension.

pack_memmap(prefix, archive_path, *[, ...])

Packs a memory-mapped tensordict directory into a single-file zip archive.

unpack_memmap(archive_path, prefix)

Extracts a memory-mapped tensordict archive into a directory.

is_memmap_archive(path)

Whether path is a memory-mapped tensordict archive.

refresh_archive_checksums(archive_path)

Recomputes the CRC-32 checksums of a memory-mapped archive after in-place writes.

to_safetensors(data, path)

Saves a tensordict or a tensorclass to a safetensors file.

from_safetensors(path, *[, device])

Loads a tensordict from a safetensors file.

from_h5(h5_file, *[, mode, auto_batch_size, ...])

Opens an HDF5 file as a PersistentTensorDict.

from_zarr(zarr_file, *[, mode, ...])

Opens a zarr store as a PersistentTensorDict.

from_csv(path, *[, auto_batch_size, ...])

Reads a CSV file into a tensordict, with one entry per column.

from_json(path, *[, auto_batch_size, ...])

Reads a JSON file of records into a tensordict, with one entry per field.

from_parquet(path, *[, auto_batch_size, ...])

Reads a Parquet file into a tensordict, with one entry per column.

from_arrow(table, *[, copy, nulls, ...])

Converts an Arrow table to a tensordict, with one entry per column, viewing the data where it can.

to_arrow(td)

Converts a tensordict with one batch dimension to an Arrow table, with one column per entry.

Locking#

A locked tensordict raises an error if you add, replace, rename, or delete an entry. In-place writes with set_ and update_ still work, also for non-tensor entries. unlock_ also works in a with block: the tensordict is locked again at the end of the block. See Keys, nested keys, and locking.

TensorDictBase.lock_()

Locks the tensordict and its nested tensordicts, and returns it.

TensorDictBase.unlock_()

Unlocks the tensordict and its nested tensordicts, and returns it.

TensorDictBase.is_locked

True if the tensordict is locked.

Distributed and remote#

Send and receive tensordicts between processes with torch.distributed, run collective operations on them, and stream them over UCXX (see Key-value stores and UCXX). See Distributed tensordicts.

TensorDictBase.send([dst, group, group_dst, ...])

Sends the leaves of the tensordict to another rank, with torch.distributed.

TensorDictBase.recv([src, group, group_src, ...])

Receives the leaves that send() sends, and writes them into the tensordict in place.

TensorDictBase.isend([dst, group, ...])

Sends the leaves of the tensordict to another rank, one asynchronous transfer per leaf.

TensorDictBase.irecv([src, group, ...])

Receives the leaves that isend() or send() sends, one asynchronous transfer per leaf.

TensorDictBase.all_reduce([op, group, ...])

Reduces each leaf over all the ranks of the group, in place, so that every rank holds the result.

TensorDictBase.reduce(dst[, op, async_op, ...])

Reduces each leaf over all the ranks of the group, into the tensordict of rank dst.

TensorDictBase.broadcast(src, *[, group, ...])

Sends the tensordict of rank src to every rank of the group, and returns it on each rank.

TensorDictBase.scatter(src[, tensordicts, ...])

Scatters a list of tensordicts from src to all ranks.

TensorDictBase.all_gather(*[, group])

Returns a list with the tensordict of each rank of the group, on every rank.

TensorDictBase.gather_and_stack(dst[, group])

Stacks the tensordicts of the other ranks into the tensordict of rank dst, in place.

TensorDictBase.init_remote([dst, group, ...])

Sends the structure and the content of the tensordict to a rank that does not know them.

TensorDictBase.from_remote_init(src[, ...])

Receives a tensordict that init_remote() sends, and returns it.

TensorDictBase.asend(dst)

Sends the tensordict through a UCXX pipe, asynchronously.

TensorDictBase.arecv(src, *[, device])

Receives a tensordict from a UCXX pipe, into the tensordict if possible, asynchronously.

Deprecated methods#

These methods still work, and each call raises a DeprecationWarning. Their pages name the replacement and the release that removes them.

TensorDictBase.load_(prefix, *args, **kwargs)

Loads a saved tensordict into the tensordict.

TensorDictBase.pin_memory_([num_threads])

Pins the tensor leaves of the tensordict and returns self.

TensorDictBase.qint8(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.qint8.

TensorDictBase.qint32(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.qint32.

TensorDictBase.quint8(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.quint8.

TensorDictBase.quint4x2(*[, cast_filter])

Returns a tensordict whose tensor leaves are cast to torch.quint4x2.

Other functions#

Type checks and testing#

Test whether an object is a tensordict, a tensorclass, or non-tensor data, and compare two tensordicts in tests.

is_tensor_collection(datatype)

Returns True if an object or a type is a tensordict or a tensorclass.

is_tensorclass(obj)

Returns True if obj is a tensorclass type or an instance of one.

is_non_tensor(data)

Returns True if data is non-tensor data or a stack of non-tensor data.

assert_close(actual, expected[, rtol, atol, ...])

Asserts that two tensordicts have the same keys and close values.

assert_allclose_td(actual, expected[, rtol, ...])

Asserts that two tensordicts have the same keys and close values.

Printing#

Choose what the representation of a tensordict shows, and rebuild a tensordict from its printed form. See Printing and display.

set_printoptions(*[, verbose])

Sets the options that control what the repr of a tensordict shows.

get_printoptions()

Returns the current print options of tensordicts as a dict.

parse_tensor_dict_string(s)

Builds a TensorDict from its printed form.

Global settings#

These functions read or change a behavior of tensordict, for the whole process or inside a with block. set_list_to_stack(False) and set_capture_non_tensor_stack(True) are deprecated, and their pages say what to use instead.

list_to_stack([allow_none])

Returns whether assigning a list to a key stores a NonTensorStack.

set_list_to_stack(mode)

Sets whether assigning a list to a key stores a stack of non-tensor data.

capture_non_tensor_stack([allow_none])

Returns whether stacking identical non-tensor data gives one value instead of a stack.

set_capture_non_tensor_stack(mode)

Sets whether stacking identical non-tensor data gives one value instead of a stack.

Deprecated functions#

These functions still work. Their pages name the replacement and the release that removes them.

get_defaults_to_none([set_to_none])

Returns whether get() returns None for a missing key.

set_get_defaults_to_none([set_to_none])

Sets whether get() returns None or raises for a missing key.

lazy_legacy([allow_none])

Returns whether the legacy lazy mode is on.

set_lazy_legacy(mode)

Turns the legacy lazy mode on or off.

Package constants#

tensordict.KEY_SEPARATOR#

".", the default separator of flatten_keys() and unflatten_keys(), for code that joins or splits nested keys the same way, such as tuple(name.split(KEY_SEPARATOR)). The names of state_dict() also use ".", the torch.nn.Module convention, independently of this constant. Reassigning it has no effect: the defaults are bound when the methods are defined. It can also be imported from tensordict.utils.

tensordict.base.NO_DEFAULT#

The sentinel that marks an argument as not given where None is a valid value, such as default in get_non_tensor() or device in new_zeros(). It can also be imported from tensordict.tensordict.

tensordict.__version__#

The version string of the installed tensordict package, or None if it cannot be determined, for example when tensordict is imported from a source tree that is not installed.

See also#