-
Notifications
You must be signed in to change notification settings - Fork 328
/
Copy pathtensordict.py
3738 lines (3201 loc) · 129 KB
/
tensordict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import annotations
import abc
import functools
import tempfile
import textwrap
import uuid
from collections.abc import Mapping
from copy import copy, deepcopy
from numbers import Number
from textwrap import indent
from typing import (
Callable,
Dict,
Generator,
Iterator,
KeysView,
List,
Optional,
Sequence,
Set,
Tuple,
Type,
Union,
)
from warnings import warn
import numpy as np
import torch
from torchrl import KeyDependentDefaultDict, prod
from torchrl.data.tensordict.memmap import MemmapTensor
from torchrl.data.tensordict.metatensor import MetaTensor
from torchrl.data.tensordict.utils import (
_getitem_batch_size,
_sub_index,
convert_ellipsis_to_idx,
)
from torchrl.data.utils import DEVICE_TYPING, expand_as_right, INDEX_TYPING
__all__ = [
"TensorDict",
"SubTensorDict",
"merge_tensordicts",
"LazyStackedTensorDict",
"SavedTensorDict",
]
TD_HANDLED_FUNCTIONS: Dict = dict()
COMPATIBLE_TYPES = Union[
torch.Tensor,
MemmapTensor,
] # None? # leaves space for _TensorDict
_accepted_classes = (torch.Tensor, MemmapTensor)
class _TensorDict(Mapping, metaclass=abc.ABCMeta):
"""
_TensorDict is an abstract parent class for TensorDicts, the torchrl
data container.
"""
_safe = False
_lazy = False
def __init__(self):
raise NotImplementedError
@property
def shape(self) -> torch.Size:
"""See _TensorDict.batch_size"""
return self.batch_size
@property
@abc.abstractmethod
def batch_size(self) -> torch.Size:
"""Shape of (or batch_size) of a TensorDict.
The shape of a tensordict corresponds to the common N first
dimensions of the tensors it contains, where N is an arbitrary
number. The TensorDict shape is controlled by the user upon
initialization (i.e. it is not inferred from the tensor shapes) and
it should not be changed dynamically.
Returns:
a torch.Size object describing the TensorDict batch size.
"""
raise NotImplementedError
def _batch_size_setter(self, new_batch_size: torch.Size) -> None:
if self._lazy:
raise RuntimeError(
"modifying the batch size of a lazy repesentation of a "
"tensordict is not permitted. Consider instantiating the "
"tensordict fist by calling `td = td.to_tensordict()` before "
"resetting the batch size."
)
if not isinstance(new_batch_size, torch.Size):
new_batch_size = torch.Size(new_batch_size)
self._check_new_batch_size(new_batch_size)
self._change_batch_size(new_batch_size)
@property
def batch_dims(self) -> int:
"""Length of the tensordict batch size.
Returns:
int describing the number of dimensions of the tensordict.
"""
return len(self.batch_size)
def ndimension(self) -> int:
return self.batch_dims
def dim(self) -> int:
return self.batch_dims
@property
@abc.abstractmethod
def device(self) -> torch.device:
"""Device of a TensorDict. All tensors of a tensordict must live on the
same device.
Returns:
torch.device object indicating the device where the tensors
are placed.
"""
raise NotImplementedError
@device.setter
@abc.abstractmethod
def device(self, value: DEVICE_TYPING) -> None:
raise NotImplementedError
@abc.abstractmethod
def _device_safe(self) -> Union[None, torch.device]:
raise NotImplementedError
def is_shared(self, no_check: bool = True) -> bool:
"""Checks if tensordict is in shared memory.
This is always True for CUDA tensordicts, except when stored as
MemmapTensors.
Args:
no_check (bool, optional): whether to use cached value or not
Default is True
"""
if no_check:
if self._is_shared is None:
if self.keys():
_is_shared = all(value.is_shared() for value in self.values_meta())
else:
_is_shared = None
self._is_shared = _is_shared
return self._is_shared
return all(item.is_shared() for item in self.values_meta())
def is_memmap(self, no_check: bool = True) -> bool:
"""Checks if tensordict is stored with MemmapTensors.
Args:
no_check (bool, optional): whether to use cached value or not
Default is True
"""
if no_check:
if self._is_memmap is None:
if self.keys():
_is_memmap = all(value.is_memmap() for value in self.values_meta())
else:
_is_memmap = None
self._is_memmap = _is_memmap
return self._is_memmap
return all(item.is_memmap() for item in self.values_meta())
def numel(self) -> int:
"""Total number of elements in the batch."""
return max(1, prod(self.batch_size))
def _check_batch_size(self) -> None:
bs = [value.shape[: self.batch_dims] for key, value in self.items_meta()] + [
self.batch_size
]
if len(set(bs)) > 1:
raise RuntimeError(
f"batch_size are incongruent, got {list(set(bs))}, "
f"-- expected {self.batch_size}"
)
def _check_is_shared(self) -> bool:
raise NotImplementedError(f"{self.__class__.__name__}")
def _check_device(self) -> None:
raise NotImplementedError(f"{self.__class__.__name__}")
def set(
self, key: str, item: COMPATIBLE_TYPES, inplace: bool = False, **kwargs
) -> _TensorDict:
"""Sets a new key-value pair.
Args:
key (str): name of the value
item (torch.Tensor): value to be stored in the tensordict
inplace (bool, optional): if True and if a key matches an existing
key in the tensordict, then the update will occur in-place
for that key-value pair. Default is `False`.
Returns:
self
"""
raise NotImplementedError(f"{self.__class__.__name__}")
@abc.abstractmethod
def set_(
self, key: str, item: COMPATIBLE_TYPES, no_check: bool = False
) -> _TensorDict:
"""Sets a value to an existing key while keeping the original storage.
Args:
key (str): name of the value
item (torch.Tensor): value to be stored in the tensordict
no_check (bool, optional): if True, it is assumed that device and shape
match the original tensor and that the keys is in the tensordict.
Returns:
self
"""
raise NotImplementedError(f"{self.__class__.__name__}")
def _default_get(
self, key: str, default: Union[str, COMPATIBLE_TYPES] = "_no_default_"
) -> COMPATIBLE_TYPES:
if not isinstance(default, str):
return default
if default == "_no_default_":
raise KeyError(
f'key "{key}" not found in {self.__class__.__name__} with '
f"keys {sorted(list(self.keys()))}"
)
else:
raise ValueError(
f"default should be None or a torch.Tensor instance, " f"got {default}"
)
@abc.abstractmethod
def get(
self, key: str, default: Union[str, COMPATIBLE_TYPES] = "_no_default_"
) -> COMPATIBLE_TYPES:
"""
Gets the value stored with the input key.
Args:
key (str): key to be queried.
default: default value if the key is not found in the tensordict.
"""
raise NotImplementedError(f"{self.__class__.__name__}")
def _get_meta(self, key) -> MetaTensor:
raise NotImplementedError(f"{self.__class__.__name__}")
def apply_(self, fn: Callable) -> _TensorDict:
"""Applies a callable to all values stored in the tensordict and
re-writes them in-place.
Args:
fn (Callable): function to be applied to the tensors in the
tensordict.
Returns:
self
"""
for key, item in self.items():
item_trsf = fn(item)
if item_trsf is not None:
self.set(key, item_trsf, inplace=True)
return self
def apply(
self, fn: Callable, batch_size: Optional[Sequence[int]] = None
) -> _TensorDict:
"""Applies a callable to all values stored in the tensordict and sets
them in a new tensordict.
Args:
fn (Callable): function to be applied to the tensors in the
tensordict.
batch_size (sequence of int, optional): if provided,
the resulting TensorDict will have the desired batch_size.
The `batch_size` argument should match the batch_size after
the transformation.
Returns:
a new tensordict with transformed_in tensors.
"""
if batch_size is None:
td = TensorDict({}, batch_size=self.batch_size, device=self._device_safe())
else:
td = TensorDict(
{}, batch_size=torch.Size(batch_size), device=self._device_safe()
)
for key, item in self.items():
item_trsf = fn(item)
td.set(key, item_trsf)
return td
def update(
self,
input_dict_or_td: Union[Dict[str, COMPATIBLE_TYPES], _TensorDict],
clone: bool = False,
inplace: bool = False,
**kwargs,
) -> _TensorDict:
"""Updates the TensorDict with values from either a dictionary or
another TensorDict.
Args:
input_dict_or_td (_TensorDict or dict): Does not keyword arguments
(unlike `dict.update()`).
clone (bool, optional): whether the tensors in the input (
tensor) dict should be cloned before being set. Default is
`False`.
inplace (bool, optional): if True and if a key matches an existing
key in the tensordict, then the update will occur in-place
for that key-value pair. Default is `False`.
**kwargs: keyword arguments for the `TensorDict.set` method
Returns:
self
"""
if input_dict_or_td is self:
# no op
return self
for key, value in input_dict_or_td.items():
if not isinstance(value, _accepted_classes):
raise TypeError(
f"Expected value to be one of types "
f"{_accepted_classes} but got {type(value)}"
)
if clone:
value = value.clone()
self.set(key, value, inplace=inplace, **kwargs)
return self
def update_(
self,
input_dict_or_td: Union[Dict[str, COMPATIBLE_TYPES], _TensorDict],
clone: bool = False,
) -> _TensorDict:
"""Updates the TensorDict in-place with values from either a dictionary
or another TensorDict.
Unlike TensorDict.update, this function will
throw an error if the key is unknown to the TensorDict
Args:
input_dict_or_td (_TensorDict or dict): Does not keyword
arguments (unlike `dict.update()`).
clone (bool, optional): whether the tensors in the input (
tensor) dict should be cloned before being set. Default is
`False`.
Returns:
self
"""
if input_dict_or_td is self:
# no op
return self
for key, value in input_dict_or_td.items():
if not isinstance(value, _accepted_classes):
raise TypeError(
f"Expected value to be one of types {_accepted_classes} "
f"but got {type(value)}"
)
if clone:
value = value.clone()
self.set_(key, value)
return self
def update_at_(
self,
input_dict_or_td: Union[Dict[str, COMPATIBLE_TYPES], _TensorDict],
idx: INDEX_TYPING,
clone: bool = False,
) -> _TensorDict:
"""Updates the TensorDict in-place at the specified index with
values from either a dictionary or another TensorDict.
Unlike TensorDict.update, this function will throw an error if the
key is unknown to the TensorDict.
Args:
input_dict_or_td (_TensorDict or dict): Does not keyword arguments
(unlike `dict.update()`).
idx (int, torch.Tensor, iterable, slice): index of the tensordict
where the update should occur.
clone (bool, optional): whether the tensors in the input (
tensor) dict should be cloned before being set. Default is
`False`.
Returns:
self
Examples:
>>> td = TensorDict(source={'a': torch.zeros(3, 4, 5),
... 'b': torch.zeros(3, 4, 10)}, batch_size=[3, 4])
>>> td.update_at_(
... TensorDict(source={'a': torch.ones(1, 4, 5),
... 'b': torch.ones(1, 4, 10)}, batch_size=[1, 4]),
... slice(1, 2))
TensorDict(
fields={a: Tensor(torch.Size([3, 4, 5]), dtype=torch.float32),
b: Tensor(torch.Size([3, 4, 10]),\
dtype=torch.float32)},
shared=False,
batch_size=torch.Size([3, 4]),
device=cpu)
"""
for key, value in input_dict_or_td.items():
if not isinstance(value, _accepted_classes):
raise TypeError(
f"Expected value to be one of types {_accepted_classes} "
f"but got {type(value)}"
)
if clone:
value = value.clone()
self.set_at_(
key,
value,
idx,
)
return self
def _convert_to_tensor(
self, array: np.ndarray
) -> Union[torch.Tensor, MemmapTensor]:
return torch.tensor(array, device=self.device)
def _process_tensor(
self,
input: Union[COMPATIBLE_TYPES, np.ndarray],
check_device: bool = True,
check_tensor_shape: bool = True,
check_shared: bool = False,
) -> Union[torch.Tensor, MemmapTensor]:
# TODO: move to _TensorDict?
if not isinstance(input, _accepted_classes):
tensor = self._convert_to_tensor(input)
else:
tensor = input
if check_device and self._device_safe() is not None:
device = self.device
tensor = tensor.to(device)
elif self._device_safe() is None:
self.device = tensor.device
if check_shared:
raise DeprecationWarning("check_shared is not authorized anymore")
if check_tensor_shape and tensor.shape[: self.batch_dims] != self.batch_size:
raise RuntimeError(
f"batch dimension mismatch, got self.batch_size"
f"={self.batch_size} and tensor.shape[:self.batch_dims]"
f"={tensor.shape[: self.batch_dims]}"
)
# minimum ndimension is 1
if tensor.ndimension() - self.ndimension() == 0:
tensor = tensor.unsqueeze(-1)
return tensor
@abc.abstractmethod
def pin_memory(self) -> _TensorDict:
"""Calls pin_memory() on the stored tensors."""
raise NotImplementedError(f"{self.__class__.__name__}")
# @abc.abstractmethod
# def is_pinned(self) -> bool:
# """Checks if tensors are pinned."""
# raise NotImplementedError(f"{self.__class__.__name__}")
def items(self) -> Iterator[Tuple[str, COMPATIBLE_TYPES]]:
"""
Returns a generator of key-value pairs for the tensordict.
"""
for k in self.keys():
yield k, self.get(k)
def values(self) -> Iterator[COMPATIBLE_TYPES]:
"""
Returns a generator representing the values for the tensordict.
"""
for k in self.keys():
yield self.get(k)
def items_meta(self) -> Iterator[Tuple[str, MetaTensor]]:
"""Returns a generator of key-value pairs for the tensordict, where the
values are MetaTensor instances corresponding to the stored tensors.
"""
for k in self.keys():
yield k, self._get_meta(k)
def values_meta(self) -> Iterator[MetaTensor]:
"""Returns a generator representing the values for the tensordict, those
values are MetaTensor instances corresponding to the stored tensors.
"""
for k in self.keys():
yield self._get_meta(k)
@abc.abstractmethod
def keys(self) -> KeysView:
"""Returns a generator of tensordict keys."""
raise NotImplementedError(f"{self.__class__.__name__}")
def expand(self, *shape: int) -> _TensorDict:
"""Expands each tensors of the tensordict according to
`tensor.expand(*shape, *tensor.shape)`
Examples:
>>> td = TensorDict(source={'a': torch.zeros(3, 4, 5),
... 'b': torch.zeros(3, 4, 10)}, batch_size=[3, 4])
>>> td_expand = td.expand(10)
>>> assert td_expand.shape == torch.Size([10, 3, 4])
>>> assert td_expand.get("a").shape == torch.Size([10, 3, 4, 5])
"""
return TensorDict(
source={
key: value.expand(*shape, *value.shape) for key, value in self.items()
},
batch_size=[*shape, *self.batch_size],
device=self._device_safe(),
)
def __bool__(self) -> bool:
raise ValueError("Converting a tensordict to boolean value is not permitted")
def __ne__(self, other: object) -> _TensorDict:
"""XOR operation over two tensordicts, for evey key. The two
tensordicts must have the same key set.
Returns:
a new TensorDict instance with all tensors are boolean
tensors of the same shape as the original tensors.
"""
if not isinstance(other, _TensorDict):
raise TypeError(
f"TensorDict comparision requires both objects to be "
f"_TensorDict subclass, got {type(other)}"
)
keys1 = set(self.keys())
keys2 = set(other.keys())
if len(keys1.difference(keys2)) or len(keys1) != len(keys2):
raise KeyError(
f"keys in {self} and {other} mismatch, got {keys1} and {keys2}"
)
d = dict()
for (key, item1) in self.items():
d[key] = item1 != other.get(key)
return TensorDict(
batch_size=self.batch_size, source=d, device=self._device_safe()
)
def __eq__(self, other: object) -> _TensorDict:
"""Compares two tensordicts against each other, for evey key. The two
tensordicts must have the same key set.
Returns:
a new TensorDict instance with all tensors are boolean
tensors of the same shape as the original tensors.
"""
if not isinstance(other, _TensorDict):
raise TypeError(
f"TensorDict comparision requires both objects to be "
f"_TensorDict subclass, got {type(other)}"
)
keys1 = set(self.keys())
keys2 = set(other.keys())
if len(keys1.difference(keys2)) or len(keys1) != len(keys2):
raise KeyError(f"keys in tensordicts mismatch, got {keys1} and {keys2}")
d = dict()
for (key, item1) in self.items():
d[key] = item1 == other.get(key)
return TensorDict(
batch_size=self.batch_size, source=d, device=self._device_safe()
)
@abc.abstractmethod
def del_(self, key: str) -> _TensorDict:
"""Deletes a key of the tensordict.
Args:
key (str): key to be deleted
Returns:
self
"""
raise NotImplementedError(f"{self.__class__.__name__}")
@abc.abstractmethod
def select(self, *keys: str, inplace: bool = False) -> _TensorDict:
"""Selects the keys of the tensordict and returns an new tensordict
with only the selected keys.
The values are not copied: in-place modifications a tensor of either
of the original or new tensordict will result in a change in both
tensordicts.
Args:
*keys (str): keys to select
inplace (bool): if True, the tensordict is pruned in place.
Default is `False`.
Returns:
A new tensordict with the selected keys only.
"""
raise NotImplementedError(f"{self.__class__.__name__}")
def exclude(self, *keys: str, inplace: bool = False) -> _TensorDict:
keys = [key for key in self.keys() if key not in keys]
return self.select(*keys, inplace=inplace)
@abc.abstractmethod
def set_at_(
self, key: str, value: COMPATIBLE_TYPES, idx: INDEX_TYPING
) -> _TensorDict:
"""Sets the values in-place at the index indicated by `idx`.
Args:
key (str): key to be modified.
value (torch.Tensor): value to be set at the index `idx`
idx (int, tensor or tuple): index where to write the values.
Returns:
self
"""
raise NotImplementedError(f"{self.__class__.__name__}")
def copy_(self, tensordict: _TensorDict) -> _TensorDict:
"""See `_TensorDict.update_`."""
return self.update_(tensordict)
def copy_at_(self, tensordict: _TensorDict, idx: INDEX_TYPING) -> _TensorDict:
"""See `_TensorDict.update_at_`."""
return self.update_at_(tensordict, idx)
def get_at(
self, key: str, idx: INDEX_TYPING, default: COMPATIBLE_TYPES = "_no_default_"
) -> COMPATIBLE_TYPES:
"""Get the value of a tensordict from the key `key` at the index `idx`.
Args:
key (str): key to be retrieved.
idx (int, slice, torch.Tensor, iterable): index of the tensor.
default (torch.Tensor): default value to return if the key is
not present in the tensordict.
Returns:
indexed tensor.
"""
value = self.get(key, default=default)
if value is not default:
return value[idx]
return value
@abc.abstractmethod
def share_memory_(self) -> _TensorDict:
"""Places all the tensors in shared memory.
Returns:
self.
"""
raise NotImplementedError(f"{self.__class__.__name__}")
@abc.abstractmethod
def memmap_(self) -> _TensorDict:
"""Writes all tensors onto a MemmapTensor.
Returns:
self.
"""
raise NotImplementedError(f"{self.__class__.__name__}")
@abc.abstractmethod
def detach_(self) -> _TensorDict:
"""Detach the tensors in the tensordict in-place.
Returns:
self.
"""
raise NotImplementedError(f"{self.__class__.__name__}")
def detach(self) -> _TensorDict:
"""Detach the tensors in the tensordict.
Returns:
a new tensordict with no tensor requiring gradient.
"""
return TensorDict(
{key: item.detach() for key, item in self.items()},
batch_size=self.batch_size,
device=self._device_safe(),
)
def to_tensordict(self):
"""Returns a regular TensorDict instance from the _TensorDict.
Returns:
a new TensorDict object containing the same values.
"""
return self.to(TensorDict)
def zero_(self) -> _TensorDict:
"""Zeros all tensors in the tensordict in-place."""
for key in self.keys():
self.fill_(key, 0)
return self
def unbind(self, dim: int) -> Tuple[_TensorDict, ...]:
"""Returns a tuple of indexed tensordicts unbound along the
indicated dimension. Resulting tensordicts will share
the storage of the initial tensordict.
"""
idx = [
(tuple(slice(None) for _ in range(dim)) + (i,))
for i in range(self.shape[dim])
]
return tuple(self[_idx] for _idx in idx)
def chunk(self, chunks: int, dim: int = 0) -> Tuple[_TensorDict, ...]:
"""Attempts to split a tendordict into the specified number of
chunks. Each chunk is a view of the input tensordict.
Args:
chunks (int): number of chunks to return
dim (int, optional): dimension along which to split the
tensordict. Default is 0.
"""
if chunks < 1:
raise ValueError(
f"chunks must be a strictly positive integer, got {chunks}."
)
indices = []
_idx_start = 0
if chunks > 1:
interval = _idx_end = self.batch_size[dim] // chunks
else:
interval = _idx_end = self.batch_size[dim]
for c in range(chunks):
indices.append(slice(_idx_start, _idx_end))
_idx_start = _idx_end
if c < chunks - 2:
_idx_end = _idx_end + interval
else:
_idx_end = self.batch_size[dim]
if dim < 0:
dim = len(self.batch_size) + dim
return tuple(self[(*[slice(None) for _ in range(dim)], idx)] for idx in indices)
def clone(self, recursive: bool = True) -> _TensorDict:
"""Clones a _TensorDict subclass instance onto a new TensorDict.
Args:
recursive (bool, optional): if True, each tensor contained in the
TensorDict will be copied too. Default is `True`.
"""
return TensorDict(
source={
key: value.clone() if recursive else value
for key, value in self.items()
},
batch_size=self.batch_size,
device=self._device_safe(),
)
@classmethod
def __torch_function__(
cls,
func: Callable,
types,
args: Tuple = (),
kwargs: Optional[dict] = None,
) -> Callable:
if kwargs is None:
kwargs = {}
if func not in TD_HANDLED_FUNCTIONS or not all(
issubclass(t, (torch.Tensor, _TensorDict)) for t in types
):
return NotImplemented
return TD_HANDLED_FUNCTIONS[func](*args, **kwargs)
@abc.abstractmethod
def to(self, dest: Union[DEVICE_TYPING, Type, torch.Size], **kwargs) -> _TensorDict:
"""Maps a _TensorDict subclass either on a new device or to another
_TensorDict subclass (if permitted). Casting tensors to a new dtype
is not allowed, as tensordicts are not bound to contain a single
tensor dtype.
Args:
dest (device, size or _TensorDict subclass): destination of the
tensordict. If it is a torch.Size object, the batch_size
will be updated provided that it is compatible with the
stored tensors.
Returns:
a new tensordict. If device indicated by dest differs from
the tensordict device, this is a no-op.
"""
raise NotImplementedError
def _check_new_batch_size(self, new_size: torch.Size):
n = len(new_size)
for key, meta_tensor in self.items_meta():
if (meta_tensor.ndimension() < n) or (meta_tensor.shape[:n] != new_size):
raise RuntimeError(
f"the tensor {key} has shape {meta_tensor.shape} which "
f"is incompatible with the new shape {new_size}"
)
@abc.abstractmethod
def _change_batch_size(self, new_size: torch.Size):
raise NotImplementedError
def cpu(self) -> _TensorDict:
"""Casts a tensordict to cpu (if not already on cpu)."""
return self.to("cpu")
def cuda(self, device: int = 0) -> _TensorDict:
"""Casts a tensordict to a cuda device (if not already on it)."""
return self.to(f"cuda:{device}")
@abc.abstractmethod
def masked_fill_(
self, mask: torch.Tensor, value: Union[float, bool]
) -> _TensorDict:
"""Fills the values corresponding to the mask with the desired value.
Args:
mask (boolean torch.Tensor): mask of values to be filled. Shape
must match tensordict shape.
value: value to used to fill the tensors.
Returns:
self
Examples:
>>> td = TensorDict(source={'a': torch.zeros(3, 4)},
... batch_size=[3])
>>> mask = torch.tensor([True, False, False])
>>> _ = td.masked_fill_(mask, 1.0)
>>> td.get("a")
tensor([[1., 1., 1., 1.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
"""
raise NotImplementedError
@abc.abstractmethod
def masked_fill(self, mask: torch.Tensor, value: Union[float, bool]) -> _TensorDict:
"""Out-of-place version of masked_fill
Args:
mask (boolean torch.Tensor): mask of values to be filled. Shape
must match tensordict shape.
value: value to used to fill the tensors.
Returns:
self
Examples:
>>> td = TensorDict(source={'a': torch.zeros(3, 4)},
... batch_size=[3])
>>> mask = torch.tensor([True, False, False])
>>> td1 = td.masked_fill(mask, 1.0)
>>> td1.get("a")
tensor([[1., 1., 1., 1.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
"""
raise NotImplementedError
def masked_select(self, mask: torch.Tensor) -> _TensorDict:
"""Masks all tensors of the TensorDict and return a new TensorDict
instance with similar keys pointing to masked values.
Args:
mask (torch.Tensor): boolean mask to be used for the tensors.
Shape must match the TensorDict batch_size.
Examples:
>>> td = TensorDict(source={'a': torch.zeros(3, 4)},
... batch_size=[3])
>>> mask = torch.tensor([True, False, False])
>>> td_mask = td.masked_select(mask)
>>> td_mask.get("a")
tensor([[0., 0., 0., 0.]])
"""
d = dict()
for key, value in self.items():
mask_expand = mask.squeeze(-1)
value_select = value[mask_expand]
d[key] = value_select
dim = int(mask.sum().item())
return TensorDict(
device=self._device_safe(), source=d, batch_size=torch.Size([dim])
)
@abc.abstractmethod
def is_contiguous(self) -> bool:
"""
Returns:
boolean indicating if all the tensors are contiguous.
"""
raise NotImplementedError
@abc.abstractmethod
def contiguous(self) -> _TensorDict:
"""
Returns:
a new tensordict of the same type with contiguous values (
or self if values are already contiguous).
"""
raise NotImplementedError
def to_dict(self) -> dict:
"""
Returns:
dictionary with key-value pairs matching those of the
tensordict.
"""
return {key: value for key, value in self.items()}
def unsqueeze(self, dim: int) -> _TensorDict:
"""Unsqueeze all tensors for a dimension comprised in between
`-td.batch_dims` and `td.batch_dims` and returns them in a new
tensordict.
Args:
dim (int): dimension along which to unsqueeze
"""
if dim < 0:
dim = self.batch_dims + dim + 1
if (dim > self.batch_dims) or (dim < 0):
raise RuntimeError(
f"unsqueezing is allowed for dims comprised between "
f"`-td.batch_dims` and `td.batch_dims` only. Got "
f"dim={dim} with a batch size of {self.batch_size}."
)