reductions.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. # mypy: allow-untyped-defs
  2. import multiprocessing
  3. import os
  4. import threading
  5. from multiprocessing import reduction
  6. from multiprocessing.util import register_after_fork
  7. import torch
  8. from torch._namedtensor_internals import check_serializing_named_tensor
  9. try:
  10. # Early load resource_sharer to prevent a partially initialized instance
  11. # from being inherited in a forked child process. The reduce_storage method
  12. # requires this module indirectly through DupFd(). The built-in mp.Queue
  13. # class pickles arguments in a background thread which may overlap with the
  14. # fork.
  15. import multiprocessing.resource_sharer
  16. except ImportError:
  17. pass
  18. class StorageWeakRef:
  19. r"""A weak reference to a Storage.
  20. The cdata member is a Python number containing the integer representation of
  21. the Storage pointer.
  22. """
  23. __slots__ = ["cdata", "_free_weak_ref"]
  24. def __init__(self, storage):
  25. self.cdata = storage._weak_ref()
  26. # Save a direct reference to _free_weak_ref because the `torch` module
  27. # might be cleared during Python shutdown before this module is cleared.
  28. self._free_weak_ref = torch.Storage._free_weak_ref # type: ignore[attr-defined]
  29. @classmethod
  30. def from_weakref(cls, cdata):
  31. instance = cls.__new__(cls)
  32. instance.cdata = cdata
  33. instance._free_weak_ref = torch.Storage._free_weak_ref # type: ignore[attr-defined]
  34. return instance
  35. def expired(self):
  36. return torch.Storage._expired(self.cdata) # type: ignore[attr-defined]
  37. def __del__(self):
  38. self._free_weak_ref(self.cdata)
  39. def __hash__(self):
  40. return self.cdata
  41. def __eq__(self, other):
  42. if id(self) == id(other):
  43. return True
  44. return self.cdata == other.cdata
  45. class SharedCache(dict):
  46. """Dictionary from multiprocessing handles to StorageWeakRef."""
  47. def __init__(self) -> None:
  48. # free_dead_references() is called if the len exceeds the current
  49. # limit. The limit scales with the number of remaining live objects.
  50. self.limit = 128
  51. # `fork` inherits lock state, so in case we fork when the lock is held,
  52. # we register a function to reset the lock to a new object to avoid
  53. # possible deadlocks, following python multiprocessing library design.
  54. self._after_fork()
  55. register_after_fork(self, SharedCache._after_fork)
  56. def _after_fork(self):
  57. self.lock = threading.Lock()
  58. def get(self, key): # type: ignore[override]
  59. with self.lock:
  60. return dict.get(self, key)
  61. def __setitem__(self, key, storage_ref):
  62. with self.lock:
  63. dict.__setitem__(self, key, storage_ref)
  64. if len(self) > self.limit:
  65. self.free_dead_references()
  66. def free_dead_references(self):
  67. live = 0
  68. for key, storage_ref in list(self.items()):
  69. if storage_ref.expired():
  70. del self[key]
  71. else:
  72. live += 1
  73. self.limit = max(128, live * 2)
  74. # mapping from handles to StorageWeakRef objects
  75. shared_cache = SharedCache()
  76. def rebuild_event(device, handle):
  77. return torch.cuda.Event.from_ipc_handle(device, handle)
  78. def reduce_event(event):
  79. handle = event.ipc_handle()
  80. return (rebuild_event, (event.device, handle))
  81. def rebuild_tensor(cls, storage, metadata):
  82. storage_offset, size, stride, requires_grad = metadata
  83. t = torch._utils._rebuild_tensor(storage, storage_offset, size, stride)
  84. if cls == torch.nn.parameter.Parameter:
  85. # we have to pass requires_grad into constructor, rather than set it as an
  86. # attribute later, because it's an important check for Integer Tensors to
  87. # have requires_grad=False (or else they raise an error)
  88. t = torch.nn.parameter.Parameter(t, requires_grad=requires_grad)
  89. else:
  90. t.requires_grad = requires_grad
  91. return t
  92. def rebuild_meta_tensor(
  93. tensor_cls,
  94. tensor_size,
  95. tensor_stride,
  96. tensor_offset,
  97. dtype,
  98. storage_size_bytes,
  99. requires_grad,
  100. ):
  101. untyped_storage = torch.UntypedStorage(storage_size_bytes, device="meta")
  102. typed_storage = torch.TypedStorage(
  103. wrap_storage=untyped_storage, dtype=dtype, _internal=True
  104. )
  105. t = torch._utils._rebuild_tensor(
  106. typed_storage,
  107. tensor_offset,
  108. tensor_size,
  109. tensor_stride,
  110. )
  111. if tensor_cls == torch.nn.parameter.Parameter:
  112. # It is crucial for integer tensors to receive
  113. # the requires_grad=False as an argument in the constructor
  114. t = torch.nn.parameter.Parameter(t, requires_grad=requires_grad)
  115. else:
  116. t.requires_grad = requires_grad
  117. return t
  118. def rebuild_cuda_tensor(
  119. tensor_cls,
  120. tensor_size,
  121. tensor_stride,
  122. tensor_offset,
  123. storage_cls,
  124. dtype,
  125. storage_device,
  126. storage_handle,
  127. storage_size_bytes,
  128. storage_offset_bytes,
  129. requires_grad,
  130. ref_counter_handle,
  131. ref_counter_offset,
  132. event_handle,
  133. event_sync_required,
  134. ):
  135. # If storage_handle is None, storage points to nullptr.
  136. if storage_handle is None or storage_size_bytes == 0:
  137. storage = storage_cls(0, dtype=dtype, device=storage_device, _internal=True)
  138. else:
  139. storage = storage_from_cache(
  140. storage_cls, (storage_handle, storage_offset_bytes)
  141. )
  142. if storage is None:
  143. torch.cuda._lazy_init()
  144. storage = storage_cls._new_shared_cuda(
  145. storage_device,
  146. storage_handle,
  147. storage_size_bytes,
  148. storage_offset_bytes,
  149. ref_counter_handle,
  150. ref_counter_offset,
  151. event_handle,
  152. event_sync_required,
  153. )
  154. shared_cache[(storage_handle, storage_offset_bytes)] = StorageWeakRef(
  155. storage
  156. )
  157. else:
  158. # We already ref counting this Storage, but producer needs new ref-counters to be released.
  159. storage_cls._release_ipc_counter(
  160. ref_counter_handle, ref_counter_offset, device=storage_device
  161. )
  162. _storage = (
  163. storage
  164. if isinstance(storage, torch.UntypedStorage)
  165. else storage._untyped_storage
  166. )
  167. t = torch._utils._rebuild_tensor(
  168. torch.storage.TypedStorage(wrap_storage=_storage, dtype=dtype, _internal=True),
  169. tensor_offset,
  170. tensor_size,
  171. tensor_stride,
  172. )
  173. if tensor_cls == torch.nn.parameter.Parameter:
  174. # It is crucial for integer tensors to receive
  175. # the requires_grad=False as an argument in the constructor
  176. t = torch.nn.parameter.Parameter(t, requires_grad=requires_grad)
  177. else:
  178. t.requires_grad = requires_grad
  179. return t
  180. def reduce_tensor(tensor):
  181. if tensor.requires_grad and not tensor.is_leaf:
  182. raise RuntimeError(
  183. "Cowardly refusing to serialize non-leaf tensor which requires_grad, "
  184. "since autograd does not support crossing process boundaries. "
  185. "If you just want to transfer the data, call detach() on the tensor "
  186. "before serializing (e.g., putting it on the queue)."
  187. )
  188. check_serializing_named_tensor(tensor)
  189. torch.utils.hooks.warn_if_has_hooks(tensor)
  190. # Note [CUDA IPC and the caching allocator]
  191. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  192. # When you send a CUDA tensor over IPC, you might expect that you will
  193. # get out the same storage from the other end. However, the CUDA caching
  194. # allocator makes it difficult to preserve this invariant. Consider
  195. # the following situation: a tensor of size 0x100 points to offset 0x20 of
  196. # a storage at 0xA100 of size 0x100. (For simplicity, all of these
  197. # sizes are given in bytes). HOWEVER, with the caching allocator, this storage
  198. # might be part of a larger cudaMalloc allocation 0xA000 of size 0x4000.
  199. #
  200. # When we want to send this CUDA tensor over IPC, we must send the
  201. # *entire* cudaMalloc allocation, i.e., the 0xA000 region, not just
  202. # the storage 0xA100 (because that is what CUDA supports). So, on the
  203. # other end, there simply isn't any way to say, "Wait, you gave me
  204. # a bigger region (0xA000) than the one I wanted (0xA100)".
  205. #
  206. # OK, so if you sent the cudaMalloc allocation, can you just wrap that up as
  207. # one storage itself? No, because this cudaMalloc allocation might contain
  208. # storages of mixed types: float, bytes, double... If you make the entire
  209. # allocation a single storage of a type A, we'll hit an error when constructing
  210. # a tensor of type B on the storage.
  211. #
  212. # cudaIpcMemHandle is an identifier to access the sender cudaMalloc allocation on the
  213. # receiver side. However, cudaIpcMemHandles from each device in a given process may
  214. # only be opened by one context per device per other process.
  215. # If we open and close a memory handle multiples times in a process, CUDA is allowed
  216. # to give it a different address; similarly, once we close the memory, we're not
  217. # allowed to access it(and the storage/tensor built on top of it), even if it is
  218. # still live in the original process. As we cannot make a cudaMalloc allocation
  219. # to a single storage in one go, this requires us to cache the device pointer for
  220. # each cudaIpcMemHandle on C++ side to reconstruct types of storages, while keep
  221. # the old ones alives.
  222. # See [https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__DEVICE.html]
  223. #
  224. # This is fine, because all we need to do is to save our position in the allocation,
  225. # and reconstruct storage and tensor from it.
  226. # 0xA000 -> -------CUDA Allocation------
  227. # | |
  228. # | |
  229. # | |
  230. # | |
  231. # 0xA100 -> --------storage1 begin------
  232. # | |
  233. # 0xA120 -> --------tensor1 begin ------
  234. # | |
  235. # | |
  236. # | |
  237. # | |
  238. # | |
  239. # 0xA160 -> --------tensor1 end---------
  240. # | |
  241. # | |
  242. # | |
  243. # 0xA200 -> --------storage1 end--------
  244. # | |
  245. # 0xE000 -> --------CUDA allocation-----
  246. #
  247. # To send tensor1, the following info are required from sender to receiver for
  248. # storage reconstruction.
  249. # 1. cudaIpcMemHandle of 0xA000(which can be mapped to a basePtr in receiver process).
  250. # basePtr may not be exactly 0xA000 since it's a different process.
  251. # 2. offset(0xA100) of storage1 in the CUDA allocation.
  252. # 3. size of storage1(0x100).
  253. #
  254. # On receiver side:
  255. # 1. Get the devPtr of the MemHandle to access the memory, reconstruct a storage
  256. # of the same type using (basePtr, offset, size).
  257. # 2. we can reconstruct the tensor on top of the reconstructed storage
  258. # Tensor(size=0x040, offset=0x020, storage=Storage(data=basePtr+0xA100, size=0x0100))
  259. #
  260. # This strategy has a few implications:
  261. #
  262. # 1. When we serialize a CUDA tensor for IPC, we cannot do it all in one
  263. # go (non-compositionally), and this requires to have a global map
  264. # memHandle -> devPtr for each process.
  265. #
  266. # 2. We MUST NOT let the new IPC tensor be resizable. Originally, a resize
  267. # of the storage beyond 0x100 would merely have caused us to do a
  268. # reallocation. You don't really want to do this, but if you did,
  269. # all that would happen is that you would lose IPC sharing. But if
  270. # you do this in the new world, we will happily let you write out of
  271. # bounds of your "allocation", clobbering unrelated data in the cached
  272. # allocator block. BAD!
  273. #
  274. # By the way, in old versions of PyTorch, we supported this situation
  275. # natively using a "storage view", which permitted multiple storages to be
  276. # views on each other. But this was the *only* use of storage views, so we
  277. # eliminated it so that we could just use tensor views to implement the same
  278. # thing.
  279. #
  280. # TODO: Handle distinguishing between subclass and non-subclass versions of NT better
  281. # https://github.com/pytorch/pytorch/issues/110543
  282. from torch.nested._internal.nested_tensor import NestedTensor
  283. if tensor.is_nested and not isinstance(tensor, NestedTensor):
  284. return reduce_nested_tensor(tensor)
  285. if tensor.layout in {
  286. torch.sparse_coo,
  287. torch.sparse_csr,
  288. torch.sparse_bsr,
  289. torch.sparse_csc,
  290. torch.sparse_bsc,
  291. }:
  292. return reduce_sparse_tensor(tensor)
  293. storage = tensor._typed_storage()
  294. if storage._untyped_storage.device.type == "cuda":
  295. (
  296. device,
  297. handle,
  298. storage_size_bytes,
  299. storage_offset_bytes,
  300. ref_counter_handle,
  301. ref_counter_offset,
  302. event_handle,
  303. event_sync_required,
  304. ) = storage._share_cuda_()
  305. tensor_offset = tensor.storage_offset()
  306. shared_cache[handle] = StorageWeakRef(storage)
  307. # _backward_hooks purposely omitted here, see
  308. # Note [Don't serialize hooks]
  309. return (
  310. rebuild_cuda_tensor,
  311. (
  312. type(tensor),
  313. tensor.size(),
  314. tensor.stride(),
  315. tensor_offset, # tensor offset in its storage
  316. type(storage),
  317. tensor.dtype,
  318. device,
  319. handle, # identifier which CUDA allocation is the storage in.
  320. storage_size_bytes, # size(in bytes) of the storage
  321. storage_offset_bytes, # offset(in bytes) of the storage in the CUDA allocation
  322. tensor.requires_grad,
  323. ref_counter_handle,
  324. ref_counter_offset,
  325. event_handle,
  326. event_sync_required,
  327. ),
  328. )
  329. elif storage._untyped_storage.device.type == "meta":
  330. return (
  331. rebuild_meta_tensor,
  332. (
  333. type(tensor),
  334. tensor.size(),
  335. tensor.stride(),
  336. tensor.storage_offset(),
  337. tensor.dtype,
  338. tensor.untyped_storage().size(),
  339. tensor.requires_grad,
  340. ),
  341. )
  342. # _backward_hooks purposely omitted here, see Note [Don't serialize hooks]
  343. metadata = (
  344. tensor.storage_offset(),
  345. tensor.size(),
  346. tensor.stride(),
  347. tensor.requires_grad,
  348. )
  349. return (rebuild_tensor, (type(tensor), storage, metadata))
  350. def rebuild_nested_tensor(
  351. rebuild_buffer_func,
  352. rebuild_buffer_args,
  353. rebuild_sizes_func,
  354. rebuild_sizes_args,
  355. rebuild_strides_func,
  356. rebuild_strides_args,
  357. rebuild_offsets_func,
  358. rebuild_offsets_args,
  359. ):
  360. buffer = rebuild_buffer_func(*rebuild_buffer_args)
  361. sizes = rebuild_sizes_func(*rebuild_sizes_args)
  362. strides = rebuild_strides_func(*rebuild_strides_args)
  363. offsets = rebuild_offsets_func(*rebuild_offsets_args)
  364. return torch._nested_view_from_buffer_copy(buffer, sizes, strides, offsets)
  365. def reduce_nested_tensor(nt):
  366. rebuild_buffer_func, rebuild_buffer_args = reduce_tensor(nt.values())
  367. rebuild_sizes_func, rebuild_sizes_args = reduce_tensor(nt._nested_tensor_size())
  368. rebuild_strides_func, rebuild_strides_args = reduce_tensor(
  369. nt._nested_tensor_strides()
  370. )
  371. rebuild_offsets_func, rebuild_offsets_args = reduce_tensor(
  372. nt._nested_tensor_storage_offsets()
  373. )
  374. return (
  375. rebuild_nested_tensor,
  376. (
  377. rebuild_buffer_func,
  378. rebuild_buffer_args,
  379. rebuild_sizes_func,
  380. rebuild_sizes_args,
  381. rebuild_strides_func,
  382. rebuild_strides_args,
  383. rebuild_offsets_func,
  384. rebuild_offsets_args,
  385. ),
  386. )
  387. def rebuild_sparse_coo_tensor(
  388. rebuild_indices_func,
  389. rebuild_indices_args,
  390. rebuild_values_func,
  391. rebuild_values_args,
  392. shape,
  393. is_coalesced,
  394. ):
  395. indices = rebuild_indices_func(*rebuild_indices_args)
  396. values = rebuild_values_func(*rebuild_values_args)
  397. return torch.sparse_coo_tensor(indices, values, shape, is_coalesced=is_coalesced)
  398. def rebuild_sparse_compressed_tensor(
  399. rebuild_compressed_indices_func,
  400. rebuild_compressed_indices_args,
  401. rebuild_plain_indices_func,
  402. rebuild_plain_indices_args,
  403. rebuild_values_func,
  404. rebuild_values_args,
  405. shape,
  406. layout,
  407. ):
  408. compressed_indices = rebuild_compressed_indices_func(
  409. *rebuild_compressed_indices_args
  410. )
  411. plain_indices = rebuild_plain_indices_func(*rebuild_plain_indices_args)
  412. values = rebuild_values_func(*rebuild_values_args)
  413. return torch.sparse_compressed_tensor(
  414. compressed_indices, plain_indices, values, shape, layout=layout
  415. )
  416. def reduce_sparse_tensor(sparse):
  417. if sparse.layout is torch.sparse_coo:
  418. rebuild_indices_func, rebuild_indices_args = reduce_tensor(sparse._indices())
  419. rebuild_values_func, rebuild_values_args = reduce_tensor(sparse._values())
  420. return (
  421. rebuild_sparse_coo_tensor,
  422. (
  423. rebuild_indices_func,
  424. rebuild_indices_args,
  425. rebuild_values_func,
  426. rebuild_values_args,
  427. sparse.shape,
  428. sparse.is_coalesced(),
  429. ),
  430. )
  431. else:
  432. if sparse.layout in {torch.sparse_csr, torch.sparse_bsr}:
  433. compressed_indices = sparse.crow_indices()
  434. plain_indices = sparse.col_indices()
  435. elif sparse.layout in {torch.sparse_csc, torch.sparse_bsc}:
  436. compressed_indices = sparse.ccol_indices()
  437. plain_indices = sparse.row_indices()
  438. else:
  439. raise NotImplementedError(sparse.layout)
  440. (
  441. rebuild_compressed_indices_func,
  442. rebuild_compressed_indices_args,
  443. ) = reduce_tensor(compressed_indices)
  444. rebuild_plain_indices_func, rebuild_plain_indices_args = reduce_tensor(
  445. plain_indices
  446. )
  447. rebuild_values_func, rebuild_values_args = reduce_tensor(sparse.values())
  448. return (
  449. rebuild_sparse_compressed_tensor,
  450. (
  451. rebuild_compressed_indices_func,
  452. rebuild_compressed_indices_args,
  453. rebuild_plain_indices_func,
  454. rebuild_plain_indices_args,
  455. rebuild_values_func,
  456. rebuild_values_args,
  457. sparse.shape,
  458. sparse.layout,
  459. ),
  460. )
  461. def fd_id(fd):
  462. # Returns a tuple which uniquely identifies a file descriptor. In Mac OS,
  463. # this doesn't work with shared memory handles, which is why we don't
  464. # support the "file_descriptor" sharing method on that platform.
  465. stat = os.fstat(fd)
  466. return (stat.st_ino, stat.st_dev)
  467. def storage_from_cache(cls, key):
  468. storage_ref = shared_cache.get(key)
  469. if storage_ref is None:
  470. return None
  471. return torch.UntypedStorage._new_with_weak_ptr(storage_ref.cdata)
  472. def rebuild_storage_fd(cls, df, size):
  473. fd = df.detach()
  474. try:
  475. storage = storage_from_cache(cls, fd_id(fd))
  476. if storage is not None:
  477. return storage
  478. storage = cls._new_shared_fd_cpu(fd, size)
  479. shared_cache[fd_id(fd)] = StorageWeakRef(storage)
  480. return storage
  481. finally:
  482. os.close(fd)
  483. def rebuild_storage_filename(cls, manager, handle, size, dtype=None):
  484. storage: torch.TypedStorage | torch.UntypedStorage = storage_from_cache(cls, handle)
  485. if storage is not None:
  486. return storage._shared_decref()
  487. if dtype is None:
  488. storage = torch.UntypedStorage._new_shared_filename_cpu(manager, handle, size)
  489. else:
  490. byte_size = size * torch._utils._element_size(dtype)
  491. untyped_storage: torch.UntypedStorage = (
  492. torch.UntypedStorage._new_shared_filename_cpu(manager, handle, byte_size)
  493. )
  494. storage = torch.TypedStorage(
  495. wrap_storage=untyped_storage, dtype=dtype, _internal=True
  496. )
  497. shared_cache[handle] = StorageWeakRef(storage)
  498. return storage._shared_decref()
  499. def rebuild_storage_empty(cls):
  500. return cls()
  501. def rebuild_typed_storage(storage, dtype):
  502. return torch.storage.TypedStorage(wrap_storage=storage, dtype=dtype, _internal=True)
  503. # Use for torch.storage.TypedStorage
  504. def reduce_typed_storage(storage):
  505. return (rebuild_typed_storage, (storage._untyped_storage, storage.dtype))
  506. def rebuild_typed_storage_child(storage, storage_type):
  507. return storage_type(wrap_storage=storage, _internal=True)
  508. # Use for child classes of torch.storage.TypedStorage, like torch.FloatStorage
  509. def reduce_typed_storage_child(storage):
  510. return (rebuild_typed_storage_child, (storage._untyped_storage, type(storage)))
  511. def reduce_storage(storage):
  512. from . import get_sharing_strategy
  513. if storage.is_cuda:
  514. raise RuntimeError(
  515. "Cannot pickle CUDA storage; try pickling a CUDA tensor instead"
  516. )
  517. elif storage.device.type == "meta":
  518. raise RuntimeError(
  519. "Cannot pickle meta storage; try pickling a meta tensor instead"
  520. )
  521. elif get_sharing_strategy() == "file_system":
  522. metadata = storage._share_filename_cpu_()
  523. cache_key = metadata[1]
  524. rebuild = rebuild_storage_filename
  525. if isinstance(storage, torch.TypedStorage):
  526. metadata += (storage.dtype,)
  527. storage._shared_incref()
  528. elif storage.size() == 0:
  529. # This is special cased because Empty tensors
  530. # (with size 0) cannot be mmapped.
  531. return (rebuild_storage_empty, (type(storage),))
  532. else:
  533. fd, size = storage._share_fd_cpu_()
  534. df = multiprocessing.reduction.DupFd(fd)
  535. cache_key = fd_id(fd)
  536. metadata = (df, size)
  537. rebuild = rebuild_storage_fd # type: ignore[assignment]
  538. shared_cache[cache_key] = StorageWeakRef(storage)
  539. return (rebuild, (type(storage),) + metadata)
  540. def init_reductions():
  541. reduction.register(torch.cuda.Event, reduce_event)
  542. for t in torch._storage_classes:
  543. if t.__name__ == "UntypedStorage":
  544. reduction.register(t, reduce_storage)
  545. else:
  546. reduction.register(t, reduce_typed_storage_child)
  547. reduction.register(torch.storage.TypedStorage, reduce_typed_storage)
  548. for t in torch._tensor_classes:
  549. reduction.register(t, reduce_tensor)
  550. # TODO: Maybe this should be in tensor_classes? :)
  551. reduction.register(torch.Tensor, reduce_tensor)
  552. from torch.nn.parameter import Parameter
  553. reduction.register(Parameter, reduce_tensor)