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,555 @@
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 copy
10
+ from collections import OrderedDict
11
+ from typing import Any, cast, Dict, Iterator, List, Optional, Tuple
12
+
13
+ import torch
14
+ import torch.distributed as dist
15
+ from torch import nn
16
+ from torch.distributed.fsdp import FullyShardedDataParallel
17
+ from torch.nn.modules.module import _IncompatibleKeys
18
+ from torch.nn.parallel import DistributedDataParallel
19
+ from torchrec.distributed.comm import get_local_size
20
+ from torchrec.distributed.embedding import EmbeddingCollectionSharder
21
+ from torchrec.distributed.embeddingbag import EmbeddingBagCollectionSharder
22
+ from torchrec.distributed.fused_embeddingbag import FusedEmbeddingBagCollectionSharder
23
+ from torchrec.distributed.planner import (
24
+ EmbeddingShardingPlanner,
25
+ sharder_name,
26
+ Topology,
27
+ )
28
+ from torchrec.distributed.quant_embedding import QuantEmbeddingCollectionSharder
29
+ from torchrec.distributed.quant_embeddingbag import QuantEmbeddingBagCollectionSharder
30
+ from torchrec.distributed.types import (
31
+ ModuleCopyMixin,
32
+ ModuleSharder,
33
+ ShardedModule,
34
+ ShardingEnv,
35
+ ShardingPlan,
36
+ )
37
+ from torchrec.distributed.utils import (
38
+ add_prefix_to_state_dict,
39
+ append_prefix,
40
+ filter_state_dict,
41
+ sharded_model_copy,
42
+ )
43
+ from torchrec.optim.fused import FusedOptimizerModule
44
+ from torchrec.optim.keyed import CombinedOptimizer, KeyedOptimizer
45
+
46
+
47
+ _DDP_STATE_DICT_PREFIX = "module."
48
+
49
+
50
+ def get_default_sharders() -> List[ModuleSharder[nn.Module]]:
51
+ return [
52
+ cast(ModuleSharder[nn.Module], EmbeddingBagCollectionSharder()),
53
+ cast(ModuleSharder[nn.Module], FusedEmbeddingBagCollectionSharder()),
54
+ cast(ModuleSharder[nn.Module], EmbeddingCollectionSharder()),
55
+ cast(ModuleSharder[nn.Module], QuantEmbeddingBagCollectionSharder()),
56
+ cast(ModuleSharder[nn.Module], QuantEmbeddingCollectionSharder()),
57
+ ]
58
+
59
+
60
+ class DataParallelWrapper(abc.ABC):
61
+ """
62
+ Interface implemented by custom data parallel wrappers.
63
+ """
64
+
65
+ @abc.abstractmethod
66
+ def wrap(
67
+ self,
68
+ dmp: "DistributedModelParallel",
69
+ env: ShardingEnv,
70
+ device: torch.device,
71
+ ) -> None:
72
+ pass
73
+
74
+
75
+ class DefaultDataParallelWrapper(DataParallelWrapper):
76
+ """
77
+ Default data parallel wrapper, which applies data parallel to all unsharded modules.
78
+ """
79
+
80
+ def wrap(
81
+ self,
82
+ dmp: "DistributedModelParallel",
83
+ env: ShardingEnv,
84
+ device: torch.device,
85
+ ) -> None:
86
+ if isinstance(dmp._dmp_wrapped_module, DistributedDataParallel) or isinstance(
87
+ dmp._dmp_wrapped_module, FullyShardedDataParallel
88
+ ):
89
+ return
90
+ pg = env.process_group
91
+ if pg is None:
92
+ raise RuntimeError("Can only init DDP for ProcessGroup-based ShardingEnv")
93
+ sharded_parameter_names = {
94
+ key
95
+ for key in DistributedModelParallel._sharded_parameter_names(
96
+ dmp._dmp_wrapped_module
97
+ )
98
+ }
99
+ all_paramemeter_names = {key for key, _ in dmp.named_parameters()}
100
+ if sharded_parameter_names == all_paramemeter_names:
101
+ return
102
+
103
+ # pyre-fixme[16]: `DistributedDataParallel` has no attribute
104
+ # `_set_params_and_buffers_to_ignore_for_model`.
105
+ DistributedDataParallel._set_params_and_buffers_to_ignore_for_model(
106
+ module=dmp._dmp_wrapped_module,
107
+ params_and_buffers_to_ignore=[
108
+ key for key in all_paramemeter_names if key in sharded_parameter_names
109
+ ],
110
+ )
111
+ # initialize DDP
112
+ dmp._dmp_wrapped_module = cast(
113
+ nn.Module,
114
+ # pyre-fixme[28]: Unexpected keyword argument `gradient_as_bucket_view`.
115
+ DistributedDataParallel(
116
+ module=dmp._dmp_wrapped_module.to(device),
117
+ device_ids=None if device.type == "cpu" else [device],
118
+ process_group=pg,
119
+ gradient_as_bucket_view=True,
120
+ broadcast_buffers=False,
121
+ static_graph=True,
122
+ ),
123
+ )
124
+
125
+
126
+ def get_unwrapped_module(module: nn.Module) -> nn.Module:
127
+ """
128
+ Unwraps module wrapped by DMP, DDP, or FSDP.
129
+ """
130
+ while (
131
+ isinstance(module, DistributedModelParallel)
132
+ or isinstance(module, DistributedDataParallel)
133
+ or isinstance(module, FullyShardedDataParallel)
134
+ ):
135
+ if isinstance(module, DistributedModelParallel):
136
+ module = module._dmp_wrapped_module
137
+ elif isinstance(module, FullyShardedDataParallel):
138
+ module = module._fsdp_wrapped_module
139
+ else:
140
+ module = module.module
141
+ return module
142
+
143
+
144
+ def get_module(module: nn.Module) -> nn.Module:
145
+ """
146
+ Unwraps DMP module.
147
+
148
+ Does not unwrap data parallel wrappers (i.e. DDP/FSDP), so overriding
149
+ implementations by the wrappers can be used.
150
+ """
151
+ while isinstance(module, DistributedModelParallel):
152
+ module = module._dmp_wrapped_module
153
+ return module
154
+
155
+
156
+ class DistributedModelParallel(nn.Module, FusedOptimizerModule):
157
+ """
158
+ Entry point to model parallelism.
159
+
160
+ Args:
161
+ module (nn.Module): module to wrap.
162
+ env (Optional[ShardingEnv]): sharding environment that has the process group.
163
+ device (Optional[torch.device]): compute device, defaults to cpu.
164
+ plan (Optional[ShardingPlan]): plan to use when sharding, defaults to
165
+ `EmbeddingShardingPlanner.collective_plan()`.
166
+ sharders (Optional[List[ModuleSharder[nn.Module]]]): `ModuleSharders` available
167
+ to shard with, defaults to `EmbeddingBagCollectionSharder()`.
168
+ init_data_parallel (bool): data-parallel modules can be lazy, i.e. they delay
169
+ parameter initialization until the first forward pass. Pass `True` to delay
170
+ initialization of data parallel modules. Do first forward pass and then call
171
+ DistributedModelParallel.init_data_parallel().
172
+ init_parameters (bool): initialize parameters for modules still on meta device.
173
+ data_parallel_wrapper (Optional[DataParallelWrapper]): custom wrapper for data
174
+ parallel modules.
175
+
176
+ Example::
177
+
178
+ @torch.no_grad()
179
+ def init_weights(m):
180
+ if isinstance(m, nn.Linear):
181
+ m.weight.fill_(1.0)
182
+ elif isinstance(m, EmbeddingBagCollection):
183
+ for param in m.parameters():
184
+ init.kaiming_normal_(param)
185
+
186
+ m = MyModel(device='meta')
187
+ m = DistributedModelParallel(m)
188
+ m.apply(init_weights)
189
+ """
190
+
191
+ def __init__(
192
+ self,
193
+ module: nn.Module,
194
+ env: Optional[ShardingEnv] = None,
195
+ device: Optional[torch.device] = None,
196
+ plan: Optional[ShardingPlan] = None,
197
+ sharders: Optional[List[ModuleSharder[torch.nn.Module]]] = None,
198
+ init_data_parallel: bool = True,
199
+ init_parameters: bool = True,
200
+ data_parallel_wrapper: Optional[DataParallelWrapper] = None,
201
+ ) -> None:
202
+ super().__init__()
203
+ torch._C._log_api_usage_once(f"torchrec.distributed.{self.__class__.__name__}")
204
+
205
+ self._dmp_wrapped_module = module
206
+ self.init_parameters = init_parameters
207
+ self._ddp_wrapped: bool = False
208
+
209
+ if env is None:
210
+ pg = dist.GroupMember.WORLD
211
+ assert pg is not None, "Process group is not initialized"
212
+ env = ShardingEnv.from_process_group(pg)
213
+ self._env: ShardingEnv = env
214
+
215
+ if device is None:
216
+ device = torch.device("cpu")
217
+ self.device: torch.device = device
218
+
219
+ if sharders is None:
220
+ sharders = get_default_sharders()
221
+ self._sharder_map: Dict[str, ModuleSharder[nn.Module]] = {
222
+ sharder_name(sharder.module_type): sharder for sharder in sharders
223
+ }
224
+
225
+ if data_parallel_wrapper is None:
226
+ data_parallel_wrapper = DefaultDataParallelWrapper()
227
+ self._data_parallel_wrapper: DataParallelWrapper = data_parallel_wrapper
228
+
229
+ # 2. Call ShardingPlanner.collective_plan passing all found modules and corresponding sharders.
230
+ if plan is None:
231
+ planner = EmbeddingShardingPlanner(
232
+ topology=Topology(
233
+ local_world_size=get_local_size(self._env.world_size),
234
+ world_size=self._env.world_size,
235
+ compute_device=self.device.type,
236
+ )
237
+ )
238
+ pg = self._env.process_group
239
+ if pg is not None:
240
+ plan = planner.collective_plan(module, sharders, pg)
241
+ else:
242
+ plan = planner.plan(module, sharders)
243
+ self._plan: ShardingPlan = plan
244
+
245
+ # 3. Replace modules w/ sharded versions,
246
+ # and then wrap w/ DistributedDataParallel.
247
+ fused_optims = []
248
+ self._init_dmp(
249
+ fused_optims=fused_optims,
250
+ )
251
+ if init_data_parallel:
252
+ self.init_data_parallel()
253
+ self._optim = CombinedOptimizer(fused_optims)
254
+
255
+ @property
256
+ def module(self) -> nn.Module:
257
+ """
258
+ Property to directly access sharded module, which will not be wrapped in DDP,
259
+ FSDP, DMP, or any other parallelism wrappers.
260
+ """
261
+ return get_unwrapped_module(self)
262
+
263
+ @module.setter
264
+ def module(self, value: nn.Module) -> None:
265
+ if isinstance(self.module, DistributedDataParallel) or isinstance(
266
+ self.module, FullyShardedDataParallel
267
+ ):
268
+ raise RuntimeError(
269
+ "module can't be set after calling init_data_parallel(...)"
270
+ )
271
+ else:
272
+ self._dmp_wrapped_module = value
273
+
274
+ # pyre-ignore [2, 3]
275
+ def forward(self, *args, **kwargs) -> Any:
276
+ return self._dmp_wrapped_module(*args, **kwargs)
277
+
278
+ def init_data_parallel(self) -> None:
279
+ """
280
+ See init_data_parallel c-tor argument for usage.
281
+ It's safe to call this method multiple times.
282
+ """
283
+ if not self._ddp_wrapped:
284
+ # Allocate any 'meta' tensors
285
+ if self.init_parameters:
286
+ self._init_parameters(self._dmp_wrapped_module)
287
+ self._data_parallel_wrapper.wrap(self, self._env, self.device)
288
+ self._ddp_wrapped = True
289
+
290
+ def _copy(self, module: nn.Module, device: torch.device) -> nn.Module:
291
+ # Copy only weights with matching device.
292
+ def _copy_if_device_match(tensor: torch.Tensor) -> torch.Tensor:
293
+ if tensor.device == self.device:
294
+ return tensor.to(device)
295
+ else:
296
+ return tensor
297
+
298
+ # if this is a sharded module, customize the copy
299
+ if isinstance(module, ModuleCopyMixin):
300
+ return module.copy(device)
301
+ # this could be dense or a compound module
302
+ for name, child in module.named_children():
303
+ # potential DFS cache or bottom-up can save runtime
304
+ # search immediate submodules
305
+ if not any(
306
+ [
307
+ isinstance(submodule, ModuleCopyMixin)
308
+ for submodule in child.modules()
309
+ ]
310
+ ):
311
+ # if not containing ShardedModule down this submodule (this is a dense module)
312
+ # copy it.
313
+ child_copy = child._apply(_copy_if_device_match)
314
+ else:
315
+ # else this module contains a ShardedModule somewhere, recursively process it.
316
+ child_copy = self._copy(child, device)
317
+ setattr(module, name, child_copy)
318
+ return module
319
+
320
+ def copy(
321
+ self,
322
+ device: torch.device,
323
+ ) -> "DistributedModelParallel":
324
+ """
325
+ Recursively copy submodules to new device by calling per-module customized copy
326
+ process, since some modules needs to use the original references (like
327
+ `ShardedModule` for inference).
328
+ """
329
+ with sharded_model_copy(device=None):
330
+ copy_dmp = copy.deepcopy(self)
331
+ copy_module = copy_dmp._copy(copy_dmp.module, device)
332
+ copy_dmp.module = copy_module
333
+ return copy_dmp
334
+
335
+ def _init_dmp(
336
+ self,
337
+ fused_optims: List[Tuple[str, KeyedOptimizer]],
338
+ ) -> None:
339
+ self._shard_modules_impl(
340
+ self._dmp_wrapped_module,
341
+ "",
342
+ fused_optims,
343
+ )
344
+
345
+ def _shard_modules_impl(
346
+ self,
347
+ module: nn.Module,
348
+ path: str,
349
+ fused_optims: List[Tuple[str, KeyedOptimizer]],
350
+ ) -> None:
351
+ sharded_params = self._plan.get_plan_for_module(path)
352
+ if sharded_params:
353
+ sharder_key = sharder_name(type(module))
354
+ sharded_module = self._sharder_map[sharder_key].shard(
355
+ module,
356
+ sharded_params,
357
+ self._env,
358
+ self.device,
359
+ )
360
+ if path:
361
+ leaf_module = self._dmp_wrapped_module
362
+ split_path = path.split(".")
363
+ for name in split_path[:-1]:
364
+ leaf_module = getattr(leaf_module, name)
365
+ setattr(leaf_module, split_path[-1], sharded_module)
366
+ else:
367
+ self._dmp_wrapped_module = sharded_module
368
+ if isinstance(sharded_module, FusedOptimizerModule):
369
+ fused_optims.append((path, sharded_module.fused_optimizer))
370
+ else:
371
+ for name, child in module.named_children():
372
+ self._shard_modules_impl(
373
+ child,
374
+ path + "." + name if path else name,
375
+ fused_optims,
376
+ )
377
+
378
+ def _init_parameters(self, module: nn.Module) -> None:
379
+ @torch.no_grad()
380
+ def init_parameters(module: nn.Module) -> None:
381
+ # Allocate parameters and buffers if over 'meta' device.
382
+ has_meta_param = False
383
+ for name, param in module._parameters.items():
384
+ if isinstance(param, torch.Tensor) and param.device.type == "meta":
385
+ module._parameters[name] = nn.Parameter(
386
+ torch.empty_like(param, device=self.device),
387
+ requires_grad=param.requires_grad,
388
+ )
389
+ has_meta_param = True
390
+ for name, buffer in module._buffers.items():
391
+ if isinstance(buffer, torch.Tensor) and buffer.device.type == "meta":
392
+ module._buffers[name] = torch.empty_like(buffer, device=self.device)
393
+
394
+ # Init parameters if at least one parameter is over 'meta' device.
395
+ if has_meta_param and hasattr(module, "reset_parameters"):
396
+ # pyre-ignore [29]
397
+ module.reset_parameters()
398
+
399
+ module.apply(init_parameters)
400
+
401
+ def sparse_grad_parameter_names(
402
+ self, destination: Optional[List[str]] = None, prefix: str = ""
403
+ ) -> List[str]:
404
+ destination = [] if destination is None else destination
405
+ return self._sparse_grad_parameter_names(self.module, destination, prefix)
406
+
407
+ def _sparse_grad_parameter_names(
408
+ self, module: nn.Module, destination: List[str], prefix: str = ""
409
+ ) -> List[str]:
410
+ module = get_unwrapped_module(module)
411
+ if isinstance(module, ShardedModule):
412
+ module.sparse_grad_parameter_names(destination, prefix)
413
+ elif isinstance(module, nn.Embedding):
414
+ if module.sparse:
415
+ destination.append(append_prefix(prefix, "weight"))
416
+ elif isinstance(module, nn.EmbeddingBag):
417
+ if module.sparse:
418
+ destination.append(append_prefix(prefix, "weight"))
419
+ else:
420
+ for name, child in module.named_children():
421
+ self._sparse_grad_parameter_names(
422
+ child, destination, append_prefix(prefix, name)
423
+ )
424
+ return destination
425
+
426
+ # pyre-ignore [14]
427
+ def state_dict(
428
+ self,
429
+ destination: Optional[Dict[str, Any]] = None,
430
+ prefix: str = "",
431
+ keep_vars: bool = False,
432
+ ) -> Dict[str, Any]:
433
+ state_dict = get_module(self).state_dict(
434
+ destination=destination, prefix=prefix, keep_vars=keep_vars
435
+ )
436
+ torch.nn.modules.utils.consume_prefix_in_state_dict_if_present(
437
+ state_dict, prefix + _DDP_STATE_DICT_PREFIX
438
+ )
439
+ add_prefix_to_state_dict(state_dict, prefix)
440
+ return state_dict
441
+
442
+ # pyre-fixme[14]: `load_state_dict` overrides method defined in `Module`
443
+ # inconsistently.
444
+ def load_state_dict(
445
+ self,
446
+ state_dict: "OrderedDict[str, torch.Tensor]",
447
+ prefix: str = "",
448
+ strict: bool = True,
449
+ ) -> _IncompatibleKeys:
450
+ return self._load_state_dict(self, state_dict, prefix, strict)
451
+
452
+ def _load_state_dict(
453
+ self,
454
+ module: nn.Module,
455
+ state_dict: "OrderedDict[str, torch.Tensor]",
456
+ prefix: str = "",
457
+ strict: bool = True,
458
+ ) -> _IncompatibleKeys:
459
+ missing_keys = []
460
+ unexpected_keys = []
461
+ module = get_module(module)
462
+ if isinstance(module, DistributedDataParallel):
463
+ torch.nn.modules.utils.consume_prefix_in_state_dict_if_present(
464
+ state_dict, prefix
465
+ )
466
+ add_prefix_to_state_dict(state_dict, prefix + _DDP_STATE_DICT_PREFIX)
467
+ if isinstance(module, ShardedModule):
468
+ return module.load_state_dict(state_dict, strict=strict)
469
+ else:
470
+ module._load_from_state_dict(
471
+ state_dict, prefix, {}, strict, missing_keys, unexpected_keys, []
472
+ )
473
+ for name, child in module.named_children():
474
+ m_keys, u_keys = self._load_state_dict(
475
+ child,
476
+ filter_state_dict(state_dict, prefix + name),
477
+ "",
478
+ strict,
479
+ )
480
+ missing_keys.extend(m_keys)
481
+ unexpected_keys.extend(u_keys)
482
+ return _IncompatibleKeys(
483
+ missing_keys=missing_keys, unexpected_keys=unexpected_keys
484
+ )
485
+
486
+ def _named_parameters(
487
+ self,
488
+ module: nn.Module,
489
+ prefix: str = "",
490
+ recurse: bool = True,
491
+ strip_ddp: bool = True,
492
+ ) -> Iterator[Tuple[str, torch.nn.Parameter]]:
493
+ if strip_ddp:
494
+ module = get_unwrapped_module(module)
495
+ if isinstance(module, ShardedModule):
496
+ yield from module.named_parameters(prefix, recurse)
497
+ else:
498
+ yield from module.named_parameters(prefix, recurse=False)
499
+ for name, child in module.named_children():
500
+ yield from self._named_parameters(
501
+ child, append_prefix(prefix, name), recurse, strip_ddp
502
+ )
503
+
504
+ def named_parameters(
505
+ self, prefix: str = "", recurse: bool = True
506
+ ) -> Iterator[Tuple[str, torch.nn.Parameter]]:
507
+ yield from self._named_parameters(self.module, prefix, recurse)
508
+
509
+ def bare_named_parameters(
510
+ self, prefix: str = "", recurse: bool = True
511
+ ) -> Iterator[Tuple[str, torch.nn.Parameter]]:
512
+ yield from self._named_parameters(self.module, prefix, recurse, False)
513
+
514
+ @staticmethod
515
+ def _sharded_parameter_names(module: nn.Module, prefix: str = "") -> Iterator[str]:
516
+ module = get_unwrapped_module(module)
517
+ if isinstance(module, ShardedModule):
518
+ yield from module.sharded_parameter_names(prefix)
519
+ else:
520
+ for name, child in module.named_children():
521
+ yield from DistributedModelParallel._sharded_parameter_names(
522
+ child, append_prefix(prefix, name)
523
+ )
524
+
525
+ def _named_buffers(
526
+ self, module: nn.Module, prefix: str = "", recurse: bool = True
527
+ ) -> Iterator[Tuple[str, torch.Tensor]]:
528
+ module = get_unwrapped_module(module)
529
+ if isinstance(module, ShardedModule):
530
+ yield from module.named_buffers(prefix, recurse)
531
+ else:
532
+ yield from module.named_buffers(prefix, recurse=False)
533
+ for name, child in module.named_children():
534
+ yield from self._named_buffers(
535
+ child, append_prefix(prefix, name), recurse
536
+ )
537
+
538
+ def named_buffers(
539
+ self, prefix: str = "", recurse: bool = True
540
+ ) -> Iterator[Tuple[str, torch.Tensor]]:
541
+ yield from self._named_buffers(self.module, prefix, recurse)
542
+
543
+ @property
544
+ def fused_optimizer(self) -> KeyedOptimizer:
545
+ return self._optim
546
+
547
+ @property
548
+ def plan(self) -> ShardingPlan:
549
+ return self._plan
550
+
551
+ @staticmethod
552
+ def _reset_parameters(module: nn.Module) -> None:
553
+ for _, m in module.named_modules():
554
+ if hasattr(m, "reset_parameters"):
555
+ m.reset_parameters()
@@ -0,0 +1,24 @@
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
+ """Torchrec Planner
9
+
10
+ The planner provides the specifications necessary for a module to be sharded,
11
+ considering the possible options to build an optimized plan.
12
+
13
+ The features includes:
14
+ - generating all possible sharding options.
15
+ - estimating perf and storage for every shard.
16
+ - estimating peak memory usage to eliminate sharding plans that might OOM.
17
+ - customizability for parameter constraints, partitioning, proposers, or performance
18
+ modeling.
19
+ - automatically building and selecting an optimized sharding plan.
20
+ """
21
+
22
+ from torchrec.distributed.planner.planners import EmbeddingShardingPlanner # noqa
23
+ from torchrec.distributed.planner.types import ParameterConstraints, Topology # noqa
24
+ from torchrec.distributed.planner.utils import bytes_to_gb, sharder_name # noqa
@@ -0,0 +1,77 @@
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
+ from typing import Optional
9
+
10
+ from torchrec.distributed.embedding_types import EmbeddingComputeKernel
11
+
12
+ MAX_SIZE: int = (1 << 63) - 1
13
+
14
+ INTRA_NODE_BANDWIDTH: float = 600 * 1024 * 1024 * 1024 / 1000 # bytes/ms
15
+ CROSS_NODE_BANDWIDTH: float = 12.5 * 1024 * 1024 * 1024 / 1000 # bytes/ms
16
+
17
+ MIN_CW_DIM: int = 128
18
+ POOLING_FACTOR: float = 1.0
19
+
20
+ BIGINT_DTYPE: int = 8
21
+
22
+ HBM_CAP: int = 32 * 1024 * 1024 * 1024 # 32 GB
23
+ DDR_CAP: int = 128 * 1024 * 1024 * 1024 # 128 GB
24
+ DDR_MEM_BW: float = 51 * 1024 * 1024 * 1024 / 1000 # bytes/ms
25
+ HBM_MEM_BW: float = 897 * 1024 * 1024 * 1024 / 1000 # bytes/ms
26
+ UVM_CACHING_RATIO: float = 0.2
27
+ BATCH_SIZE: int = 512
28
+
29
+ BATCHED_COPY_PERF_FACTOR: float = 2.455 # empirical studies
30
+ FULL_BLOCK_EMB_DIM: int = 128 # FBGEMM Kernel, 32 threads X 4D-Vector
31
+ HALF_BLOCK_PENALTY: float = 1.15 # empirical studies
32
+ QUARTER_BLOCK_PENALTY: float = 1.75 # empirical studies
33
+ BWD_COMPUTE_MULTIPLIER: float = 2 # empirical studies
34
+ WEIGHTED_KERNEL_MULTIPLIER: float = 1.1 # empirical studies
35
+ DP_ELEMENTWISE_KERNELS_PERF_FACTOR: float = 9.22 # empirical studies
36
+
37
+
38
+ def kernel_bw_lookup(
39
+ compute_device: str,
40
+ compute_kernel: str,
41
+ caching_ratio: Optional[float] = None,
42
+ ) -> Optional[float]:
43
+ """
44
+ Calculates the device bandwidth based on given compute device, compute kernel, and
45
+ caching ratio.
46
+
47
+ Args:
48
+ compute_kernel (str): compute kernel.
49
+ compute_device (str): compute device.
50
+ caching_ratio (Optional[float]): caching ratio used to determine device bandwidth
51
+ if UVM caching is enabled.
52
+
53
+ Returns:
54
+ float: the device bandwidth.
55
+ """
56
+ caching_ratio = caching_ratio if caching_ratio else UVM_CACHING_RATIO
57
+ lookup = {
58
+ # CPU
59
+ ("cpu", EmbeddingComputeKernel.DENSE.value): 0.5 * DDR_MEM_BW,
60
+ ("cpu", EmbeddingComputeKernel.FUSED.value): 1 * DDR_MEM_BW,
61
+ ("cpu", EmbeddingComputeKernel.QUANT.value): 1 * DDR_MEM_BW,
62
+ # CUDA
63
+ ("cuda", EmbeddingComputeKernel.DENSE.value): 0.5 * HBM_MEM_BW,
64
+ ("cuda", EmbeddingComputeKernel.FUSED.value): 1 * HBM_MEM_BW,
65
+ ("cuda", EmbeddingComputeKernel.FUSED_UVM.value): DDR_MEM_BW / 10,
66
+ ("cuda", EmbeddingComputeKernel.FUSED_UVM_CACHING.value): (
67
+ caching_ratio * HBM_MEM_BW + (1 - caching_ratio) * DDR_MEM_BW
68
+ )
69
+ / 10,
70
+ ("cuda", EmbeddingComputeKernel.QUANT.value): 1 * HBM_MEM_BW,
71
+ ("cuda", EmbeddingComputeKernel.QUANT_UVM.value): DDR_MEM_BW / 10,
72
+ ("cuda", EmbeddingComputeKernel.QUANT_UVM_CACHING.value): (
73
+ caching_ratio * HBM_MEM_BW + (1 - caching_ratio) * DDR_MEM_BW
74
+ )
75
+ / 10,
76
+ }
77
+ return lookup.get((compute_device, compute_kernel))