torchrec 0.2.0.dev0__37-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. examples/__init__.py +0 -0
  2. examples/datasets/__init__.py +8 -0
  3. examples/datasets/criteo_dataframes.py +101 -0
  4. examples/ray/__init__.py +0 -0
  5. examples/ray/compute_world_size.py +51 -0
  6. examples/ray/train_torchrec.py +133 -0
  7. examples/retrieval/__init__.py +6 -0
  8. examples/retrieval/data/__init__.py +6 -0
  9. examples/retrieval/data/dataloader.py +44 -0
  10. examples/retrieval/knn_index.py +67 -0
  11. examples/retrieval/modules/__init__.py +6 -0
  12. examples/retrieval/modules/two_tower.py +229 -0
  13. examples/retrieval/two_tower_retrieval.py +192 -0
  14. examples/retrieval/two_tower_train.py +253 -0
  15. examples/torcharrow/__init__.py +8 -0
  16. examples/torcharrow/dataloader.py +116 -0
  17. examples/torcharrow/run.py +126 -0
  18. fbgemm_gpu/__init__.py +16 -0
  19. fbgemm_gpu/batched_unary_embeddings_ops.py +82 -0
  20. fbgemm_gpu/enums.py +21 -0
  21. fbgemm_gpu/fbgemm_gpu_py.so +0 -0
  22. fbgemm_gpu/permute_pooled_embedding_modules.py +73 -0
  23. fbgemm_gpu/permute_pooled_embedding_modules_split.py +76 -0
  24. fbgemm_gpu/split_embedding_codegen_lookup_invokers/__init__.py +19 -0
  25. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_adagrad.py +120 -0
  26. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_adam.py +149 -0
  27. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad.py +128 -0
  28. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad_with_counter.py +134 -0
  29. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad_with_weight_decay.py +128 -0
  30. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_sgd.py +105 -0
  31. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_args.py +54 -0
  32. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_lamb.py +149 -0
  33. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_lars_sgd.py +128 -0
  34. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_partial_rowwise_adam.py +149 -0
  35. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_partial_rowwise_lamb.py +149 -0
  36. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad.py +128 -0
  37. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad_with_counter.py +134 -0
  38. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad_with_weight_decay.py +128 -0
  39. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_weighted_adagrad.py +130 -0
  40. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_sgd.py +105 -0
  41. fbgemm_gpu/split_embedding_configs.py +182 -0
  42. fbgemm_gpu/split_embedding_inference_converter.py +208 -0
  43. fbgemm_gpu/split_table_batched_embeddings_ops.py +2503 -0
  44. fbgemm_gpu/uvm.py +35 -0
  45. torchrec/__init__.py +27 -0
  46. torchrec/datasets/__init__.py +31 -0
  47. torchrec/datasets/criteo.py +831 -0
  48. torchrec/datasets/movielens.py +140 -0
  49. torchrec/datasets/random.py +188 -0
  50. torchrec/datasets/scripts/__init__.py +0 -0
  51. torchrec/datasets/scripts/contiguous_preproc_criteo.py +75 -0
  52. torchrec/datasets/scripts/npy_preproc_criteo.py +73 -0
  53. torchrec/datasets/test_utils/__init__.py +0 -0
  54. torchrec/datasets/test_utils/criteo_test_utils.py +139 -0
  55. torchrec/datasets/utils.py +341 -0
  56. torchrec/distributed/__init__.py +55 -0
  57. torchrec/distributed/batched_embedding_kernel.py +697 -0
  58. torchrec/distributed/collective_utils.py +71 -0
  59. torchrec/distributed/comm.py +149 -0
  60. torchrec/distributed/comm_ops.py +930 -0
  61. torchrec/distributed/dist_data.py +949 -0
  62. torchrec/distributed/embedding.py +638 -0
  63. torchrec/distributed/embedding_kernel.py +326 -0
  64. torchrec/distributed/embedding_lookup.py +760 -0
  65. torchrec/distributed/embedding_sharding.py +660 -0
  66. torchrec/distributed/embedding_tower_sharding.py +992 -0
  67. torchrec/distributed/embedding_types.py +369 -0
  68. torchrec/distributed/embeddingbag.py +731 -0
  69. torchrec/distributed/fused_embeddingbag.py +148 -0
  70. torchrec/distributed/grouped_position_weighted.py +103 -0
  71. torchrec/distributed/model_parallel.py +555 -0
  72. torchrec/distributed/planner/__init__.py +24 -0
  73. torchrec/distributed/planner/constants.py +77 -0
  74. torchrec/distributed/planner/enumerators.py +353 -0
  75. torchrec/distributed/planner/parallelized_planners.py +307 -0
  76. torchrec/distributed/planner/partitioners.py +280 -0
  77. torchrec/distributed/planner/perf_models.py +24 -0
  78. torchrec/distributed/planner/planners.py +290 -0
  79. torchrec/distributed/planner/proposers.py +270 -0
  80. torchrec/distributed/planner/shard_estimators.py +971 -0
  81. torchrec/distributed/planner/stats.py +477 -0
  82. torchrec/distributed/planner/storage_reservations.py +168 -0
  83. torchrec/distributed/planner/types.py +423 -0
  84. torchrec/distributed/planner/utils.py +30 -0
  85. torchrec/distributed/quant_embedding.py +307 -0
  86. torchrec/distributed/quant_embedding_kernel.py +295 -0
  87. torchrec/distributed/quant_embeddingbag.py +288 -0
  88. torchrec/distributed/sharding/__init__.py +0 -0
  89. torchrec/distributed/sharding/cw_sequence_sharding.py +71 -0
  90. torchrec/distributed/sharding/cw_sharding.py +242 -0
  91. torchrec/distributed/sharding/dp_sequence_sharding.py +87 -0
  92. torchrec/distributed/sharding/dp_sharding.py +217 -0
  93. torchrec/distributed/sharding/rw_sequence_sharding.py +130 -0
  94. torchrec/distributed/sharding/rw_sharding.py +393 -0
  95. torchrec/distributed/sharding/sequence_sharding.py +69 -0
  96. torchrec/distributed/sharding/tw_sequence_sharding.py +211 -0
  97. torchrec/distributed/sharding/tw_sharding.py +469 -0
  98. torchrec/distributed/sharding/twcw_sharding.py +32 -0
  99. torchrec/distributed/sharding/twrw_sharding.py +543 -0
  100. torchrec/distributed/sharding/vb_cw_sharding.py +91 -0
  101. torchrec/distributed/sharding/vb_rw_sharding.py +250 -0
  102. torchrec/distributed/sharding/vb_sharding.py +54 -0
  103. torchrec/distributed/sharding/vb_tw_sharding.py +148 -0
  104. torchrec/distributed/sharding/vb_twrw_sharding.py +388 -0
  105. torchrec/distributed/test_utils/__init__.py +0 -0
  106. torchrec/distributed/test_utils/multi_process.py +132 -0
  107. torchrec/distributed/test_utils/test_model.py +818 -0
  108. torchrec/distributed/test_utils/test_model_parallel.py +74 -0
  109. torchrec/distributed/test_utils/test_model_parallel_base.py +117 -0
  110. torchrec/distributed/test_utils/test_sharding.py +280 -0
  111. torchrec/distributed/train_pipeline.py +531 -0
  112. torchrec/distributed/types.py +594 -0
  113. torchrec/distributed/utils.py +186 -0
  114. torchrec/fused_planner.py +57 -0
  115. torchrec/fx/__init__.py +15 -0
  116. torchrec/fx/tracer.py +78 -0
  117. torchrec/inference/__init__.py +25 -0
  118. torchrec/inference/client.py +127 -0
  119. torchrec/inference/model_packager.py +102 -0
  120. torchrec/inference/modules.py +155 -0
  121. torchrec/inference/state_dict_transform.py +103 -0
  122. torchrec/metrics/__init__.py +0 -0
  123. torchrec/metrics/auc.py +159 -0
  124. torchrec/metrics/calibration.py +108 -0
  125. torchrec/metrics/ctr.py +104 -0
  126. torchrec/metrics/metric_module.py +358 -0
  127. torchrec/metrics/metrics_config.py +152 -0
  128. torchrec/metrics/metrics_namespace.py +114 -0
  129. torchrec/metrics/model_utils.py +85 -0
  130. torchrec/metrics/mse.py +134 -0
  131. torchrec/metrics/ne.py +164 -0
  132. torchrec/metrics/rec_metric.py +686 -0
  133. torchrec/metrics/throughput.py +174 -0
  134. torchrec/models/__init__.py +27 -0
  135. torchrec/models/deepfm.py +346 -0
  136. torchrec/models/dlrm.py +708 -0
  137. torchrec/modules/__init__.py +34 -0
  138. torchrec/modules/activation.py +55 -0
  139. torchrec/modules/crossnet.py +446 -0
  140. torchrec/modules/deepfm.py +213 -0
  141. torchrec/modules/embedding_configs.py +148 -0
  142. torchrec/modules/embedding_modules.py +381 -0
  143. torchrec/modules/embedding_tower.py +150 -0
  144. torchrec/modules/feature_processor.py +74 -0
  145. torchrec/modules/fused_embedding_modules.py +625 -0
  146. torchrec/modules/lazy_extension.py +258 -0
  147. torchrec/modules/mlp.py +172 -0
  148. torchrec/modules/utils.py +117 -0
  149. torchrec/optim/__init__.py +35 -0
  150. torchrec/optim/clipping.py +53 -0
  151. torchrec/optim/fused.py +42 -0
  152. torchrec/optim/keyed.py +399 -0
  153. torchrec/optim/rowwise_adagrad.py +222 -0
  154. torchrec/optim/test_utils/__init__.py +19 -0
  155. torchrec/optim/warmup.py +147 -0
  156. torchrec/quant/__init__.py +34 -0
  157. torchrec/quant/embedding_modules.py +545 -0
  158. torchrec/sparse/__init__.py +33 -0
  159. torchrec/sparse/jagged_tensor.py +1281 -0
  160. torchrec/sparse/test_utils/__init__.py +45 -0
  161. torchrec/streamable.py +46 -0
  162. torchrec/test_utils/__init__.py +111 -0
  163. torchrec-0.2.dev0.dist-info/LICENSE +29 -0
  164. torchrec-0.2.dev0.dist-info/METADATA +175 -0
  165. torchrec-0.2.dev0.dist-info/RECORD +167 -0
  166. torchrec-0.2.dev0.dist-info/WHEEL +5 -0
  167. torchrec-0.2.dev0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,594 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import abc
9
+ import operator
10
+ from dataclasses import dataclass
11
+ from enum import Enum, unique
12
+ from typing import Any, Callable, Dict, Generic, Iterator, List, Optional, Type, TypeVar
13
+
14
+ from torch.autograd.profiler import record_function
15
+
16
+ try:
17
+ # For python 3.6 and below, GenericMeta will be used by
18
+ # other metaclasses (i.e. AwaitableMeta) for customized
19
+ # behaviors, as Generic is non-trival metaclass in
20
+ # python 3.6 and below
21
+ from typing import GenericMeta # pyre-ignore: python 3.6
22
+ except ImportError:
23
+ # In python 3.7+, GenericMeta doesn't exist as it's no
24
+ # longer a non-trival metaclass,
25
+ # see https://www.python.org/dev/peps/pep-0560/
26
+ # So we make a fake type here in order to share the same
27
+ # code with python 3.6 or below, it will just be used as
28
+ # a placeholder for customized metaclass behaviors
29
+ # (i.e. Awaitable)
30
+ class GenericMeta(type):
31
+ pass
32
+
33
+
34
+ import torch
35
+ import torch.distributed as dist
36
+ import torch.fx
37
+ from torch import nn
38
+
39
+ # @manual
40
+ from torch.distributed._shard.sharded_tensor import ( # noqa
41
+ Shard,
42
+ ShardedTensor,
43
+ ShardedTensorMetadata,
44
+ TensorProperties,
45
+ )
46
+
47
+ # @manual
48
+ from torch.distributed._shard.sharding_spec import ( # noqa
49
+ EnumerableShardingSpec,
50
+ ShardingSpec,
51
+ ShardMetadata,
52
+ )
53
+ from torchrec.streamable import Multistreamable
54
+
55
+
56
+ class ShardingType(Enum):
57
+ """
58
+ Well-known sharding types, used by inter-module optimizations.
59
+ """
60
+
61
+ # Replicated on all ranks
62
+ DATA_PARALLEL = "data_parallel"
63
+ # Placed on a single rank
64
+ TABLE_WISE = "table_wise"
65
+ # Placed on multiple ranks as different sharded tables
66
+ COLUMN_WISE = "column_wise"
67
+ # Range-split on the first dimension across all ranks
68
+ ROW_WISE = "row_wise"
69
+ # Row-wise on the same node and table-wise across nodes
70
+ # Useful when having multiple ranks per node
71
+ # and comms within a single node are more efficient than across nodes.
72
+ TABLE_ROW_WISE = "table_row_wise"
73
+ # Column-wise on the same node and table-wise across nodes
74
+ TABLE_COLUMN_WISE = "table_column_wise"
75
+
76
+
77
+ class ParameterStorage(Enum):
78
+ """
79
+ Well-known physical resources, which can be used as constraints by ShardingPlanner.
80
+ """
81
+
82
+ # GPU-attached memory
83
+ HBM = "hbm"
84
+ # CPU-attached memory
85
+ DDR = "ddr"
86
+
87
+
88
+ @unique
89
+ class ComputeKernel(Enum):
90
+ DEFAULT = "default"
91
+
92
+
93
+ W = TypeVar("W")
94
+ M = TypeVar("M", bound=nn.Module)
95
+ Out = TypeVar("Out")
96
+ CompIn = TypeVar("CompIn", bound=Multistreamable)
97
+ DistOut = TypeVar("DistOut")
98
+
99
+
100
+ class Awaitable(abc.ABC, Generic[W]):
101
+ def __init__(self) -> None:
102
+ self._callbacks: List[Callable[[W], W]] = []
103
+
104
+ @abc.abstractmethod
105
+ def _wait_impl(self) -> W:
106
+ pass
107
+
108
+ def wait(self) -> W:
109
+ with record_function(f"## {self.__class__.__name__} wait() ##"):
110
+ ret: W = self._wait_impl()
111
+ for callback in self.callbacks:
112
+ ret = callback(ret)
113
+ return ret
114
+
115
+ @property
116
+ def callbacks(self) -> List[Callable[[W], W]]:
117
+ return self._callbacks
118
+
119
+
120
+ class NoWait(Awaitable[W]):
121
+ def __init__(self, obj: W) -> None:
122
+ super().__init__()
123
+ self._obj = obj
124
+
125
+ def _wait_impl(self) -> W:
126
+ return self._obj
127
+
128
+
129
+ # pyre-fixme[11]: Annotation `ProxyableClassMeta` is not defined as a type.
130
+ class _LazyAwaitableMeta(GenericMeta, abc.ABCMeta, torch.fx.ProxyableClassMeta):
131
+ """
132
+ The _LazyAwaitableMeta class that inherits both ABCMeta and ProxyableClassMeta
133
+ This is because ABCMeta/ProxyableClassMeta are both non-trival metaclasses
134
+ Declaring this separately to ensure the init order of metaclasses
135
+
136
+ XXX: Generics are non-trival metaclass before python 3.7 but are removed
137
+ afterwards. we add GenericsMeta here to support version before 3.7.
138
+ """
139
+
140
+ pass
141
+
142
+
143
+ class LazyAwaitable(Awaitable[W], metaclass=_LazyAwaitableMeta):
144
+ """
145
+ The LazyAwaitable type which exposes a `wait()` API, concrete types
146
+ can control how to initialize and how the `wait()` behavior should
147
+ be in order to achieve specific async operation.
148
+
149
+ This base LazyAwaitable type is a "lazy" async type, which means it will
150
+ delay `wait()` as late as possible, see details in `__torch_function__`
151
+ below. This could help the model automatically enable computation and
152
+ communication overlap, model author doesn't need to manually call
153
+ `wait()` if the results is used by a pytorch function, or by other python
154
+ operations (NOTE: need to implement corresponding magic methods
155
+ like __getattr__ below)
156
+
157
+ Some caveats:
158
+
159
+ * This works with Pytorch functions, but not any generic method, if
160
+ you would like to do arbitary python operations, you need to
161
+ implement the corresponding magic methods
162
+
163
+ * In the case that one function have two or more arguments are LazyAwaitable,
164
+ the lazy wait mechanism can't ensure perfect computation/communication
165
+ overlap (i.e. quickly waited the first one but long wait on the second)
166
+ """
167
+
168
+ def __init__(
169
+ self,
170
+ ) -> None:
171
+ super().__init__()
172
+ # _result is used to cache the results after the wait() is called.
173
+ self._result: Optional[W] = None
174
+
175
+ @staticmethod
176
+ # pyre-ignore [2, 3]
177
+ def _wait_async(obj: Any) -> Any:
178
+ """
179
+ This method is used internally to automatically wait when necessary
180
+ and cache the results of the `LazyAwaitable.wait()` call
181
+ """
182
+ if isinstance(obj, LazyAwaitable):
183
+ if obj._result is None:
184
+ obj._result = obj.wait()
185
+ return obj._result
186
+ else:
187
+ return obj
188
+
189
+ # pyre-ignore [2, 3]
190
+ def __torch_function__(self, func, types, args=(), kwargs=None):
191
+ """
192
+ The LazyAwaitable type has a `__torch_function__` implementation.
193
+ This means when this type is seens as an argument to a PyTorch
194
+ function in a position where it expects a W, the PyTorch's
195
+ dispatcher will call into this function for special handling
196
+
197
+ Our `__torch_function__` implementation goes through all of the
198
+ args and kwargs and checks if any of them are `LazyAwaitable`.
199
+ If it is, it will call `wait()` on it and replace the LazyAwaitable
200
+ type object with the result of wait. In this way, async values
201
+ are waited on when the concrete value is first needed and without
202
+ the user having to write an explicit `wait()` call.
203
+ """
204
+ kwargs = kwargs or {}
205
+
206
+ # wait() on all LazyAwaitable args/kwargs and replace
207
+ # them with the resulting value.
208
+ new_args = torch.fx.node.map_aggregate(args, LazyAwaitable._wait_async)
209
+ new_kwargs = torch.fx.node.map_aggregate(kwargs, LazyAwaitable._wait_async)
210
+
211
+ return func(*new_args, **new_kwargs)
212
+
213
+ # pyre-ignore [2, 3]
214
+ def __getattr__(self, name):
215
+ """
216
+ Overrides __getattr__ to allow LazyAwaitable to first wait and then call getattr
217
+ on the wait results.
218
+ """
219
+ if name == "_result":
220
+ raise RuntimeError(
221
+ f"LazyAwaitable type {type(self)} has not been initialized properly, "
222
+ f"did you forget to call 'super()'?"
223
+ )
224
+
225
+ res = LazyAwaitable._wait_async(self)
226
+ return getattr(res, name)
227
+
228
+
229
+ class LazyNoWait(LazyAwaitable[W]):
230
+ def __init__(self, obj: W) -> None:
231
+ super().__init__()
232
+ self._obj = obj
233
+
234
+ def _wait_impl(self) -> W:
235
+ return self._obj
236
+
237
+
238
+ # install magic methods
239
+ for orig_method_name in torch.fx.graph.magic_methods:
240
+ as_magic = f"__{orig_method_name}__"
241
+
242
+ def scope(method):
243
+ def impl(*args, **kwargs):
244
+ lhs = args[0]
245
+ op_fn = getattr(operator, method)
246
+ if len(args) == 1:
247
+ return op_fn(LazyAwaitable._wait_async(lhs))
248
+ elif len(args) == 2:
249
+ rhs = args[1]
250
+ return op_fn(
251
+ LazyAwaitable._wait_async(lhs), LazyAwaitable._wait_async(rhs)
252
+ )
253
+ else:
254
+ raise RuntimeError(f"magic method {as_magic} not supported!")
255
+
256
+ impl.__name__ = as_magic
257
+ setattr(LazyAwaitable, as_magic, impl)
258
+
259
+ # pyre-ignore [16]
260
+ scope(orig_method_name)
261
+
262
+ # install reflective magic methods
263
+ for orig_method_name in torch.fx.graph.reflectable_magic_methods:
264
+ as_magic = f"__r{orig_method_name}__"
265
+ # pyre-ignore [2, 3]
266
+ def scope(method):
267
+ # pyre-ignore [2, 3, 53]
268
+ def impl(self, rhs):
269
+ op_fn = getattr(operator, method)
270
+ return op_fn(
271
+ LazyAwaitable._wait_async(rhs), LazyAwaitable._wait_async(self)
272
+ )
273
+
274
+ impl.__name__ = as_magic
275
+ impl.__qualname__ = as_magic
276
+ setattr(LazyAwaitable, as_magic, impl)
277
+
278
+ # pyre-ignore [16]
279
+ scope(orig_method_name)
280
+
281
+
282
+ @dataclass
283
+ class ParameterSharding:
284
+ """
285
+ Describes the sharding of the parameter.
286
+
287
+ sharding_type (str): how this parameter is sharded. See ShardingType for well-known
288
+ types.
289
+ compute_kernel (str): compute kernel to be used by this parameter.
290
+ ranks (Optional[List[int]]): rank of each shard.
291
+ sharding_spec (Optional[ShardingSpec]): list of ShardMetadata for each shard.
292
+
293
+ NOTE:
294
+ ShardingType.TABLE_WISE - rank where this embedding is placed
295
+ ShardingType.COLUMN_WISE - rank where the embedding shards are placed, seen as
296
+ individual tables
297
+ ShardingType.TABLE_ROW_WISE - first rank when this embedding is placed
298
+ ShardingType.ROW_WISE, ShardingType.DATA_PARALLEL - unused
299
+
300
+ """
301
+
302
+ sharding_type: str
303
+ compute_kernel: str
304
+ ranks: Optional[List[int]] = None
305
+ sharding_spec: Optional[ShardingSpec] = None
306
+
307
+
308
+ @dataclass
309
+ class ShardedModuleContext(Multistreamable):
310
+ pass
311
+
312
+
313
+ class EmptyContext(ShardedModuleContext):
314
+ def record_stream(self, stream: torch.cuda.streams.Stream) -> None:
315
+ pass
316
+
317
+ # pyre-ignore [2]
318
+ def __setattr__(self, key: str, value: Any) -> None:
319
+ raise NotImplementedError()
320
+
321
+
322
+ class ShardingEnv:
323
+ """
324
+ Provides an abstraction over `torch.distributed.ProcessGroup`, which practically
325
+ enables `DistributedModelParallel` to be used during inference.
326
+ """
327
+
328
+ def __init__(
329
+ self,
330
+ world_size: int,
331
+ rank: int,
332
+ pg: Optional[dist.ProcessGroup] = None,
333
+ ) -> None:
334
+ self.world_size = world_size
335
+ self.rank = rank
336
+ self.process_group: Optional[dist.ProcessGroup] = pg
337
+
338
+ @classmethod
339
+ def from_process_group(cls, pg: dist.ProcessGroup) -> "ShardingEnv":
340
+ """
341
+ Creates ProcessGroup-based sharding environment.
342
+
343
+ NOTE:
344
+ Typically used during training.
345
+ """
346
+ return cls(dist.get_world_size(pg), dist.get_rank(pg), pg)
347
+
348
+ @classmethod
349
+ def from_local(cls, world_size: int, rank: int) -> "ShardingEnv":
350
+ """
351
+ Creates a local host-based sharding environment.
352
+
353
+ NOTE:
354
+ Typically used during single host inference.
355
+ """
356
+ return cls(world_size, rank, None)
357
+
358
+
359
+ class ModuleCopyMixin:
360
+ """
361
+ A mixin to allow modules to override copy behaviors in DMP.
362
+ """
363
+
364
+ def copy(self, device: torch.device) -> nn.Module:
365
+ # pyre-ignore [16]
366
+ return self.to(device)
367
+
368
+
369
+ class ShardedModule(abc.ABC, nn.Module, Generic[CompIn, DistOut, Out], ModuleCopyMixin):
370
+ """
371
+ All model-parallel modules implement this interface.
372
+ Inputs and outputs are data-parallel.
373
+
374
+ NOTE:
375
+ 'input_dist' / 'output_dist' are responsible of transforming inputs / outputs
376
+ from data-parallel to model parallel and vise-versa.
377
+ """
378
+
379
+ @abc.abstractmethod
380
+ def __init__(self) -> None:
381
+ super().__init__()
382
+ torch._C._log_api_usage_once(f"torchrec.distributed.{self.__class__.__name__}")
383
+
384
+ def create_context(self) -> ShardedModuleContext:
385
+ return EmptyContext()
386
+
387
+ @abc.abstractmethod
388
+ def input_dist(
389
+ self,
390
+ ctx: ShardedModuleContext,
391
+ # pyre-ignore[2]
392
+ *input,
393
+ # pyre-ignore[2]
394
+ **kwargs,
395
+ ) -> Awaitable[CompIn]:
396
+ pass
397
+
398
+ @abc.abstractmethod
399
+ def compute(self, ctx: ShardedModuleContext, dist_input: CompIn) -> DistOut:
400
+ pass
401
+
402
+ @abc.abstractmethod
403
+ def output_dist(
404
+ self, ctx: ShardedModuleContext, output: DistOut
405
+ ) -> LazyAwaitable[Out]:
406
+ pass
407
+
408
+ def compute_and_output_dist(
409
+ self, ctx: ShardedModuleContext, input: CompIn
410
+ ) -> LazyAwaitable[Out]:
411
+ """
412
+ In case of multiple output distributions it makes sense to override this method
413
+ and initiate the output distibution as soon as the corresponding compute
414
+ completes.
415
+ """
416
+ output = self.compute(ctx, input)
417
+ return self.output_dist(ctx, output)
418
+
419
+ # pyre-ignore[2]
420
+ def forward(self, *input, **kwargs) -> LazyAwaitable[Out]:
421
+ """
422
+ Executes the input dist, compute, and output dist steps.
423
+
424
+ Args:
425
+ *input: input.
426
+ **kwargs: keyword arguments.
427
+
428
+ Returns:
429
+ LazyAwaitable[Out]: awaitable of output from output dist.
430
+ """
431
+ ctx = self.create_context()
432
+ dist_input = self.input_dist(ctx, *input, **kwargs).wait()
433
+ return self.compute_and_output_dist(ctx, dist_input)
434
+
435
+ def sparse_grad_parameter_names(
436
+ self,
437
+ destination: Optional[List[str]] = None,
438
+ prefix: str = "",
439
+ ) -> List[str]:
440
+ destination = [] if destination is None else destination
441
+ return destination
442
+
443
+ def sharded_parameter_names(self, prefix: str = "") -> Iterator[str]:
444
+ for key, _ in self.named_parameters(prefix):
445
+ yield key
446
+
447
+
448
+ class ModuleSharder(abc.ABC, Generic[M]):
449
+ """
450
+ `ModuleSharder` is per each module, which supports sharding,
451
+ e.g. `EmbeddingBagCollection`.
452
+ """
453
+
454
+ def __init__(self) -> None:
455
+ torch._C._log_api_usage_once(f"torchrec.distributed.{self.__class__.__name__}")
456
+
457
+ @abc.abstractclassmethod
458
+ # pyre-ignore [3]
459
+ def shard(
460
+ self,
461
+ module: M,
462
+ params: Dict[str, ParameterSharding],
463
+ env: ShardingEnv,
464
+ device: Optional[torch.device] = None,
465
+ ) -> ShardedModule[Any, Any, Any]:
466
+ """
467
+ Does the actual sharding. It will allocate parameters on the requested locations
468
+ as specified by corresponding ParameterSharding.
469
+
470
+ Default implementation is data-parallel replication.
471
+
472
+ Args:
473
+ module (M): module to shard.
474
+ params (Dict[str, ParameterSharding]): dict of fully qualified parameter names
475
+ (module path + parameter name, '.'-separated) to its sharding spec.
476
+ env (ShardingEnv): sharding environment that has the process group.
477
+ device (torch.device): compute device.
478
+
479
+ Returns:
480
+ ShardedModule[Any, Any, Any]: sharded module implementation.
481
+ """
482
+ ...
483
+
484
+ @property
485
+ @abc.abstractmethod
486
+ def module_type(self) -> Type[M]:
487
+ ...
488
+
489
+ def shardable_parameters(self, module: M) -> Dict[str, nn.Parameter]:
490
+ """
491
+ List of parameters that can be sharded.
492
+ """
493
+ return dict(module.named_parameters())
494
+
495
+ def sharding_types(self, compute_device_type: str) -> List[str]:
496
+ """
497
+ List of supported sharding types. See `ShardingType` for well-known examples.
498
+ """
499
+ return [ShardingType.DATA_PARALLEL.value]
500
+
501
+ def compute_kernels(
502
+ self, sharding_type: str, compute_device_type: str
503
+ ) -> List[str]:
504
+ """
505
+ List of supported compute kernels for a given sharding type and compute device.
506
+ """
507
+
508
+ return [ComputeKernel.DEFAULT.value]
509
+
510
+ def storage_usage(
511
+ self, tensor: torch.Tensor, compute_device_type: str, compute_kernel: str
512
+ ) -> Dict[str, int]:
513
+ """
514
+ List of system resources and corresponding usage given a compute device and
515
+ compute kernel.
516
+ """
517
+
518
+ assert compute_device_type in {"cuda", "cpu"}
519
+ storage_map = {"cuda": ParameterStorage.HBM, "cpu": ParameterStorage.DDR}
520
+ return {
521
+ storage_map[compute_device_type].value: tensor.element_size()
522
+ * tensor.nelement()
523
+ }
524
+
525
+
526
+ @dataclass
527
+ class ShardingPlan:
528
+ """
529
+ Representation of sharding plan.
530
+
531
+ Attributes:
532
+ plan (Dict[str, Dict[str, ParameterSharding]]): dict keyed by module path of
533
+ dict of parameter sharding specs keyed by parameter name.
534
+ """
535
+
536
+ plan: Dict[str, Dict[str, ParameterSharding]]
537
+
538
+ def get_plan_for_module(
539
+ self, module_path: str
540
+ ) -> Optional[Dict[str, ParameterSharding]]:
541
+ """
542
+ Args:
543
+ module_path (str):
544
+
545
+ Returns:
546
+ Optional[Dict[str, ParameterSharding]]: dict of parameter sharding specs keyed by parameter name. None if sharding specs do not exist for given module_path.
547
+ """
548
+ return self.plan.get(module_path, None)
549
+
550
+ def __str__(self) -> str:
551
+ return str(self.plan)
552
+
553
+
554
+ class ShardingPlanner(abc.ABC):
555
+ """
556
+ Plans sharding.
557
+ This plan can be saved and re-used to ensure sharding stability.
558
+ """
559
+
560
+ @abc.abstractmethod
561
+ def plan(
562
+ self,
563
+ module: nn.Module,
564
+ sharders: List[ModuleSharder[nn.Module]],
565
+ ) -> ShardingPlan:
566
+ """
567
+ Plans sharding for provided module and given sharders.
568
+
569
+ Args:
570
+ module (nn.Module): module that sharding is planned for.
571
+ sharders (List[ModuleSharder[nn.Module]]): provided sharders for module.
572
+
573
+ Returns:
574
+ ShardingPlan: the computed sharding plan.
575
+ """
576
+ ...
577
+
578
+ @abc.abstractmethod
579
+ def collective_plan(
580
+ self,
581
+ module: nn.Module,
582
+ sharders: List[ModuleSharder[nn.Module]],
583
+ ) -> ShardingPlan:
584
+ """
585
+ Calls self.plan(...) on rank 0 and broadcasts.
586
+
587
+ Args:
588
+ module (nn.Module): module that sharding is planned for.
589
+ sharders (List[ModuleSharder[nn.Module]]): provided sharders for module.
590
+
591
+ Returns:
592
+ ShardingPlan: the computed sharding plan.
593
+ """
594
+ ...