-
Notifications
You must be signed in to change notification settings - Fork 77
/
_td.py
5128 lines (4652 loc) · 184 KB
/
_td.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 numbers
import os
import weakref
from collections import defaultdict
from concurrent.futures import Future, ThreadPoolExecutor, wait
from copy import copy
from numbers import Number
from pathlib import Path
from textwrap import indent
from typing import Any, Callable, Dict, Iterable, Iterator, List, Sequence, Tuple, Type
from warnings import warn
import numpy as np
import orjson as json
import torch
from tensordict._nestedkey import NestedKey
from tensordict.base import (
_ACCEPTED_CLASSES,
_default_is_leaf,
_device_recorder,
_expand_to_match_shape,
_is_leaf_nontensor,
_is_tensor_collection,
_load_metadata,
_NESTED_TENSORS_AS_LISTS,
_register_tensor_class,
BEST_ATTEMPT_INPLACE,
CompatibleType,
is_tensor_collection,
NO_DEFAULT,
T,
TensorDictBase,
)
from tensordict.memmap import MemoryMappedTensor
from tensordict.utils import (
_add_batch_dim_pre_hook,
_as_context_manager,
_BatchedUninitializedBuffer,
_BatchedUninitializedParameter,
_check_inbuild,
_clone_value,
_get_item,
_get_leaf_tensordict,
_get_shape_from_args,
_getitem_batch_size,
_index_preserve_data_ptr,
_infer_size_impl,
_is_shared,
_is_tensorclass,
_KEY_ERROR,
_LOCK_ERROR,
_NON_STR_KEY_ERR,
_NON_STR_KEY_TUPLE_ERR,
_parse_to,
_prune_selected_keys,
_set_item,
_set_max_batch_size,
_shape,
_STRDTYPE2DTYPE,
_StringKeys,
_StringOnlyDict,
_sub_index,
_unravel_key_to_tuple,
_zip_strict,
cache,
convert_ellipsis_to_idx,
DeviceType,
expand_as_right,
IndexType,
is_non_tensor,
is_tensorclass,
KeyedJaggedTensor,
lock_blocked,
unravel_key,
unravel_key_list,
)
from torch import nn, Tensor
from torch._dynamo import graph_break
from torch._functorch.vmap import _maybe_remove_batch_dim
from torch.nn.parameter import UninitializedTensorMixin
from torch.nn.utils._named_member_accessor import swap_tensor
from torch.utils._pytree import tree_map
try:
from functorch import dim as ftdim
_has_funcdim = True
except ImportError:
from tensordict.utils import _ftdim_mock as ftdim
_has_funcdim = False
try:
from torch.compiler import is_dynamo_compiling
except ImportError: # torch 2.0
from torch._dynamo import is_compiling as is_dynamo_compiling
try:
from torch.nn.parameter import Buffer
except ImportError:
from tensordict.utils import Buffer
_register_tensor_class(ftdim.Tensor)
__base__setattr__ = torch.nn.Module.__setattr__
_has_mps = torch.backends.mps.is_available()
_has_cuda = torch.cuda.is_available()
_has_functorch = False
try:
try:
from torch._C._functorch import ( # @manual=fbcode//caffe2:torch
_add_batch_dim,
_remove_batch_dim,
is_batchedtensor,
)
except ImportError:
from functorch._C import is_batchedtensor # @manual=fbcode//functorch:_C
_has_functorch = True
except ImportError:
_has_functorch = False
def is_batchedtensor(tensor: Tensor) -> bool:
"""Placeholder for the functorch function."""
return False
class TensorDict(TensorDictBase):
"""A batched dictionary of tensors.
TensorDict is a tensor container where all tensors are stored in a
key-value pair fashion and where each element shares the same first ``N``
leading dimensions shape, where is an arbitrary number with ``N >= 0``.
Additionally, if the tensordict has a specified device, then each element
must share that device.
TensorDict instances support many regular tensor operations with the notable
exception of algebraic operations:
- operations on shape: when a shape operation is called (indexing,
reshape, view, expand, transpose, permute,
unsqueeze, squeeze, masking etc), the operations is done as if it
was executed on a tensor of the same shape as the batch size then
expended to the right, e.g.:
>>> td = TensorDict({'a': torch.zeros(3, 4, 5)}, batch_size=[3, 4])
>>> # returns a TensorDict of batch size [3, 4, 1]:
>>> td_unsqueeze = td.unsqueeze(-1)
>>> # returns a TensorDict of batch size [12]
>>> td_view = td.view(-1)
>>> # returns a tensor of batch size [12, 4]
>>> a_view = td.view(-1).get("a")
- casting operations: a TensorDict can be cast on a different device using
>>> td_cpu = td.to("cpu")
>>> dictionary = td.to_dict()
A call of the `.to()` method with a dtype will return an error.
- Cloning (:meth:`~TensorDictBase.clone`), contiguous (:meth:`~TensorDictBase.contiguous`);
- Reading: `td.get(key)`, `td.get_at(key, index)`
- Content modification: :obj:`td.set(key, value)`, :obj:`td.set_(key, value)`,
:obj:`td.update(td_or_dict)`, :obj:`td.update_(td_or_dict)`, :obj:`td.fill_(key,
value)`, :obj:`td.rename_key_(old_name, new_name)`, etc.
- Operations on multiple tensordicts: `torch.cat(tensordict_list, dim)`,
`torch.stack(tensordict_list, dim)`, `td1 == td2`, `td.apply(lambda x+y, other_td)` etc.
Args:
source (TensorDict or Dict[NestedKey, Union[Tensor, TensorDictBase]]): a
data source. If empty, the tensordict can be populated subsequently.
A ``TensorDict`` can also be built via a sequence of keyword arguments,
as it is the case for ``dict(...)``.
batch_size (iterable of int, optional): a batch size for the
tensordict. The batch size can be modified subsequently as long
as it is compatible with its content.
If not batch-size is provided, an empty batch-size is assumed (it
is not inferred automatically from the data). To automatically set
the batch-size, refer to :meth:`~.auto_batch_size_`.
device (torch.device or compatible type, optional): a device for the
TensorDict. If provided, all tensors will be stored on that device.
If not, tensors on different devices are allowed.
names (lsit of str, optional): the names of the dimensions of the
tensordict. If provided, its length must match the one of the
``batch_size``. Defaults to ``None`` (no dimension name, or ``None``
for every dimension).
non_blocking (bool, optional): if ``True`` and a device is passed, the tensordict
is delivered without synchronization. This is the fastest option but is only
safe when casting from cpu to cuda (otherwise a synchronization call must be
implemented by the user).
If ``False`` is passed, every tensor movement will be done synchronously.
If ``None`` (default), the device casting will be done asynchronously but
a synchronization will be executed after creation if required. This option
should generally be faster than ``False`` and potentially slower than ``True``.
lock (bool, optional): if ``True``, the resulting tensordict will be
locked.
Examples:
>>> import torch
>>> from tensordict import TensorDict
>>> source = {'random': torch.randn(3, 4),
... 'zeros': torch.zeros(3, 4, 5)}
>>> batch_size = [3]
>>> td = TensorDict(source, batch_size=batch_size)
>>> print(td.shape) # equivalent to td.batch_size
torch.Size([3])
>>> td_unqueeze = td.unsqueeze(-1)
>>> print(td_unqueeze.get("zeros").shape)
torch.Size([3, 1, 4, 5])
>>> print(td_unqueeze[0].shape)
torch.Size([1])
>>> print(td_unqueeze.view(-1).shape)
torch.Size([3])
>>> print((td.clone()==td).all())
True
"""
_td_dim_names = None
_is_shared = False
_is_memmap = False
_has_exclusive_keys = False
def __init__(
self,
source: T | dict[str, CompatibleType] = None,
batch_size: Sequence[int] | torch.Size | int | None = None,
device: DeviceType | None = None,
names: Sequence[str] | None = None,
non_blocking: bool = None,
lock: bool = False,
**kwargs,
) -> None:
if (source is not None) and kwargs:
raise ValueError(
"Either a dictionary or a sequence of kwargs must be provided, not both."
)
source = source if not kwargs else kwargs
self._tensordict = _StringOnlyDict()
# if names and is_dynamo_compiling():
# graph_break()
has_device = device is not None
sub_non_blocking = False
call_sync = False
if has_device:
if non_blocking is None:
sub_non_blocking = True
else:
sub_non_blocking = non_blocking
device = torch.device(device)
# Auto-index the device
if device.type not in ("cpu", "meta") and device.index is None:
device = torch.device(device.type, index=0)
if device.type == "cuda":
# CUDA does its sync by itself
call_sync = False
else:
call_sync = non_blocking is None
if call_sync:
_device_recorder.mark()
try:
self._device = device
if source is None:
source = {}
if not isinstance(source, (TensorDictBase, dict)):
raise ValueError(
"A TensorDict source is expected to be a TensorDictBase "
f"sub-type or a dictionary, found type(source)={type(source)}."
)
self._batch_size = self._parse_batch_size(source, batch_size)
# TODO: this breaks when stacking tensorclasses with dynamo
if not is_dynamo_compiling():
self.names = names
for key, value in source.items():
self.set(key, value, non_blocking=sub_non_blocking)
if call_sync:
if _device_recorder.has_transfer():
self._sync_all()
_device_recorder.unmark()
call_sync = False
if lock:
self.lock_()
finally:
if call_sync:
_device_recorder.unmark()
@classmethod
def _new_unsafe(
cls,
source: T | dict[str, CompatibleType] = None,
batch_size: Sequence[int] | torch.Size | int | None = None,
device: DeviceType | None = None,
names: Sequence[str] | None = None,
non_blocking: bool = None,
lock: bool = False,
nested: bool = True,
**kwargs,
) -> TensorDict:
if is_dynamo_compiling():
return TensorDict(
source,
batch_size=batch_size,
device=device,
names=names,
non_blocking=non_blocking,
lock=lock,
**kwargs,
)
if kwargs and not source:
source = kwargs
self = cls.__new__(cls)
sub_non_blocking = False
if device is not None:
if non_blocking is None:
sub_non_blocking = True
non_blocking = False
else:
sub_non_blocking = non_blocking
device = torch.device(device) if device is not None else None
if _has_mps:
# With MPS, an explicit sync is required
sub_non_blocking = True
self._device = device
self._tensordict = _tensordict = _StringOnlyDict()
self._batch_size = batch_size
if source: # faster than calling items
for key, value in source.items():
if nested and isinstance(value, dict):
value = TensorDict._new_unsafe(
source=value,
batch_size=self._batch_size,
device=self._device,
non_blocking=sub_non_blocking,
)
_tensordict[key] = value
# assert names is None or len(names) == self.batch_dims, (names, batch_size)
# assert (names is None) or (not all(name is None for name in names))
self._td_dim_names = names
if lock:
self.lock_()
return self
@classmethod
def from_module(
cls,
module: torch.nn.Module,
as_module: bool = False,
lock: bool = False,
use_state_dict: bool = False,
filter_empty: bool = True,
):
result = cls._from_module(
module=module,
as_module=as_module,
use_state_dict=use_state_dict,
filter_empty=filter_empty,
)
if result is None:
result = TensorDict._new_unsafe({}, batch_size=torch.Size(()))
if lock:
result.lock_()
return result
@classmethod
def _from_module(
cls,
module: torch.nn.Module,
as_module: bool = False,
use_state_dict: bool = False,
prefix="",
filter_empty: bool = True,
):
from tensordict.nn import TensorDictParams
if isinstance(module, TensorDictParams):
return module
destination = {}
if use_state_dict:
keep_vars = False
# do we need this feature atm?
local_metadata = {}
# if hasattr(destination, "_metadata"):
# destination._metadata[prefix[:-1]] = local_metadata
for hook in module._state_dict_pre_hooks.values():
hook(module, prefix, keep_vars)
module._save_to_state_dict(destination, "", keep_vars)
else:
for name, param in module._parameters.items():
if param is None:
continue
destination[name] = param
for name, buffer in module._buffers.items():
if buffer is None:
continue
destination[name] = buffer
if use_state_dict:
for hook in module._state_dict_hooks.values():
hook_result = hook(module, destination, prefix, local_metadata)
if hook_result is not None:
destination = hook_result
if not filter_empty or destination:
destination_set = True
destination = TensorDict._new_unsafe(destination, batch_size=torch.Size(()))
else:
destination_set = False
for name, submodule in module._modules.items():
if submodule is not None:
subtd = cls._from_module(
module=submodule,
as_module=False,
use_state_dict=use_state_dict,
prefix=prefix + name + ".",
filter_empty=filter_empty,
)
if subtd is not None:
if not destination_set:
destination = TensorDict._new_unsafe(batch_size=torch.Size(()))
destination_set = True
destination._set_str(
name, subtd, validated=True, inplace=False, non_blocking=False
)
if not destination_set:
return
if as_module:
from tensordict.nn.params import TensorDictParams
return TensorDictParams(destination, no_convert=True)
return destination
def is_empty(self):
for item in self._tensordict.values():
# we need to check if item is empty
if _is_tensor_collection(type(item)):
if not item.is_empty():
return False
if is_non_tensor(item):
return False
else:
return False
return True
def _to_module(
self,
module: nn.Module,
*,
inplace: bool | None = None,
return_swap: bool = True,
swap_dest=None,
memo=None,
use_state_dict: bool = False,
non_blocking: bool = False,
is_dynamo: bool | None = None,
):
if is_dynamo is None:
is_dynamo = is_dynamo_compiling()
if is_dynamo:
_check_inbuild()
if not use_state_dict and isinstance(module, TensorDictBase):
if return_swap:
swap = module.copy()
module._param_td = getattr(self, "_param_td", self)
return swap
else:
module.update(self)
return
hooks = memo["hooks"]
if return_swap:
_swap = {}
if not is_dynamo:
memo[weakref.ref(module)] = _swap
if use_state_dict:
if inplace is not None:
raise RuntimeError(
"inplace argument cannot be passed when use_state_dict=True."
)
# execute module's pre-hooks
state_dict = self.flatten_keys(".")
prefix = ""
strict = True
local_metadata = {}
missing_keys = []
unexpected_keys = []
error_msgs = []
for hook in module._load_state_dict_pre_hooks.values():
hook(
state_dict,
prefix,
local_metadata,
strict,
missing_keys,
unexpected_keys,
error_msgs,
)
def convert_type(x, y):
if isinstance(y, nn.Parameter):
return nn.Parameter(x)
if isinstance(y, Buffer):
return Buffer(x)
return x
input = state_dict.unflatten_keys(".")._fast_apply(
convert_type, self, propagate_lock=True
)
else:
input = self
inplace = bool(inplace)
# we use __dict__ directly to avoid the getattr/setattr overhead whenever we can
if not is_dynamo and type(module).__setattr__ is __base__setattr__:
# if type(module).__setattr__ is __base__setattr__:
__dict__ = module.__dict__
_parameters = __dict__["_parameters"]
_buffers = __dict__["_buffers"]
else:
__dict__ = None
for key, value in input.items():
if isinstance(value, (Tensor, ftdim.Tensor)):
# For Dynamo, we use regular set/delattr as we're not
# much afraid by overhead (and dynamo doesn't like those
# hacks we're doing).
if __dict__ is not None:
# if setattr is the native nn.Module.setattr, we can rely on _set_tensor_dict
local_out = _set_tensor_dict(
__dict__,
_parameters,
_buffers,
hooks,
module,
key,
value,
inplace,
)
else:
if not inplace:
local_out = swap_tensor(module, key, value)
else:
new_val = local_out
if return_swap:
local_out = local_out.clone()
new_val.data.copy_(value.data, non_blocking=non_blocking)
else:
if __dict__ is not None:
child = __dict__["_modules"][key]
else:
child = module._modules.get(key)
if not is_dynamo:
local_out = memo.get(weakref.ref(child), NO_DEFAULT)
if is_dynamo or local_out is NO_DEFAULT:
local_out = value._to_module(
child,
inplace=inplace,
return_swap=return_swap,
swap_dest={}, # we'll be calling update later
memo=memo,
use_state_dict=use_state_dict,
non_blocking=non_blocking,
is_dynamo=is_dynamo,
)
if return_swap:
_swap[key] = local_out
if return_swap:
if isinstance(swap_dest, dict):
return _swap
elif swap_dest is not None:
def _quick_set(swap_dict, swap_td):
for key, val in swap_dict.items():
if isinstance(val, dict):
_quick_set(val, swap_td._get_str(key, default=NO_DEFAULT))
elif swap_td._get_str(key, None) is not val:
swap_td._set_str(
key,
val,
inplace=False,
validated=True,
non_blocking=non_blocking,
)
_quick_set(_swap, swap_dest)
return swap_dest
else:
return TensorDict._new_unsafe(_swap, batch_size=[])
def __ne__(self, other: object) -> T | bool:
if _is_tensorclass(other):
return other != self
if isinstance(other, (dict,)):
other = self.from_dict_instance(other)
if _is_tensor_collection(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 = {}
for key, item1 in self.items():
d[key] = item1 != other.get(key)
return TensorDict(batch_size=self.batch_size, source=d, device=self.device)
if isinstance(other, (numbers.Number, Tensor)):
return TensorDict(
{key: value != other for key, value in self.items()},
self.batch_size,
device=self.device,
)
return True
def __xor__(self, other: object) -> T | bool:
if _is_tensorclass(other):
return other ^ self
if isinstance(other, (dict,)):
other = self.from_dict_instance(other)
if _is_tensor_collection(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 = {}
for key, item1 in self.items():
d[key] = item1 ^ other.get(key)
return TensorDict(batch_size=self.batch_size, source=d, device=self.device)
if isinstance(other, (numbers.Number, Tensor)):
return TensorDict(
{key: value ^ other for key, value in self.items()},
self.batch_size,
device=self.device,
)
return True
def __or__(self, other: object) -> T | bool:
if _is_tensorclass(other):
return other | self
if isinstance(other, (dict,)):
other = self.from_dict_instance(other)
if _is_tensor_collection(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 = {}
for key, item1 in self.items():
d[key] = item1 | other.get(key)
return TensorDict(batch_size=self.batch_size, source=d, device=self.device)
if isinstance(other, (numbers.Number, Tensor)):
return TensorDict(
{key: value | other for key, value in self.items()},
self.batch_size,
device=self.device,
)
return False
def __eq__(self, other: object) -> T | bool:
if is_tensorclass(other):
return other == self
if isinstance(other, (dict,)):
other = self.from_dict_instance(other)
if _is_tensor_collection(type(other)):
keys1 = set(self.keys())
keys2 = set(other.keys())
if len(keys1.difference(keys2)) or len(keys1) != len(keys2):
keys1 = sorted(
keys1,
key=lambda key: "".join(key) if isinstance(key, tuple) else key,
)
keys2 = sorted(
keys2,
key=lambda key: "".join(key) if isinstance(key, tuple) else key,
)
raise KeyError(f"keys in tensordicts mismatch, got {keys1} and {keys2}")
d = {}
for key, item1 in self.items():
d[key] = item1 == other.get(key)
return TensorDict(source=d, batch_size=self.batch_size, device=self.device)
if isinstance(other, (numbers.Number, Tensor)):
return TensorDict(
{key: value == other for key, value in self.items()},
self.batch_size,
device=self.device,
)
return False
def __ge__(self, other: object) -> T | bool:
if is_tensorclass(other):
return other <= self
if isinstance(other, (dict,)):
other = self.from_dict_instance(other)
if _is_tensor_collection(type(other)):
keys1 = set(self.keys())
keys2 = set(other.keys())
if len(keys1.difference(keys2)) or len(keys1) != len(keys2):
keys1 = sorted(
keys1,
key=lambda key: "".join(key) if isinstance(key, tuple) else key,
)
keys2 = sorted(
keys2,
key=lambda key: "".join(key) if isinstance(key, tuple) else key,
)
raise KeyError(f"keys in tensordicts mismatch, got {keys1} and {keys2}")
d = {}
for key, item1 in self.items():
d[key] = item1 >= other.get(key)
return TensorDict(source=d, batch_size=self.batch_size, device=self.device)
if isinstance(other, (numbers.Number, Tensor)):
return TensorDict(
{key: value >= other for key, value in self.items()},
self.batch_size,
device=self.device,
)
return False
def __gt__(self, other: object) -> T | bool:
if is_tensorclass(other):
return other < self
if isinstance(other, (dict,)):
other = self.from_dict_instance(other)
if _is_tensor_collection(type(other)):
keys1 = set(self.keys())
keys2 = set(other.keys())
if len(keys1.difference(keys2)) or len(keys1) != len(keys2):
keys1 = sorted(
keys1,
key=lambda key: "".join(key) if isinstance(key, tuple) else key,
)
keys2 = sorted(
keys2,
key=lambda key: "".join(key) if isinstance(key, tuple) else key,
)
raise KeyError(f"keys in tensordicts mismatch, got {keys1} and {keys2}")
d = {}
for key, item1 in self.items():
d[key] = item1 > other.get(key)
return TensorDict(source=d, batch_size=self.batch_size, device=self.device)
if isinstance(other, (numbers.Number, Tensor)):
return TensorDict(
{key: value > other for key, value in self.items()},
self.batch_size,
device=self.device,
)
return False
def __le__(self, other: object) -> T | bool:
if is_tensorclass(other):
return other >= self
if isinstance(other, (dict,)):
other = self.from_dict_instance(other)
if _is_tensor_collection(type(other)):
keys1 = set(self.keys())
keys2 = set(other.keys())
if len(keys1.difference(keys2)) or len(keys1) != len(keys2):
keys1 = sorted(
keys1,
key=lambda key: "".join(key) if isinstance(key, tuple) else key,
)
keys2 = sorted(
keys2,
key=lambda key: "".join(key) if isinstance(key, tuple) else key,
)
raise KeyError(f"keys in tensordicts mismatch, got {keys1} and {keys2}")
d = {}
for key, item1 in self.items():
d[key] = item1 <= other.get(key)
return TensorDict(source=d, batch_size=self.batch_size, device=self.device)
if isinstance(other, (numbers.Number, Tensor)):
return TensorDict(
{key: value <= other for key, value in self.items()},
self.batch_size,
device=self.device,
)
return False
def __lt__(self, other: object) -> T | bool:
if is_tensorclass(other):
return other > self
if isinstance(other, (dict,)):
other = self.from_dict_instance(other)
if _is_tensor_collection(type(other)):
keys1 = set(self.keys())
keys2 = set(other.keys())
if len(keys1.difference(keys2)) or len(keys1) != len(keys2):
keys1 = sorted(
keys1,
key=lambda key: "".join(key) if isinstance(key, tuple) else key,
)
keys2 = sorted(
keys2,
key=lambda key: "".join(key) if isinstance(key, tuple) else key,
)
raise KeyError(f"keys in tensordicts mismatch, got {keys1} and {keys2}")
d = {}
for key, item1 in self.items():
d[key] = item1 < other.get(key)
return TensorDict(source=d, batch_size=self.batch_size, device=self.device)
if isinstance(other, (numbers.Number, Tensor)):
return TensorDict(
{key: value < other for key, value in self.items()},
self.batch_size,
device=self.device,
)
return False
def __setitem__(
self,
index: IndexType,
value: Any,
) -> None:
istuple = isinstance(index, tuple)
if istuple or isinstance(index, str):
# try:
index_unravel = _unravel_key_to_tuple(index)
if index_unravel:
self._set_tuple(
index_unravel,
value,
inplace=(
BEST_ATTEMPT_INPLACE
if isinstance(self, _SubTensorDict)
else False
),
validated=False,
non_blocking=False,
)
return
# we must use any and because using Ellipsis in index can break with some indices
if index is Ellipsis or (
isinstance(index, tuple) and any(idx is Ellipsis for idx in index)
):
index = convert_ellipsis_to_idx(index, self.batch_size)
if isinstance(value, (TensorDictBase, dict)):
indexed_bs = _getitem_batch_size(self.batch_size, index)
if isinstance(value, dict):
value = self.from_dict_instance(
value, batch_size=indexed_bs, device=self.device
)
elif value.device != self.device:
value = value.to(self.device)
# value = self.empty(recurse=True)[index].update(value)
if value.batch_size != indexed_bs:
if value.shape == indexed_bs[-len(value.shape) :]:
# try to expand on the left (broadcasting)
value = value.expand(indexed_bs)
else:
try:
# copy and change batch_size if can't be expanded
value = value.copy()
value.batch_size = indexed_bs
except RuntimeError as err:
raise RuntimeError(
f"indexed destination TensorDict batch size is {indexed_bs} "
f"(batch_size = {self.batch_size}, index={index}), "
f"which differs from the source batch size {value.batch_size}"
) from err
keys = set(self.keys())
subtd = None
for value_key, item in value.items():
if value_key in keys:
self._set_at_str(
value_key, item, index, validated=True, non_blocking=False
)
else:
if subtd is None:
subtd = self._get_sub_tensordict(index)
subtd.set(value_key, item, inplace=True, non_blocking=False)
else:
for key in self.keys():
self.set_at_(key, value, index)
def all(self, dim: int = None) -> bool | TensorDictBase:
if dim is not None and (dim >= self.batch_dims or dim < -self.batch_dims):
raise RuntimeError(
"dim must be greater than or equal to -tensordict.batch_dims and "
"smaller than tensordict.batch_dims"
)
if dim is not None:
if dim < 0:
dim = self.batch_dims + dim
names = None
if self._has_names():
names = copy(self.names)
names = [name for i, name in enumerate(names) if i != dim]
return TensorDict(
source={key: value.all(dim=dim) for key, value in self.items()},
batch_size=[b for i, b in enumerate(self.batch_size) if i != dim],
device=self.device,
names=names,
)
return all(value.all() for value in self.values())
def any(self, dim: int = None) -> bool | TensorDictBase:
if dim is not None and (dim >= self.batch_dims or dim < -self.batch_dims):
raise RuntimeError(
"dim must be greater than or equal to -tensordict.batch_dims and "
"smaller than tensordict.batch_dims"
)
if dim is not None:
if dim < 0:
dim = self.batch_dims + dim
names = None
if self._has_names():
names = copy(self.names)
names = [name for i, name in enumerate(names) if i != dim]
return TensorDict(
source={key: value.any(dim=dim) for key, value in self.items()},
batch_size=[b for i, b in enumerate(self.batch_size) if i != dim],
device=self.device,
names=names,
)
return any([value.any() for value in self.values()])
def _cast_reduction(
self,
*,
reduction_name,
dim=NO_DEFAULT,
keepdim=NO_DEFAULT,
tuple_ok=True,
further_reduce: bool,
**kwargs,
):
if further_reduce:
# It is not very memory-efficient to do this, but it's the easiest to cover all use cases
if dim is NO_DEFAULT:
agglomerate = [
val.contiguous().flatten()
for val in self._values_list(
True, True, is_leaf=_NESTED_TENSORS_AS_LISTS
)
]
agglomerate = torch.cat(agglomerate, dim=0)
return getattr(torch, reduction_name)(agglomerate)
else:
agglomerate = list(
self._values_list(True, True, is_leaf=_NESTED_TENSORS_AS_LISTS)
)
agglomerate = torch.cat(agglomerate, dim=0)
return getattr(torch, reduction_name)(
agglomerate, keepdim=keepdim, dim=dim
)
def proc_dim(dim, tuple_ok=True):
if dim is None:
return dim
if isinstance(dim, tuple):
if tuple_ok:
return tuple(_d for d in dim for _d in proc_dim(d, tuple_ok=False))
return dim
if dim >= self.batch_dims or dim < -self.batch_dims:
raise RuntimeError(
"dim must be greater than or equal to -tensordict.batch_dims and "
"smaller than tensordict.batch_dims"
)
if dim < 0:
return (self.batch_dims + dim,)
return (dim,)
if dim is not NO_DEFAULT:
dim = proc_dim(dim, tuple_ok=tuple_ok)
if not tuple_ok:
dim = dim[0]