Shortcuts

TensorSpec

class torchrl.data.TensorSpec(shape: ~torch.Size, space: ~typing.Union[None, ~torchrl.data.tensor_specs.Box], device: torch.device | None = <property object>, dtype: ~torch.dtype = torch.float32, domain: str = '')[source]

Parent class of the tensor meta-data containers.

TorchRL’s TensorSpec are used to present what input/output is to be expected for a specific class, or sometimes to simulate simple behaviors by generating random data within a defined space.

TensorSpecs are primarily used in environments to specify their input/output structure without needing to execute the environment (or starting it). They can also be used to instantiate shared buffers to pass data from worker to worker.

TensorSpecs are dataclasses that always share the following fields: shape, space, `dtype and device.

As such, TensorSpecs possess some common behavior with Tensor and TensorDict: they can be reshaped, indexed, squeezed, unsqueezed, moved to another device etc.

Parameters:
  • shape (torch.Size) – size of the tensor. The shape includes the batch dimensions as well as the feature dimension. A negative shape (-1) means that the dimension has a variable number of elements.

  • space (Box) – Box instance describing what kind of values can be expected.

  • device (torch.device) – device of the tensor.

  • dtype (torch.dtype) – dtype of the tensor.

Note

A spec can be constructed from a TensorDict using the make_composite_from_td() function. This function makes a low-assumption educated guess on the specs that may correspond to the input tensordict and can help to build specs automatically without an in-depth knowledge of the TensorSpec API.

assert_is_in(value: Tensor) None[source]

Asserts whether a tensor belongs to the box, and raises an exception otherwise.

Parameters:

value (torch.Tensor) – value to be checked.

abstract cardinality() int[source]

The cardinality of the spec.

This refers to the number of possible outcomes in a spec. It is assumed that the cardinality of a composite spec is the cartesian product of all possible outcomes.

clear_device_() T[source]

A no-op for all leaf specs (which must have a device).

For Composite specs, this method will erase the device.

abstract clone() TensorSpec[source]

Creates a copy of the TensorSpec.

contains(item: torch.Tensor | tensordict.base.TensorDictBase) bool[source]

If the value val could have been generated by the TensorSpec, returns True, otherwise False.

See is_in() for more information.

cpu()[source]

Casts the TensorSpec to ‘cpu’ device.

cuda(device=None)[source]

Casts the TensorSpec to ‘cuda’ device.

property device: device

The device of the spec.

Only Composite specs can have a None device. All leaves must have a non-null device.

encode(val: numpy.ndarray | torch.Tensor | tensordict.base.TensorDictBase, *, ignore_device: bool = False) torch.Tensor | tensordict.base.TensorDictBase[source]

Encodes a value given the specified spec, and return the corresponding tensor.

This method is to be used in environments that return a value (eg, a numpy array) that can be easily mapped to the TorchRL required domain. If the value is already a tensor, the spec will not change its value and return it as-is.

Parameters:

val (np.ndarray or torch.Tensor) – value to be encoded as tensor.

Keyword Arguments:

ignore_device (bool, optional) – if True, the spec device will be ignored. This is used to group tensor casting within a call to TensorDict(..., device="cuda") which is faster.

Returns:

torch.Tensor matching the required tensor specs.

abstract enumerate() Any[source]

Returns all the samples that can be obtained from the TensorSpec.

The samples will be stacked along the first dimension.

This method is only implemented for discrete specs.

abstract expand(shape: Size)[source]

Returns a new Spec with the expanded shape.

Parameters:

*shape (tuple or iterable of int) – the new shape of the Spec. Must be broadcastable with the current shape: its length must be at least as long as the current shape length, and its last values must be compliant too; ie they can only differ from it if the current dimension is a singleton.

flatten(start_dim: int, end_dim: int) T[source]

Flattens a TensorSpec.

Check flatten() for more information on this method.

classmethod implements_for_spec(torch_function: Callable) Callable[source]

Register a torch function override for TensorSpec.

abstract index(index: Union[int, Tensor, ndarray, slice, List], tensor_to_index: torch.Tensor | tensordict.base.TensorDictBase) torch.Tensor | tensordict.base.TensorDictBase[source]

Indexes the input tensor.

Parameters:
  • index (int, torch.Tensor, slice or list) – index of the tensor

  • tensor_to_index – tensor to be indexed

Returns:

indexed tensor

abstract is_in(val: torch.Tensor | tensordict.base.TensorDictBase) bool[source]

If the value val could have been generated by the TensorSpec, returns True, otherwise False.

More precisely, the is_in methods checks that the value val is within the limits defined by the space attribute (the box), and that the dtype, device, shape potentially other metadata match those of the spec. If any of these checks fails, the is_in method will return False.

Parameters:

val (torch.Tensor) – value to be checked.

Returns:

boolean indicating if values belongs to the TensorSpec box.

make_neg_dim(dim: int) T[source]

Converts a specific dimension to -1.

property ndim: int

Number of dimensions of the spec shape.

Shortcut for len(spec.shape).

ndimension() int[source]

Number of dimensions of the spec shape.

Shortcut for len(spec.shape).

one(shape: Optional[Size] = None) torch.Tensor | tensordict.base.TensorDictBase[source]

Returns a one-filled tensor in the box.

Note

Even though there is no guarantee that 1 belongs to the spec domain, this method will not raise an exception when this condition is violated. The primary use case of one is to generate empty data buffers, not meaningful data.

Parameters:

shape (torch.Size) – shape of the one-tensor

Returns:

a one-filled tensor sampled in the TensorSpec box.

ones(shape: Optional[Size] = None) torch.Tensor | tensordict.base.TensorDictBase[source]

Proxy to one().

project(val: torch.Tensor | tensordict.base.TensorDictBase) torch.Tensor | tensordict.base.TensorDictBase[source]

If the input tensor is not in the TensorSpec box, it maps it back to it given some defined heuristic.

Parameters:

val (torch.Tensor) – tensor to be mapped to the box.

Returns:

a torch.Tensor belonging to the TensorSpec box.

abstract rand(shape: Optional[Size] = None) torch.Tensor | tensordict.base.TensorDictBase[source]

Returns a random tensor in the space defined by the spec.

The sampling will be done uniformly over the space, unless the box is unbounded in which case normal values will be drawn.

Parameters:

shape (torch.Size) – shape of the random tensor

Returns:

a random tensor sampled in the TensorSpec box.

reshape(shape) T[source]

Reshapes a TensorSpec.

Check reshape() for more information on this method.

sample(shape: Optional[Size] = None) torch.Tensor | tensordict.base.TensorDictBase[source]

Returns a random tensor in the space defined by the spec.

See rand() for details.

squeeze(dim: Optional[int] = None) T[source]

Returns a new Spec with all the dimensions of size 1 removed.

When dim is given, a squeeze operation is done only in that dimension.

Parameters:

dim (int or None) – the dimension to apply the squeeze operation to

abstract to(dest: Union[dtype, device, str, int]) TensorSpec[source]

Casts a TensorSpec to a device or a dtype.

Returns the same spec if no change is made.

to_numpy(val: torch.Tensor | tensordict.base.TensorDictBase, safe: Optional[bool] = None) numpy.ndarray | dict[source]

Returns the np.ndarray correspondent of an input tensor.

This is intended to be the inverse operation of encode().

Parameters:
  • val (torch.Tensor) – tensor to be transformed_in to numpy.

  • safe (bool) – boolean value indicating whether a check should be performed on the value against the domain of the spec. Defaults to the value of the CHECK_SPEC_ENCODE environment variable.

Returns:

a np.ndarray.

type_check(value: Tensor, key: Optional[NestedKey] = None) None[source]

Checks the input value dtype against the TensorSpec dtype and raises an exception if they don’t match.

Parameters:
  • value (torch.Tensor) – tensor whose dtype has to be checked.

  • key (str, optional) – if the TensorSpec has keys, the value dtype will be checked against the spec pointed by the indicated key.

unflatten(dim: int, sizes: Tuple[int]) T[source]

Unflattens a TensorSpec.

Check unflatten() for more information on this method.

unsqueeze(dim: int) T[source]

Returns a new Spec with one more singleton dimension (at the position indicated by dim).

Parameters:

dim (int or None) – the dimension to apply the unsqueeze operation to.

view(*shape) T

Reshapes a TensorSpec.

Check reshape() for more information on this method.

zero(shape: Optional[Size] = None) torch.Tensor | tensordict.base.TensorDictBase[source]

Returns a zero-filled tensor in the box.

Note

Even though there is no guarantee that 0 belongs to the spec domain, this method will not raise an exception when this condition is violated. The primary use case of zero is to generate empty data buffers, not meaningful data.

Parameters:

shape (torch.Size) – shape of the zero-tensor

Returns:

a zero-filled tensor sampled in the TensorSpec box.

zeros(shape: Optional[Size] = None) torch.Tensor | tensordict.base.TensorDictBase[source]

Proxy to zero().

Docs

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources