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,288 @@
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 collections import OrderedDict
9
+ from typing import Any, Dict, List, Optional, Tuple, Type
10
+
11
+ import torch
12
+ from torch import nn
13
+ from torch.nn.modules.module import _IncompatibleKeys
14
+ from torchrec.distributed.embedding_sharding import (
15
+ EmbeddingSharding,
16
+ EmbeddingShardingInfo,
17
+ ListOfSparseFeaturesListAwaitable,
18
+ )
19
+ from torchrec.distributed.embedding_types import (
20
+ BaseQuantEmbeddingSharder,
21
+ ListOfSparseFeaturesList,
22
+ SparseFeatures,
23
+ SparseFeaturesList,
24
+ )
25
+ from torchrec.distributed.embeddingbag import (
26
+ create_sharding_infos_by_sharding,
27
+ EmbeddingBagCollectionAwaitable,
28
+ )
29
+ from torchrec.distributed.sharding.tw_sharding import InferTwEmbeddingSharding
30
+ from torchrec.distributed.types import (
31
+ Awaitable,
32
+ LazyAwaitable,
33
+ ParameterSharding,
34
+ ShardedModule,
35
+ ShardedModuleContext,
36
+ ShardingEnv,
37
+ ShardingType,
38
+ )
39
+ from torchrec.distributed.utils import filter_state_dict
40
+ from torchrec.modules.embedding_configs import (
41
+ data_type_to_sparse_type,
42
+ dtype_to_data_type,
43
+ )
44
+ from torchrec.modules.embedding_modules import EmbeddingBagCollectionInterface
45
+ from torchrec.quant.embedding_modules import (
46
+ EmbeddingBagCollection as QuantEmbeddingBagCollection,
47
+ )
48
+ from torchrec.sparse.jagged_tensor import KeyedJaggedTensor, KeyedTensor
49
+
50
+
51
+ def create_infer_embedding_bag_sharding(
52
+ sharding_type: str,
53
+ sharding_infos: List[EmbeddingShardingInfo],
54
+ env: ShardingEnv,
55
+ ) -> EmbeddingSharding[SparseFeaturesList, List[torch.Tensor]]:
56
+ if sharding_type == ShardingType.TABLE_WISE.value:
57
+ return InferTwEmbeddingSharding(sharding_infos, env, device=None)
58
+ else:
59
+ raise ValueError(f"Sharding type not supported {sharding_type}")
60
+
61
+
62
+ class ShardedQuantEmbeddingBagCollection(
63
+ ShardedModule[ListOfSparseFeaturesList, List[List[torch.Tensor]], KeyedTensor],
64
+ ):
65
+ """
66
+ Sharded implementation of `EmbeddingBagCollection`.
67
+ This is part of the public API to allow for manual data dist pipelining.
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ module: EmbeddingBagCollectionInterface,
73
+ table_name_to_parameter_sharding: Dict[str, ParameterSharding],
74
+ env: ShardingEnv,
75
+ fused_params: Optional[Dict[str, Any]] = None,
76
+ ) -> None:
77
+ super().__init__()
78
+ sharding_type_to_sharding_infos = create_sharding_infos_by_sharding(
79
+ module, table_name_to_parameter_sharding, "embedding_bags."
80
+ )
81
+ self._sharding_type_to_sharding: Dict[
82
+ str, EmbeddingSharding[SparseFeaturesList, List[torch.Tensor]]
83
+ ] = {
84
+ sharding_type: create_infer_embedding_bag_sharding(
85
+ sharding_type, embedding_confings, env
86
+ )
87
+ for sharding_type, embedding_confings in sharding_type_to_sharding_infos.items()
88
+ }
89
+
90
+ self._is_weighted: bool = module.is_weighted
91
+ self._input_dists: nn.ModuleList = nn.ModuleList()
92
+ self._lookups: nn.ModuleList = nn.ModuleList()
93
+ self._create_lookups(fused_params)
94
+ self._output_dists: nn.ModuleList = nn.ModuleList()
95
+ self._embedding_names: List[str] = []
96
+ self._embedding_dims: List[int] = []
97
+ self._feature_splits: List[int] = []
98
+ self._features_order: List[int] = []
99
+
100
+ # forward pass flow control
101
+ self._has_uninitialized_input_dist: bool = True
102
+ self._has_uninitialized_output_dist: bool = True
103
+ self._has_features_permute: bool = True
104
+
105
+ def _create_input_dist(
106
+ self,
107
+ input_feature_names: List[str],
108
+ device: torch.device,
109
+ ) -> None:
110
+ feature_names: List[str] = []
111
+ for sharding in self._sharding_type_to_sharding.values():
112
+ self._input_dists.append(sharding.create_input_dist())
113
+ feature_names.extend(
114
+ sharding.id_score_list_feature_names()
115
+ if self._is_weighted
116
+ else sharding.id_list_feature_names()
117
+ )
118
+ self._feature_splits.append(
119
+ len(
120
+ sharding.id_score_list_feature_names()
121
+ if self._is_weighted
122
+ else sharding.id_list_feature_names()
123
+ )
124
+ )
125
+
126
+ if feature_names == input_feature_names:
127
+ self._has_features_permute = False
128
+ else:
129
+ for f in feature_names:
130
+ self._features_order.append(input_feature_names.index(f))
131
+ self.register_buffer(
132
+ "_features_order_tensor",
133
+ torch.tensor(self._features_order, device=device, dtype=torch.int32),
134
+ )
135
+
136
+ def _create_lookups(
137
+ self,
138
+ fused_params: Optional[Dict[str, Any]],
139
+ ) -> None:
140
+ for sharding in self._sharding_type_to_sharding.values():
141
+ self._lookups.append(sharding.create_lookup(fused_params=fused_params))
142
+
143
+ def _create_output_dist(self, device: Optional[torch.device] = None) -> None:
144
+ for sharding in self._sharding_type_to_sharding.values():
145
+ self._output_dists.append(sharding.create_output_dist(device))
146
+ self._embedding_names.extend(sharding.embedding_names())
147
+ self._embedding_dims.extend(sharding.embedding_dims())
148
+
149
+ # pyre-ignore [14]
150
+ def input_dist(
151
+ self, ctx: ShardedModuleContext, features: KeyedJaggedTensor
152
+ ) -> Awaitable[ListOfSparseFeaturesList]:
153
+ if self._has_uninitialized_input_dist:
154
+ self._create_input_dist(features.keys(), features.device())
155
+ self._has_uninitialized_input_dist = False
156
+ if self._has_uninitialized_output_dist:
157
+ self._create_output_dist(features.device())
158
+ self._has_uninitialized_output_dist = False
159
+ with torch.no_grad():
160
+ if self._has_features_permute:
161
+ features = features.permute(
162
+ self._features_order,
163
+ # pyre-ignore [6]
164
+ self._features_order_tensor,
165
+ )
166
+ features_by_shards = features.split(
167
+ self._feature_splits,
168
+ )
169
+ awaitables = [
170
+ module(
171
+ SparseFeatures(
172
+ id_list_features=None
173
+ if self._is_weighted
174
+ else features_by_shard,
175
+ id_score_list_features=features_by_shard
176
+ if self._is_weighted
177
+ else None,
178
+ )
179
+ ).wait() # a dummy wait since now length indices comm is splited
180
+ for module, features_by_shard in zip(
181
+ self._input_dists, features_by_shards
182
+ )
183
+ ]
184
+ return ListOfSparseFeaturesListAwaitable(awaitables)
185
+
186
+ def compute(
187
+ self,
188
+ ctx: ShardedModuleContext,
189
+ dist_input: ListOfSparseFeaturesList,
190
+ ) -> List[List[torch.Tensor]]:
191
+ return [lookup(features) for lookup, features in zip(self._lookups, dist_input)]
192
+
193
+ def output_dist(
194
+ self,
195
+ ctx: ShardedModuleContext,
196
+ output: List[List[torch.Tensor]],
197
+ ) -> LazyAwaitable[KeyedTensor]:
198
+ return EmbeddingBagCollectionAwaitable(
199
+ awaitables=[
200
+ dist(embeddings) for dist, embeddings in zip(self._output_dists, output)
201
+ ],
202
+ embedding_dims=self._embedding_dims,
203
+ embedding_names=self._embedding_names,
204
+ )
205
+
206
+ def compute_and_output_dist(
207
+ self, ctx: ShardedModuleContext, input: ListOfSparseFeaturesList
208
+ ) -> LazyAwaitable[KeyedTensor]:
209
+ return EmbeddingBagCollectionAwaitable(
210
+ awaitables=[
211
+ dist(lookup(features))
212
+ for lookup, dist, features in zip(
213
+ self._lookups,
214
+ self._output_dists,
215
+ input,
216
+ )
217
+ ],
218
+ embedding_dims=self._embedding_dims,
219
+ embedding_names=self._embedding_names,
220
+ )
221
+
222
+ # pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently.
223
+ def state_dict(
224
+ self,
225
+ destination: Optional[Dict[str, Any]] = None,
226
+ prefix: str = "",
227
+ keep_vars: bool = False,
228
+ ) -> Dict[str, Any]:
229
+ if destination is None:
230
+ destination = OrderedDict()
231
+ # pyre-ignore [16]
232
+ destination._metadata = OrderedDict()
233
+ for lookup in self._lookups:
234
+ lookup.state_dict(destination, prefix + "embedding_bags.", keep_vars)
235
+ return destination
236
+
237
+ # pyre-fixme[14]: `load_state_dict` overrides method defined in `Module`
238
+ # inconsistently.
239
+ def load_state_dict(
240
+ self,
241
+ state_dict: "OrderedDict[str, torch.Tensor]",
242
+ strict: bool = True,
243
+ ) -> _IncompatibleKeys:
244
+ missing_keys = []
245
+ unexpected_keys = []
246
+ for lookup in self._lookups:
247
+ missing, unexpected = lookup.load_state_dict(
248
+ filter_state_dict(state_dict, "embedding_bags"),
249
+ strict,
250
+ )
251
+ missing_keys.extend(missing)
252
+ unexpected_keys.extend(unexpected)
253
+ return _IncompatibleKeys(
254
+ missing_keys=missing_keys, unexpected_keys=unexpected_keys
255
+ )
256
+
257
+ def copy(self, device: torch.device) -> nn.Module:
258
+ return self
259
+
260
+
261
+ class QuantEmbeddingBagCollectionSharder(
262
+ BaseQuantEmbeddingSharder[QuantEmbeddingBagCollection]
263
+ ):
264
+ def shard(
265
+ self,
266
+ module: QuantEmbeddingBagCollection,
267
+ params: Dict[str, ParameterSharding],
268
+ env: ShardingEnv,
269
+ device: Optional[torch.device] = None,
270
+ ) -> ShardedQuantEmbeddingBagCollection:
271
+ fused_params = self.fused_params if self.fused_params else {}
272
+ fused_params["output_dtype"] = data_type_to_sparse_type(
273
+ dtype_to_data_type(module.output_dtype)
274
+ )
275
+ return ShardedQuantEmbeddingBagCollection(module, params, env, fused_params)
276
+
277
+ def shardable_parameters(
278
+ self, module: QuantEmbeddingBagCollection
279
+ ) -> Dict[str, nn.Parameter]:
280
+ return {
281
+ name.split(".")[-2]: param
282
+ for name, param in module.state_dict().items()
283
+ if name.endswith(".weight")
284
+ }
285
+
286
+ @property
287
+ def module_type(self) -> Type[QuantEmbeddingBagCollection]:
288
+ return QuantEmbeddingBagCollection
File without changes
@@ -0,0 +1,71 @@
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 Any, Dict, Optional
9
+
10
+ import torch
11
+ from torchrec.distributed.embedding_lookup import GroupedEmbeddingsLookup
12
+ from torchrec.distributed.embedding_sharding import (
13
+ BaseEmbeddingLookup,
14
+ BaseSparseFeaturesDist,
15
+ )
16
+ from torchrec.distributed.embedding_types import (
17
+ BaseGroupedFeatureProcessor,
18
+ SparseFeatures,
19
+ )
20
+ from torchrec.distributed.sharding.cw_sharding import BaseCwEmbeddingSharding
21
+ from torchrec.distributed.sharding.sequence_sharding import BaseSequenceEmbeddingDist
22
+ from torchrec.distributed.sharding.tw_sequence_sharding import TwSequenceEmbeddingDist
23
+ from torchrec.distributed.sharding.tw_sharding import TwSparseFeaturesDist
24
+
25
+
26
+ class CwSequenceEmbeddingSharding(
27
+ BaseCwEmbeddingSharding[SparseFeatures, torch.Tensor]
28
+ ):
29
+ """
30
+ Shards sequence (unpooled) embeddings column-wise, i.e.. a given embedding is
31
+ partitioned along its columns and placed on specified ranks.
32
+ """
33
+
34
+ def create_input_dist(
35
+ self,
36
+ device: Optional[torch.device] = None,
37
+ ) -> BaseSparseFeaturesDist[SparseFeatures]:
38
+ return TwSparseFeaturesDist(
39
+ # pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
40
+ # `Optional[ProcessGroup]`.
41
+ self._pg,
42
+ self._id_list_features_per_rank(),
43
+ self._id_score_list_features_per_rank(),
44
+ device if device is not None else self._device,
45
+ )
46
+
47
+ def create_lookup(
48
+ self,
49
+ device: Optional[torch.device] = None,
50
+ fused_params: Optional[Dict[str, Any]] = None,
51
+ feature_processor: Optional[BaseGroupedFeatureProcessor] = None,
52
+ ) -> BaseEmbeddingLookup:
53
+ assert feature_processor is None
54
+ return GroupedEmbeddingsLookup(
55
+ grouped_configs=self._grouped_embedding_configs,
56
+ fused_params=fused_params,
57
+ pg=self._pg,
58
+ device=device if device is not None else self._device,
59
+ )
60
+
61
+ def create_output_dist(
62
+ self,
63
+ device: Optional[torch.device] = None,
64
+ ) -> BaseSequenceEmbeddingDist[torch.Tensor]:
65
+ return TwSequenceEmbeddingDist(
66
+ # pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
67
+ # `Optional[ProcessGroup]`.
68
+ self._pg,
69
+ self._id_list_features_per_rank(),
70
+ device if device is not None else self._device,
71
+ )
@@ -0,0 +1,242 @@
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 Any, Callable, Dict, List, Optional, Set, Tuple, TypeVar
9
+
10
+ import torch
11
+ import torch.distributed as dist # noqa
12
+ from fbgemm_gpu.permute_pooled_embedding_modules_split import (
13
+ PermutePooledEmbeddingsSplit,
14
+ )
15
+ from torchrec.distributed.embedding_lookup import GroupedPooledEmbeddingsLookup
16
+ from torchrec.distributed.embedding_sharding import (
17
+ BaseEmbeddingDist,
18
+ BaseEmbeddingLookup,
19
+ BaseSparseFeaturesDist,
20
+ EmbeddingShardingInfo,
21
+ )
22
+ from torchrec.distributed.embedding_types import (
23
+ BaseGroupedFeatureProcessor,
24
+ EmbeddingComputeKernel,
25
+ ShardedEmbeddingTable,
26
+ SparseFeatures,
27
+ )
28
+ from torchrec.distributed.sharding.tw_sharding import (
29
+ BaseTwEmbeddingSharding,
30
+ TwPooledEmbeddingDist,
31
+ TwSparseFeaturesDist,
32
+ )
33
+ from torchrec.distributed.types import ShardedTensorMetadata, ShardingEnv, ShardMetadata
34
+ from torchrec.streamable import Multistreamable
35
+
36
+ F = TypeVar("F", bound=Multistreamable)
37
+ T = TypeVar("T")
38
+
39
+
40
+ class BaseCwEmbeddingSharding(BaseTwEmbeddingSharding[F, T]):
41
+ """
42
+ Base class for column-wise sharding.
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ sharding_infos: List[EmbeddingShardingInfo],
48
+ env: ShardingEnv,
49
+ device: Optional[torch.device] = None,
50
+ permute_embeddings: bool = False,
51
+ ) -> None:
52
+ super().__init__(
53
+ sharding_infos,
54
+ env,
55
+ device,
56
+ )
57
+ self._permute_embeddings = permute_embeddings
58
+ if self._permute_embeddings:
59
+ self._init_combined_embeddings()
60
+
61
+ def _init_combined_embeddings(self) -> None:
62
+ """
63
+ Grabs the embedding names and dims from TwEmbeddingSharder.
64
+
65
+ NOTE:
66
+ This could have duplications if there are multiple shards from the same
67
+ table on a rank. Later on we process these to combine shards together.
68
+ """
69
+
70
+ embedding_names: List[str] = super().embedding_names()
71
+ embedding_dims: List[int] = super().embedding_dims()
72
+
73
+ embedding_shard_metadata: List[
74
+ Optional[ShardMetadata]
75
+ ] = super().embedding_shard_metadata()
76
+
77
+ embedding_name_to_index_offset_tuples: Dict[str, List[Tuple[int, int]]] = {}
78
+ for i, (name, metadata) in enumerate(
79
+ zip(embedding_names, embedding_shard_metadata)
80
+ ):
81
+ if name not in embedding_name_to_index_offset_tuples:
82
+ embedding_name_to_index_offset_tuples[name] = []
83
+ embedding_name_to_index_offset_tuples[name].append(
84
+ (i, metadata.shard_offsets[1] if metadata is not None else 0)
85
+ )
86
+
87
+ embedding_name_to_index: Dict[str, List[int]] = {}
88
+ for name, index_offset_tuples in embedding_name_to_index_offset_tuples.items():
89
+ embedding_name_to_index[name] = [
90
+ idx_off_tuple[0]
91
+ for idx_off_tuple in sorted(
92
+ index_offset_tuples,
93
+ key=lambda idx_off_tuple: idx_off_tuple[1],
94
+ )
95
+ ]
96
+
97
+ combined_embedding_names: List[str] = []
98
+ seen_embedding_names: Set[str] = set()
99
+
100
+ for name in embedding_names:
101
+ if name not in seen_embedding_names:
102
+ combined_embedding_names.append(name)
103
+ seen_embedding_names.add(name)
104
+
105
+ combined_embedding_dims: List[int] = []
106
+
107
+ embedding_order: List[int] = []
108
+ for name in combined_embedding_names:
109
+ combined_embedding_dims.append(
110
+ sum([embedding_dims[idx] for idx in embedding_name_to_index[name]])
111
+ )
112
+ embedding_order.extend(embedding_name_to_index[name])
113
+
114
+ self._embedding_names: List[str] = embedding_names
115
+ self._embedding_dims: List[int] = embedding_dims
116
+ self._embedding_order: List[int] = embedding_order
117
+
118
+ self._combined_embedding_names: List[str] = combined_embedding_names
119
+ self._combined_embedding_dims: List[int] = combined_embedding_dims
120
+
121
+ def _shard(
122
+ self,
123
+ sharding_infos: List[EmbeddingShardingInfo],
124
+ ) -> List[List[ShardedEmbeddingTable]]:
125
+ # pyre-fixme[16]: `Optional` has no attribute `size`.
126
+ world_size = self._pg.size()
127
+ tables_per_rank: List[List[ShardedEmbeddingTable]] = [
128
+ [] for i in range(world_size)
129
+ ]
130
+ for info in sharding_infos:
131
+ # pyre-fixme [16]
132
+ shards: List[ShardMetadata] = info.param_sharding.sharding_spec.shards
133
+
134
+ # construct the global sharded_tensor_metadata
135
+ global_metadata = ShardedTensorMetadata(
136
+ shards_metadata=shards,
137
+ size=torch.Size(
138
+ [
139
+ info.embedding_config.num_embeddings,
140
+ info.embedding_config.embedding_dim,
141
+ ]
142
+ ),
143
+ )
144
+
145
+ # pyre-fixme [6]
146
+ for i, rank in enumerate(info.param_sharding.ranks):
147
+ tables_per_rank[rank].append(
148
+ ShardedEmbeddingTable(
149
+ num_embeddings=info.embedding_config.num_embeddings,
150
+ embedding_dim=info.embedding_config.embedding_dim,
151
+ name=info.embedding_config.name,
152
+ embedding_names=info.embedding_config.embedding_names,
153
+ data_type=info.embedding_config.data_type,
154
+ feature_names=info.embedding_config.feature_names,
155
+ pooling=info.embedding_config.pooling,
156
+ is_weighted=info.embedding_config.is_weighted,
157
+ has_feature_processor=info.embedding_config.has_feature_processor,
158
+ local_rows=info.embedding_config.num_embeddings,
159
+ local_cols=shards[i].shard_sizes[1],
160
+ compute_kernel=EmbeddingComputeKernel(
161
+ info.param_sharding.compute_kernel
162
+ ),
163
+ local_metadata=shards[i],
164
+ global_metadata=global_metadata,
165
+ )
166
+ )
167
+
168
+ return tables_per_rank
169
+
170
+ def embedding_dims(self) -> List[int]:
171
+ return (
172
+ self._combined_embedding_dims
173
+ if self._permute_embeddings
174
+ else super().embedding_dims()
175
+ )
176
+
177
+ def embedding_names(self) -> List[str]:
178
+ return (
179
+ self._combined_embedding_names
180
+ if self._permute_embeddings
181
+ else super().embedding_names()
182
+ )
183
+
184
+
185
+ class CwPooledEmbeddingSharding(BaseCwEmbeddingSharding[SparseFeatures, torch.Tensor]):
186
+ """
187
+ Shards embedding bags column-wise, i.e.. a given embedding table is partitioned
188
+ along its columns and placed on specified ranks.
189
+ """
190
+
191
+ def create_input_dist(
192
+ self,
193
+ device: Optional[torch.device] = None,
194
+ ) -> BaseSparseFeaturesDist[SparseFeatures]:
195
+ return TwSparseFeaturesDist(
196
+ # pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
197
+ # `Optional[ProcessGroup]`.
198
+ self._pg,
199
+ self._id_list_features_per_rank(),
200
+ self._id_score_list_features_per_rank(),
201
+ device if device is not None else self._device,
202
+ )
203
+
204
+ def create_lookup(
205
+ self,
206
+ device: Optional[torch.device] = None,
207
+ fused_params: Optional[Dict[str, Any]] = None,
208
+ feature_processor: Optional[BaseGroupedFeatureProcessor] = None,
209
+ ) -> BaseEmbeddingLookup:
210
+ return GroupedPooledEmbeddingsLookup(
211
+ grouped_configs=self._grouped_embedding_configs,
212
+ grouped_score_configs=self._score_grouped_embedding_configs,
213
+ fused_params=fused_params,
214
+ pg=self._pg,
215
+ device=device if device is not None else self._device,
216
+ feature_processor=feature_processor,
217
+ )
218
+
219
+ def create_output_dist(
220
+ self,
221
+ device: Optional[torch.device] = None,
222
+ ) -> BaseEmbeddingDist[torch.Tensor]:
223
+ device = device if device is not None else self._device
224
+ embedding_permute_op: Optional[PermutePooledEmbeddingsSplit] = None
225
+ callbacks: Optional[List[Callable[[torch.Tensor], torch.Tensor]]] = None
226
+ if self._permute_embeddings and self._embedding_order != list(
227
+ range(len(self._embedding_order))
228
+ ):
229
+ assert len(self._embedding_order) == len(self._embedding_dims)
230
+ embedding_permute_op = PermutePooledEmbeddingsSplit(
231
+ self._embedding_dims,
232
+ self._embedding_order,
233
+ ).to(device=device)
234
+ callbacks = [embedding_permute_op]
235
+ return TwPooledEmbeddingDist(
236
+ # pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
237
+ # `Optional[ProcessGroup]`.
238
+ self._pg,
239
+ self._dim_sum_per_rank(),
240
+ device,
241
+ callbacks,
242
+ )
@@ -0,0 +1,87 @@
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 Any, Dict, Optional
9
+
10
+ import torch
11
+ from torchrec.distributed.embedding_lookup import GroupedEmbeddingsLookup
12
+ from torchrec.distributed.embedding_sharding import (
13
+ BaseEmbeddingLookup,
14
+ BaseSparseFeaturesDist,
15
+ )
16
+ from torchrec.distributed.embedding_types import (
17
+ BaseGroupedFeatureProcessor,
18
+ SparseFeatures,
19
+ )
20
+ from torchrec.distributed.sharding.dp_sharding import (
21
+ BaseDpEmbeddingSharding,
22
+ DpSparseFeaturesDist,
23
+ )
24
+ from torchrec.distributed.sharding.sequence_sharding import (
25
+ BaseSequenceEmbeddingDist,
26
+ SequenceShardingContext,
27
+ )
28
+ from torchrec.distributed.types import Awaitable, NoWait
29
+
30
+
31
+ class DpSequenceEmbeddingDist(BaseSequenceEmbeddingDist[torch.Tensor]):
32
+ """
33
+ Distributes sequence embeddings to be data-parallel.
34
+ """
35
+
36
+ def __init__(self) -> None:
37
+ super().__init__()
38
+
39
+ def forward(
40
+ self,
41
+ local_embs: torch.Tensor,
42
+ sharding_ctx: SequenceShardingContext,
43
+ ) -> Awaitable[torch.Tensor]:
44
+ """
45
+ No-op as sequence embeddings are already distributed in data-parallel fashion.
46
+
47
+ Args:
48
+ local_embs (torch.Tensor): output sequence embeddings.
49
+
50
+ Returns:
51
+ Awaitable[torch.Tensor]: awaitable of pooled embeddings tensor.
52
+ """
53
+
54
+ return NoWait(local_embs)
55
+
56
+
57
+ class DpSequenceEmbeddingSharding(
58
+ BaseDpEmbeddingSharding[SparseFeatures, torch.Tensor]
59
+ ):
60
+ """
61
+ Shards sequence (unpooled) embedding data-parallel, with no table sharding i.e.. a
62
+ given embedding table is replicated across all ranks.
63
+ """
64
+
65
+ def create_input_dist(
66
+ self, device: Optional[torch.device] = None
67
+ ) -> BaseSparseFeaturesDist[SparseFeatures]:
68
+ return DpSparseFeaturesDist()
69
+
70
+ def create_lookup(
71
+ self,
72
+ device: Optional[torch.device] = None,
73
+ fused_params: Optional[Dict[str, Any]] = None,
74
+ feature_processor: Optional[BaseGroupedFeatureProcessor] = None,
75
+ ) -> BaseEmbeddingLookup:
76
+ assert feature_processor is None
77
+ return GroupedEmbeddingsLookup(
78
+ grouped_configs=self._grouped_embedding_configs,
79
+ fused_params=fused_params,
80
+ pg=self._env.process_group,
81
+ device=device if device is not None else self._device,
82
+ )
83
+
84
+ def create_output_dist(
85
+ self, device: Optional[torch.device] = None
86
+ ) -> BaseSequenceEmbeddingDist[torch.Tensor]:
87
+ return DpSequenceEmbeddingDist()