TensorDictBase.state_dict#
- TensorDictBase.state_dict(destination=None, prefix='', keep_vars=False, flatten=True) OrderedDict[str, Any]#
Returns the leaves of the tensordict in an
OrderedDict, astorch.nn.Module.state_dict()does.The state dict is flat by default: the key of a nested leaf joins its keys with
"."("n.b"for("n", "b")), followingtorch.nn.Module.state_dict(). Withflatten=False, each nested tensordict becomes a nestedOrderedDict. Read it back withload_state_dict().The batch size and device of each level are stored in a
_metadataattribute of the result, as intorch.nn.Module.state_dict(). In a flat state dict, they are stored under the"."-joined key of the level (""for the root,"n"for the nested tensordict"n"). In a nested state dict, each nestedOrderedDicthas its own_metadata.- Parameters:
destination (OrderedDict, optional) – an
OrderedDictto write the entries into, and to return. A plaindictraises anAttributeError. Defaults toNone, which creates a newOrderedDict.prefix (str, optional) – a string prepended to every key. Defaults to
"".keep_vars (bool, optional) – if
False, the tensors are detached from autograd. IfTrue, the tensors of the tensordict are returned unchanged. Defaults toFalse.flatten (bool, optional) – if
True, nested keys are joined with".". IfFalse, nested tensordicts become nestedOrderedDictinstances. Defaults toTrue.
- Raises:
KeyError – if
flatten=Trueand two entries get the same key, as a dotted key"a.b"and a nested key("a", "b")do. The key of a level in_metadatacounts too. Useflatten=Falseto keep such entries apart.- Returns:
destination, or a newOrderedDict.
Examples
>>> from tensordict import TensorDict >>> data = TensorDict({"1": 1, "2": 2, "3": {"3": 3}}, []) >>> sd = data.state_dict() >>> print(dict(sd)) {'1': tensor(1), '2': tensor(2), '3.3': tensor(3)} >>> print(dict(sd._metadata)) {'': {'batch_size': torch.Size([]), 'device': None}, '3': {'batch_size': torch.Size([]), 'device': None}}
Every tensordict class and every tensorclass has this method. For the other methods, see Methods by task.