-
Notifications
You must be signed in to change notification settings - Fork 3
/
MoveDataMixin.py
401 lines (339 loc) · 14.7 KB
/
MoveDataMixin.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
"""MoveDataMixin."""
import dataclasses
from collections.abc import Iterator
from copy import copy as shallowcopy
from copy import deepcopy
from typing import ClassVar, TypeAlias
import torch
from typing_extensions import Any, Protocol, Self, overload, runtime_checkable
class InconsistentDeviceError(ValueError): # noqa: D101
def __init__(self, *devices): # noqa: D107
super().__init__(f'Inconsistent devices found, found at least {", ".join(str(d) for d in devices)}')
@runtime_checkable
class DataclassInstance(Protocol):
"""An instance of a dataclass."""
__dataclass_fields__: ClassVar[dict[str, dataclasses.Field[Any]]]
class MoveDataMixin:
"""Move dataclass fields to cpu/gpu and convert dtypes."""
@overload
def to(
self,
device: str | torch.device | int | None = None,
dtype: torch.dtype | None = None,
non_blocking: bool = False,
*,
copy: bool = False,
memory_format: torch.memory_format | None = None,
) -> Self: ...
@overload
def to(
self,
dtype: torch.dtype,
non_blocking: bool = False,
*,
copy: bool = False,
memory_format: torch.memory_format | None = None,
) -> Self: ...
@overload
def to(
self,
tensor: torch.Tensor,
non_blocking: bool = False,
*,
copy: bool = False,
memory_format: torch.memory_format | None = None,
) -> Self: ...
def to(self, *args, **kwargs) -> Self:
"""Perform dtype and/or device conversion of data.
A torch.dtype and torch.device are inferred from the arguments
args and kwargs. Please have a look at the
documentation of torch.Tensor.to() for more details.
A new instance of the dataclass will be returned.
The conversion will be applied to all Tensor- or Module
fields of the dataclass, and to all fields that implement
the MoveDataMixin.
The dtype-type, i.e. float or complex will always be preserved,
but the precision of floating point dtypes might be changed.
Example:
If called with dtype=torch.float32 OR dtype=torch.complex64:
- A complex128 tensor will be converted to complex64
- A float64 tensor will be converted to float32
- A bool tensor will remain bool
- An int64 tensor will remain int64
If other conversions are desired, please use the torch.Tensor.to() method of
the fields directly.
If the copy argument is set to True (default), a deep copy will be returned
even if no conversion is necessary.
If two fields are views of the same data before, in the result they will be independent
copies if copy is set to True or a conversion is necessary.
If set to False, some Tensors might be shared between the original and the new object.
"""
# Parse the arguments of the three overloads and call _to with the parsed arguments
parsedType: TypeAlias = tuple[
str | torch.device | int | None, torch.dtype | None, bool, bool, torch.memory_format
]
def parse3(
other: torch.Tensor,
non_blocking: bool = False,
copy: bool = False,
) -> parsedType:
return other.device, other.dtype, non_blocking, copy, torch.preserve_format
def parse2(
dtype: torch.dtype,
non_blocking: bool = False,
copy: bool = False,
memory_format: torch.memory_format = torch.preserve_format,
) -> parsedType:
return None, dtype, non_blocking, copy, memory_format
def parse1(
device: str | torch.device | int | None = None,
dtype: None | torch.dtype = None,
non_blocking: bool = False,
copy: bool = False,
memory_format: torch.memory_format = torch.preserve_format,
) -> parsedType:
return device, dtype, non_blocking, copy, memory_format
if args and isinstance(args[0], torch.Tensor) or 'tensor' in kwargs:
# overload 3 ("tensor" specifies the dtype and device)
device, dtype, non_blocking, copy, memory_format = parse3(*args, **kwargs)
elif args and isinstance(args[0], torch.dtype):
# overload 2 (no device specified, only dtype)
device, dtype, non_blocking, copy, memory_format = parse2(*args, **kwargs)
else:
# overload 1 (device and dtype specified)
device, dtype, non_blocking, copy, memory_format = parse1(*args, **kwargs)
return self._to(device=device, dtype=dtype, non_blocking=non_blocking, memory_format=memory_format, copy=copy)
def _items(self) -> Iterator[tuple[str, Any]]:
"""Return an iterator over fields, parameters, buffers, and modules of the object."""
if isinstance(self, DataclassInstance):
for field in dataclasses.fields(self):
name = field.name
data = getattr(self, name)
yield name, data
if isinstance(self, torch.nn.Module):
yield from self._parameters.items()
yield from self._buffers.items()
yield from self._modules.items()
def _to(
self,
device: torch.device | str | int | None = None,
dtype: torch.dtype | None = None,
non_blocking: bool = False,
memory_format: torch.memory_format = torch.preserve_format,
shared_memory: bool = False,
copy: bool = False,
memo: dict | None = None,
) -> Self:
new = shallowcopy(self) if copy or not isinstance(self, torch.nn.Module) else self
"""Move data to device and convert dtype if necessary.
This method is called by .to(), .cuda(), .cpu(), .double(), and so on.
It should not be called directly.
See .to() for more details.
Parameters
----------
device
The destination device.
dtype
The destination dtype.
non_blocking
If True and the source is in pinned memory, the copy will be asynchronous with respect to the host.
Otherwise, the argument has no effect.
memory_format
The desired memory format of returned tensor.
shared_memory
If True and the target device is CPU, the tensors will reside in shared memory.
Otherwise, the argument has no effect.
copy
If True, the returned tensor will always be a copy, even if the input was already on the correct device.
This will also create new tensors for views
memo
A dictionary to keep track of already converted objects to avoid multiple conversions.
"""
if memo is None:
memo = {}
def _tensor_to(data: torch.Tensor) -> torch.Tensor:
"""Move tensor to device and convert dtype if necessary."""
new_dtype: torch.dtype | None
if dtype is not None and data.dtype.is_floating_point:
new_dtype = dtype.to_real()
elif dtype is not None and data.dtype.is_complex:
new_dtype = dtype.to_complex()
else:
# bool or int: keep as is
new_dtype = None
data = data.to(
device,
new_dtype,
non_blocking=non_blocking,
memory_format=memory_format,
copy=copy,
)
if shared_memory:
data.share_memory_()
return data
def _module_to(data: torch.nn.Module) -> torch.nn.Module:
if copy:
data = deepcopy(data)
return data._apply(_tensor_to, recurse=True)
def _mixin_to(obj: MoveDataMixin) -> MoveDataMixin:
return obj._to(
device=device,
dtype=dtype,
non_blocking=non_blocking,
memory_format=memory_format,
shared_memory=shared_memory,
copy=copy,
memo=memo,
)
converted: Any
for name, data in new._items():
if id(data) in memo:
object.__setattr__(new, name, memo[id(data)])
continue
if isinstance(data, torch.Tensor):
converted = _tensor_to(data)
elif isinstance(data, MoveDataMixin):
converted = _mixin_to(data)
elif isinstance(data, torch.nn.Module):
converted = _module_to(data)
elif copy:
converted = deepcopy(data)
else:
converted = data
memo[id(data)] = converted
# this works even if new is frozen
object.__setattr__(new, name, converted)
return new
def cuda(
self,
device: torch.device | str | int | None = None,
*,
non_blocking: bool = False,
memory_format: torch.memory_format = torch.preserve_format,
copy: bool = False,
) -> Self:
"""Put object in CUDA memory.
Parameters
----------
device
The destination GPU device. Defaults to the current CUDA device.
non_blocking
If True and the source is in pinned memory, the copy will be asynchronous with respect to the host.
Otherwise, the argument has no effect.
memory_format
The desired memory format of returned tensor.
copy:
If True, the returned tensor will always be a copy, even if the input was already on the correct device.
This will also create new tensors for views
"""
if device is None:
device = torch.device(torch.cuda.current_device())
return self._to(device=device, dtype=None, memory_format=memory_format, non_blocking=non_blocking, copy=copy)
def cpu(self, *, memory_format: torch.memory_format = torch.preserve_format, copy: bool = False) -> Self:
"""Put in CPU memory.
Parameters
----------
memory_format
The desired memory format of returned tensor.
copy
If True, the returned tensor will always be a copy, even if the input was already on the correct device.
This will also create new tensors for views
"""
return self._to(device='cpu', dtype=None, non_blocking=True, memory_format=memory_format, copy=copy)
def double(self, *, memory_format: torch.memory_format = torch.preserve_format, copy: bool = False) -> Self:
"""Convert all float tensors to double precision.
converts float to float64 and complex to complex128
Parameters
----------
memory_format
The desired memory format of returned tensor.
copy
If True, the returned tensor will always be a copy, even if the input was already on the correct device.
This will also create new tensors for views
"""
return self._to(dtype=torch.float64, memory_format=memory_format, copy=copy)
def half(self, *, memory_format: torch.memory_format = torch.preserve_format, copy: bool = False) -> Self:
"""Convert all float tensors to half precision.
converts float to float16 and complex to complex32
Parameters
----------
memory_format
The desired memory format of returned tensor.
copy
If True, the returned tensor will always be a copy, even if the input was already on the correct device.
This will also create new tensors for views
"""
return self._to(dtype=torch.float16, memory_format=memory_format, copy=copy)
def single(self, *, memory_format: torch.memory_format = torch.preserve_format, copy: bool = False) -> Self:
"""Convert all float tensors to single precision.
converts float to float32 and complex to complex64
Parameters
----------
memory_format
The desired memory format of returned tensor.
copy
If True, the returned tensor will always be a copy, even if the input was already on the correct device.
This will also create new tensors for views
"""
return self._to(dtype=torch.float32, memory_format=memory_format, copy=copy)
@property
def device(self) -> torch.device | None:
"""Return the device of the tensors.
Looks at each field of a dataclass implementing a device attribute,
such as torch.Tensors or MoveDataMixin instances. If the devices
of the fields differ, an InconsistentDeviceError is raised, otherwise
the device is returned. If no field implements a device attribute,
None is returned.
Raises
------
InconsistentDeviceError:
If the devices of different fields differ.
Returns
-------
The device of the fields or None if no field implements a device attribute.
"""
device: None | torch.device = None
for _, data in self._items():
if not hasattr(data, 'device'):
continue
current_device = getattr(data, 'device', None)
if current_device is None:
continue
if device is None:
device = current_device
elif device != current_device:
raise InconsistentDeviceError(current_device, device)
return device
def clone(self: Self) -> Self:
"""Return a deep copy of the object."""
return self._to(device=None, dtype=None, non_blocking=False, memory_format=torch.preserve_format, copy=True)
@property
def is_cuda(self) -> bool:
"""Return True if all tensors are on a single CUDA device.
Checks all tensor attributes of the dataclass for their device,
(recursively if an attribute is a MoveDataMixin)
Returns False if not all tensors are on the same CUDA devices, or if the device is inconsistent,
returns True if the data class has no tensors as attributes.
"""
try:
device = self.device
except InconsistentDeviceError:
return False
if device is None:
return True
return device.type == 'cuda'
@property
def is_cpu(self) -> bool:
"""Return True if all tensors are on the CPU.
Checks all tensor attributes of the dataclass for their device,
(recursively if an attribute is a MoveDataMixin)
Returns False if not all tensors are on cpu or if the device is inconsistent,
returns True if the data class has no tensors as attributes.
"""
try:
device = self.device
except InconsistentDeviceError:
return False
if device is None:
return True
return device.type == 'cpu'