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,469 @@
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, TypeVar
9
+
10
+ import torch
11
+ import torch.distributed as dist
12
+ from torchrec.distributed.dist_data import EmbeddingsAllToOne, PooledEmbeddingsAllToAll
13
+ from torchrec.distributed.embedding_lookup import (
14
+ GroupedPooledEmbeddingsLookup,
15
+ InferGroupedPooledEmbeddingsLookup,
16
+ )
17
+ from torchrec.distributed.embedding_sharding import (
18
+ BaseEmbeddingDist,
19
+ BaseEmbeddingLookup,
20
+ BaseSparseFeaturesDist,
21
+ EmbeddingSharding,
22
+ EmbeddingShardingInfo,
23
+ group_tables,
24
+ SparseFeaturesAllToAll,
25
+ SparseFeaturesOneToAll,
26
+ )
27
+ from torchrec.distributed.embedding_types import (
28
+ BaseGroupedFeatureProcessor,
29
+ EmbeddingComputeKernel,
30
+ GroupedEmbeddingConfig,
31
+ ShardedEmbeddingTable,
32
+ SparseFeatures,
33
+ SparseFeaturesList,
34
+ )
35
+ from torchrec.distributed.types import (
36
+ Awaitable,
37
+ NoWait,
38
+ ShardedTensorMetadata,
39
+ ShardingEnv,
40
+ ShardMetadata,
41
+ )
42
+ from torchrec.streamable import Multistreamable
43
+
44
+
45
+ F = TypeVar("F", bound=Multistreamable)
46
+ T = TypeVar("T")
47
+
48
+
49
+ class BaseTwEmbeddingSharding(EmbeddingSharding[F, T]):
50
+ """
51
+ Base class for table wise sharding.
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ sharding_infos: List[EmbeddingShardingInfo],
57
+ env: ShardingEnv,
58
+ device: Optional[torch.device] = None,
59
+ ) -> None:
60
+ super().__init__()
61
+ self._env = env
62
+ self._device = device
63
+ self._pg: Optional[dist.ProcessGroup] = self._env.process_group
64
+ self._world_size: int = self._env.world_size
65
+ self._rank: int = self._env.rank
66
+ sharded_tables_per_rank = self._shard(sharding_infos)
67
+ self._grouped_embedding_configs_per_rank: List[
68
+ List[GroupedEmbeddingConfig]
69
+ ] = []
70
+ self._score_grouped_embedding_configs_per_rank: List[
71
+ List[GroupedEmbeddingConfig]
72
+ ] = []
73
+ (
74
+ self._grouped_embedding_configs_per_rank,
75
+ self._score_grouped_embedding_configs_per_rank,
76
+ ) = group_tables(sharded_tables_per_rank)
77
+ self._grouped_embedding_configs: List[
78
+ GroupedEmbeddingConfig
79
+ ] = self._grouped_embedding_configs_per_rank[self._rank]
80
+ self._score_grouped_embedding_configs: List[
81
+ GroupedEmbeddingConfig
82
+ ] = self._score_grouped_embedding_configs_per_rank[self._rank]
83
+
84
+ def _shard(
85
+ self,
86
+ sharding_infos: List[EmbeddingShardingInfo],
87
+ ) -> List[List[ShardedEmbeddingTable]]:
88
+ world_size = self._world_size
89
+ tables_per_rank: List[List[ShardedEmbeddingTable]] = [
90
+ [] for i in range(world_size)
91
+ ]
92
+ for info in sharding_infos:
93
+ # pyre-fixme [16]
94
+ shards = info.param_sharding.sharding_spec.shards
95
+ # construct the global sharded_tensor_metadata
96
+ global_metadata = ShardedTensorMetadata(
97
+ shards_metadata=shards,
98
+ size=torch.Size(
99
+ [
100
+ info.embedding_config.num_embeddings,
101
+ info.embedding_config.embedding_dim,
102
+ ]
103
+ ),
104
+ )
105
+
106
+ # pyre-fixme [16]
107
+ tables_per_rank[info.param_sharding.ranks[0]].append(
108
+ ShardedEmbeddingTable(
109
+ num_embeddings=info.embedding_config.num_embeddings,
110
+ embedding_dim=info.embedding_config.embedding_dim,
111
+ name=info.embedding_config.name,
112
+ embedding_names=info.embedding_config.embedding_names,
113
+ data_type=info.embedding_config.data_type,
114
+ feature_names=info.embedding_config.feature_names,
115
+ pooling=info.embedding_config.pooling,
116
+ is_weighted=info.embedding_config.is_weighted,
117
+ has_feature_processor=info.embedding_config.has_feature_processor,
118
+ local_rows=info.embedding_config.num_embeddings,
119
+ local_cols=info.embedding_config.embedding_dim,
120
+ compute_kernel=EmbeddingComputeKernel(
121
+ info.param_sharding.compute_kernel
122
+ ),
123
+ local_metadata=shards[0],
124
+ global_metadata=global_metadata,
125
+ weight_init_max=info.embedding_config.weight_init_max,
126
+ weight_init_min=info.embedding_config.weight_init_min,
127
+ )
128
+ )
129
+ return tables_per_rank
130
+
131
+ def _dim_sum_per_rank(self) -> List[int]:
132
+ dim_sum_per_rank = []
133
+ for grouped_embedding_configs, score_grouped_embedding_configs in zip(
134
+ self._grouped_embedding_configs_per_rank,
135
+ self._score_grouped_embedding_configs_per_rank,
136
+ ):
137
+ dim_sum = 0
138
+ for grouped_config in grouped_embedding_configs:
139
+ dim_sum += grouped_config.dim_sum()
140
+ for grouped_config in score_grouped_embedding_configs:
141
+ dim_sum += grouped_config.dim_sum()
142
+ dim_sum_per_rank.append(dim_sum)
143
+ return dim_sum_per_rank
144
+
145
+ def embedding_dims(self) -> List[int]:
146
+ embedding_dims = []
147
+ for grouped_embedding_configs, score_grouped_embedding_configs in zip(
148
+ self._grouped_embedding_configs_per_rank,
149
+ self._score_grouped_embedding_configs_per_rank,
150
+ ):
151
+ for grouped_config in grouped_embedding_configs:
152
+ embedding_dims.extend(grouped_config.embedding_dims())
153
+ for grouped_config in score_grouped_embedding_configs:
154
+ embedding_dims.extend(grouped_config.embedding_dims())
155
+ return embedding_dims
156
+
157
+ def embedding_names(self) -> List[str]:
158
+ embedding_names = []
159
+ for grouped_embedding_configs, score_grouped_embedding_configs in zip(
160
+ self._grouped_embedding_configs_per_rank,
161
+ self._score_grouped_embedding_configs_per_rank,
162
+ ):
163
+ for grouped_config in grouped_embedding_configs:
164
+ embedding_names.extend(grouped_config.embedding_names())
165
+ for grouped_config in score_grouped_embedding_configs:
166
+ embedding_names.extend(grouped_config.embedding_names())
167
+ return embedding_names
168
+
169
+ def embedding_shard_metadata(self) -> List[Optional[ShardMetadata]]:
170
+ embedding_shard_metadata = []
171
+ for grouped_embedding_configs, score_grouped_embedding_configs in zip(
172
+ self._grouped_embedding_configs_per_rank,
173
+ self._score_grouped_embedding_configs_per_rank,
174
+ ):
175
+ for grouped_config in grouped_embedding_configs:
176
+ embedding_shard_metadata.extend(
177
+ grouped_config.embedding_shard_metadata()
178
+ )
179
+ for grouped_config in score_grouped_embedding_configs:
180
+ embedding_shard_metadata.extend(
181
+ grouped_config.embedding_shard_metadata()
182
+ )
183
+ return embedding_shard_metadata
184
+
185
+ def id_list_feature_names(self) -> List[str]:
186
+ id_list_feature_names = []
187
+ for grouped_embedding_configs in self._grouped_embedding_configs_per_rank:
188
+ for grouped_config in grouped_embedding_configs:
189
+ id_list_feature_names.extend(grouped_config.feature_names())
190
+ return id_list_feature_names
191
+
192
+ def id_score_list_feature_names(self) -> List[str]:
193
+ id_score_list_feature_names = []
194
+ for (
195
+ score_grouped_embedding_configs
196
+ ) in self._score_grouped_embedding_configs_per_rank:
197
+ for grouped_config in score_grouped_embedding_configs:
198
+ id_score_list_feature_names.extend(grouped_config.feature_names())
199
+ return id_score_list_feature_names
200
+
201
+ def _id_list_features_per_rank(self) -> List[int]:
202
+ id_list_features_per_rank = []
203
+ for grouped_embedding_configs in self._grouped_embedding_configs_per_rank:
204
+ num_features = 0
205
+ for grouped_config in grouped_embedding_configs:
206
+ num_features += grouped_config.num_features()
207
+ id_list_features_per_rank.append(num_features)
208
+ return id_list_features_per_rank
209
+
210
+ def _id_score_list_features_per_rank(self) -> List[int]:
211
+ id_score_list_features_per_rank = []
212
+ for (
213
+ score_grouped_embedding_configs
214
+ ) in self._score_grouped_embedding_configs_per_rank:
215
+ num_features = 0
216
+ for grouped_config in score_grouped_embedding_configs:
217
+ num_features += grouped_config.num_features()
218
+ id_score_list_features_per_rank.append(num_features)
219
+ return id_score_list_features_per_rank
220
+
221
+
222
+ class TwSparseFeaturesDist(BaseSparseFeaturesDist[SparseFeatures]):
223
+ """
224
+ Redistributes sparse features with an AlltoAll collective operation for table wise
225
+ sharding.
226
+
227
+ Args:
228
+ pg (dist.ProcessGroup): ProcessGroup for AlltoAll communication.
229
+ id_list_features_per_rank (List[int]): number of id list features to send to
230
+ each rank.
231
+ id_score_list_features_per_rank (List[int]): number of id score list features to
232
+ send to each rank.
233
+ device (Optional[torch.device]): device on which buffers will be allocated.
234
+ """
235
+
236
+ def __init__(
237
+ self,
238
+ pg: dist.ProcessGroup,
239
+ id_list_features_per_rank: List[int],
240
+ id_score_list_features_per_rank: List[int],
241
+ device: Optional[torch.device] = None,
242
+ ) -> None:
243
+ super().__init__()
244
+ self._dist = SparseFeaturesAllToAll(
245
+ pg=pg,
246
+ id_list_features_per_rank=id_list_features_per_rank,
247
+ id_score_list_features_per_rank=id_score_list_features_per_rank,
248
+ device=device,
249
+ )
250
+
251
+ def forward(
252
+ self,
253
+ sparse_features: SparseFeatures,
254
+ ) -> Awaitable[Awaitable[SparseFeatures]]:
255
+ """
256
+ Performs AlltoAll operation on sparse features.
257
+
258
+ Args:
259
+ sparse_features (SparseFeatures): sparse features to redistribute.
260
+
261
+ Returns:
262
+ Awaitable[Awaitable[SparseFeatures]]: awaitable of awaitable of SparseFeatures.
263
+ """
264
+
265
+ return self._dist(sparse_features)
266
+
267
+
268
+ class TwPooledEmbeddingDist(BaseEmbeddingDist[torch.Tensor]):
269
+ """
270
+ Redistributes pooled embedding tensor with an AlltoAll collective operation for
271
+ table wise sharding.
272
+
273
+ Args:
274
+ pg (dist.ProcessGroup): ProcessGroup for AlltoAll communication.
275
+ dim_sum_per_rank (List[int]): number of features (sum of dimensions) of the
276
+ embedding in each rank.
277
+ device (Optional[torch.device]): device on which buffers will be allocated.
278
+ """
279
+
280
+ def __init__(
281
+ self,
282
+ pg: dist.ProcessGroup,
283
+ dim_sum_per_rank: List[int],
284
+ device: Optional[torch.device] = None,
285
+ callbacks: Optional[List[Callable[[torch.Tensor], torch.Tensor]]] = None,
286
+ ) -> None:
287
+ super().__init__()
288
+ self._dist = PooledEmbeddingsAllToAll(pg, dim_sum_per_rank, device, callbacks)
289
+
290
+ def forward(
291
+ self,
292
+ local_embs: torch.Tensor,
293
+ ) -> Awaitable[torch.Tensor]:
294
+ """
295
+ Performs AlltoAll operation on pooled embeddings tensor.
296
+
297
+ Args:
298
+ local_embs (torch.Tensor): tensor of values to distribute.
299
+
300
+ Returns:
301
+ Awaitable[torch.Tensor]: awaitable of pooled embeddings.
302
+ """
303
+
304
+ return self._dist(local_embs)
305
+
306
+
307
+ class TwPooledEmbeddingSharding(BaseTwEmbeddingSharding[SparseFeatures, torch.Tensor]):
308
+ """
309
+ Shards embedding bags table-wise, i.e.. a given embedding table is entirely placed
310
+ on a selected rank.
311
+ """
312
+
313
+ def create_input_dist(
314
+ self,
315
+ device: Optional[torch.device] = None,
316
+ ) -> BaseSparseFeaturesDist[SparseFeatures]:
317
+ return TwSparseFeaturesDist(
318
+ # pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
319
+ # `Optional[ProcessGroup]`.
320
+ self._pg,
321
+ self._id_list_features_per_rank(),
322
+ self._id_score_list_features_per_rank(),
323
+ device if device is not None else self._device,
324
+ )
325
+
326
+ def create_lookup(
327
+ self,
328
+ device: Optional[torch.device] = None,
329
+ fused_params: Optional[Dict[str, Any]] = None,
330
+ feature_processor: Optional[BaseGroupedFeatureProcessor] = None,
331
+ ) -> BaseEmbeddingLookup:
332
+ return GroupedPooledEmbeddingsLookup(
333
+ grouped_configs=self._grouped_embedding_configs,
334
+ grouped_score_configs=self._score_grouped_embedding_configs,
335
+ fused_params=fused_params,
336
+ pg=self._pg,
337
+ device=device if device is not None else self._device,
338
+ feature_processor=feature_processor,
339
+ )
340
+
341
+ def create_output_dist(
342
+ self,
343
+ device: Optional[torch.device] = None,
344
+ ) -> BaseEmbeddingDist[torch.Tensor]:
345
+ return TwPooledEmbeddingDist(
346
+ # pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
347
+ # `Optional[ProcessGroup]`.
348
+ self._pg,
349
+ self._dim_sum_per_rank(),
350
+ device if device is not None else self._device,
351
+ )
352
+
353
+
354
+ class InferTwSparseFeaturesDist(BaseSparseFeaturesDist[SparseFeaturesList]):
355
+ """
356
+ Redistributes sparse features to all devices for inference.
357
+
358
+ Args:
359
+ id_list_features_per_rank (List[int]): number of id list features to send
360
+ to each rank.
361
+ id_score_list_features_per_rank (List[int]): number of id score list features
362
+ to send to each rank.
363
+ world_size (int): number of devices in the topology.
364
+ """
365
+
366
+ def __init__(
367
+ self,
368
+ id_list_features_per_rank: List[int],
369
+ id_score_list_features_per_rank: List[int],
370
+ world_size: int,
371
+ ) -> None:
372
+ super().__init__()
373
+ self._dist: SparseFeaturesOneToAll = SparseFeaturesOneToAll(
374
+ id_list_features_per_rank,
375
+ id_score_list_features_per_rank,
376
+ world_size,
377
+ )
378
+
379
+ def forward(
380
+ self,
381
+ sparse_features: SparseFeatures,
382
+ ) -> Awaitable[Awaitable[SparseFeaturesList]]:
383
+ """
384
+ Performs OnetoAll operation on sparse features.
385
+
386
+ Args:
387
+ sparse_features (SparseFeatures): sparse features to redistribute.
388
+
389
+ Returns:
390
+ Awaitable[Awaitable[SparseFeatures]]: awaitable of awaitable of SparseFeatures.
391
+ """
392
+
393
+ return NoWait(self._dist.forward(sparse_features))
394
+
395
+
396
+ class InferTwPooledEmbeddingDist(BaseEmbeddingDist[List[torch.Tensor]]):
397
+ """
398
+ Merges pooled embedding tensor from each device for inference.
399
+
400
+ Args:
401
+ device (Optional[torch.device]): device on which buffer will be allocated.
402
+ world_size (int): number of devices in the topology.
403
+ """
404
+
405
+ def __init__(
406
+ self,
407
+ device: torch.device,
408
+ world_size: int,
409
+ ) -> None:
410
+ super().__init__()
411
+ self._dist: EmbeddingsAllToOne = EmbeddingsAllToOne(device, world_size, 1)
412
+
413
+ def forward(
414
+ self,
415
+ local_embs: List[torch.Tensor],
416
+ ) -> Awaitable[torch.Tensor]:
417
+ """
418
+ Performs AlltoOne operation on pooled embedding tensors.
419
+
420
+ Args:
421
+ local_embs (List[torch.Tensor]): pooled embedding tensors with
422
+ `len(local_embs) == world_size`.
423
+
424
+ Returns:
425
+ Awaitable[torch.Tensor]: awaitable of merged pooled embedding tensor.
426
+ """
427
+
428
+ return self._dist.forward(local_embs)
429
+
430
+
431
+ class InferTwEmbeddingSharding(
432
+ BaseTwEmbeddingSharding[SparseFeaturesList, List[torch.Tensor]]
433
+ ):
434
+ """
435
+ Shards embedding bags table-wise for inference
436
+ """
437
+
438
+ def create_input_dist(
439
+ self, device: Optional[torch.device] = None
440
+ ) -> BaseSparseFeaturesDist[SparseFeaturesList]:
441
+ return InferTwSparseFeaturesDist(
442
+ self._id_list_features_per_rank(),
443
+ self._id_score_list_features_per_rank(),
444
+ self._world_size,
445
+ )
446
+
447
+ def create_lookup(
448
+ self,
449
+ device: Optional[torch.device] = None,
450
+ fused_params: Optional[Dict[str, Any]] = None,
451
+ feature_processor: Optional[BaseGroupedFeatureProcessor] = None,
452
+ ) -> BaseEmbeddingLookup[SparseFeaturesList, List[torch.Tensor]]:
453
+ return InferGroupedPooledEmbeddingsLookup(
454
+ grouped_configs_per_rank=self._grouped_embedding_configs_per_rank,
455
+ grouped_score_configs_per_rank=self._score_grouped_embedding_configs_per_rank,
456
+ world_size=self._world_size,
457
+ fused_params=fused_params,
458
+ )
459
+
460
+ def create_output_dist(
461
+ self,
462
+ device: Optional[torch.device] = None,
463
+ ) -> BaseEmbeddingDist[List[torch.Tensor]]:
464
+ device = device if device is not None else self._device
465
+ return InferTwPooledEmbeddingDist(
466
+ # pyre-fixme [6]
467
+ device,
468
+ self._world_size,
469
+ )
@@ -0,0 +1,32 @@
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 List, Optional
9
+
10
+ import torch
11
+ from torchrec.distributed.embedding_sharding import EmbeddingShardingInfo
12
+ from torchrec.distributed.sharding.cw_sharding import CwPooledEmbeddingSharding
13
+ from torchrec.distributed.types import ShardingEnv
14
+
15
+
16
+ class TwCwPooledEmbeddingSharding(CwPooledEmbeddingSharding):
17
+ """
18
+ Shards embedding bags table-wise column-wise, i.e.. a given embedding table is
19
+ partitioned along its columns and the table slices are placed on all ranks
20
+ within a host group.
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ sharding_infos: List[EmbeddingShardingInfo],
26
+ env: ShardingEnv,
27
+ device: Optional[torch.device] = None,
28
+ permute_embeddings: bool = False,
29
+ ) -> None:
30
+ super().__init__(
31
+ sharding_infos, env, device, permute_embeddings=permute_embeddings
32
+ )