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,388 @@
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
+ #!/usr/bin/env python3
9
+
10
+ import itertools
11
+ import math
12
+ from typing import Any, cast, Dict, List, Optional, Tuple
13
+
14
+ import torch
15
+ import torch.distributed as dist
16
+ from torchrec.distributed.dist_data import (
17
+ PooledEmbeddingsAllToAll,
18
+ PooledEmbeddingsReduceScatter,
19
+ )
20
+ from torchrec.distributed.embedding_lookup import GroupedPooledEmbeddingsLookup
21
+ from torchrec.distributed.embedding_sharding import (
22
+ BaseEmbeddingDist,
23
+ BaseEmbeddingLookup,
24
+ BaseSparseFeaturesDist,
25
+ bucketize_kjt_before_all2all,
26
+ SparseFeaturesAllToAll,
27
+ )
28
+ from torchrec.distributed.embedding_types import (
29
+ BaseGroupedFeatureProcessor,
30
+ SparseFeatures,
31
+ )
32
+ from torchrec.distributed.sharding.twrw_sharding import BaseTwRwEmbeddingSharding
33
+ from torchrec.distributed.sharding.vb_sharding import (
34
+ BaseVariableBatchEmbeddingDist,
35
+ VariableBatchShardingContext,
36
+ )
37
+ from torchrec.distributed.types import Awaitable
38
+
39
+ torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops")
40
+ torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops_cpu")
41
+
42
+
43
+ class VariableBatchTwRwSparseFeaturesDist(BaseSparseFeaturesDist[SparseFeatures]):
44
+ """
45
+ Bucketizes sparse features in TWRW fashion and then redistributes with an AlltoAll
46
+ collective operation.
47
+
48
+ Supports variable batch size.
49
+
50
+ Args:
51
+ pg (dist.ProcessGroup): ProcessGroup for AlltoAll communication.
52
+ intra_pg (dist.ProcessGroup): ProcessGroup within single host group for AlltoAll
53
+ communication.
54
+ id_list_features_per_rank (List[int]): number of id list features to send to
55
+ each rank.
56
+ id_score_list_features_per_rank (List[int]): number of id score list features to
57
+ send to each rank
58
+ id_list_feature_hash_sizes (List[int]): hash sizes of id list features.
59
+ id_score_list_feature_hash_sizes (List[int]): hash sizes of id score list
60
+ features.
61
+ device (Optional[torch.device]): device on which buffers will be allocated.
62
+ has_feature_processor (bool): existence of feature processor (ie. position
63
+ weighted features).
64
+
65
+ Example::
66
+
67
+ 3 features
68
+ 2 hosts with 2 devices each
69
+
70
+ Bucketize each feature into 2 buckets
71
+ Staggered shuffle with feature splits [2, 1]
72
+ AlltoAll operation
73
+
74
+ NOTE: result of staggered shuffle and AlltoAll operation look the same after
75
+ reordering in AlltoAll
76
+
77
+ Result:
78
+ host 0 device 0:
79
+ feature 0 bucket 0
80
+ feature 1 bucket 0
81
+
82
+ host 0 device 1:
83
+ feature 0 bucket 1
84
+ feature 1 bucket 1
85
+
86
+ host 1 device 0:
87
+ feature 2 bucket 0
88
+
89
+ host 1 device 1:
90
+ feature 2 bucket 1
91
+ """
92
+
93
+ def __init__(
94
+ self,
95
+ pg: dist.ProcessGroup,
96
+ intra_pg: dist.ProcessGroup,
97
+ id_list_features_per_rank: List[int],
98
+ id_score_list_features_per_rank: List[int],
99
+ id_list_feature_hash_sizes: List[int],
100
+ id_score_list_feature_hash_sizes: List[int],
101
+ device: Optional[torch.device] = None,
102
+ has_feature_processor: bool = False,
103
+ ) -> None:
104
+ super().__init__()
105
+ assert (
106
+ pg.size() % intra_pg.size() == 0
107
+ ), "currently group granularity must be node"
108
+
109
+ self._world_size: int = pg.size()
110
+ self._local_size: int = intra_pg.size()
111
+ self._num_cross_nodes: int = self._world_size // self._local_size
112
+ id_list_feature_block_sizes = [
113
+ math.ceil(hash_size / self._local_size)
114
+ for hash_size in id_list_feature_hash_sizes
115
+ ]
116
+ id_score_list_feature_block_sizes = [
117
+ math.ceil(hash_size / self._local_size)
118
+ for hash_size in id_score_list_feature_hash_sizes
119
+ ]
120
+
121
+ self._id_list_sf_staggered_shuffle: List[int] = self._staggered_shuffle(
122
+ id_list_features_per_rank
123
+ )
124
+ self._id_score_list_sf_staggered_shuffle: List[int] = self._staggered_shuffle(
125
+ id_score_list_features_per_rank
126
+ )
127
+ self.register_buffer(
128
+ "_id_list_feature_block_sizes_tensor",
129
+ torch.tensor(
130
+ id_list_feature_block_sizes,
131
+ device=device,
132
+ dtype=torch.int32,
133
+ ),
134
+ )
135
+ self.register_buffer(
136
+ "_id_score_list_feature_block_sizes_tensor",
137
+ torch.tensor(
138
+ id_score_list_feature_block_sizes,
139
+ device=device,
140
+ dtype=torch.int32,
141
+ ),
142
+ )
143
+ self.register_buffer(
144
+ "_id_list_sf_staggered_shuffle_tensor",
145
+ torch.tensor(
146
+ self._id_list_sf_staggered_shuffle,
147
+ device=device,
148
+ dtype=torch.int32,
149
+ ),
150
+ )
151
+ self.register_buffer(
152
+ "_id_score_list_sf_staggered_shuffle_tensor",
153
+ torch.tensor(
154
+ self._id_score_list_sf_staggered_shuffle,
155
+ device=device,
156
+ dtype=torch.int32,
157
+ ),
158
+ )
159
+ self._dist = SparseFeaturesAllToAll(
160
+ pg=pg,
161
+ id_list_features_per_rank=id_list_features_per_rank,
162
+ id_score_list_features_per_rank=id_score_list_features_per_rank,
163
+ device=device,
164
+ stagger=self._num_cross_nodes,
165
+ variable_batch_size=True,
166
+ )
167
+ self._has_feature_processor = has_feature_processor
168
+
169
+ def forward(
170
+ self,
171
+ sparse_features: SparseFeatures,
172
+ ) -> Awaitable[Awaitable[SparseFeatures]]:
173
+ """
174
+ Bucketizes sparse feature values into local world size number of buckets,
175
+ performs staggered shuffle on the sparse features, and then performs AlltoAll
176
+ operation.
177
+
178
+ Args:
179
+ sparse_features (SparseFeatures): sparse features to bucketize and
180
+ redistribute.
181
+
182
+ Returns:
183
+ Awaitable[SparseFeatures]: awaitable of SparseFeatures.
184
+ """
185
+
186
+ bucketized_sparse_features = SparseFeatures(
187
+ id_list_features=bucketize_kjt_before_all2all(
188
+ sparse_features.id_list_features,
189
+ num_buckets=self._local_size,
190
+ block_sizes=self._id_list_feature_block_sizes_tensor,
191
+ output_permute=False,
192
+ bucketize_pos=self._has_feature_processor,
193
+ )[0].permute(
194
+ self._id_list_sf_staggered_shuffle,
195
+ self._id_list_sf_staggered_shuffle_tensor,
196
+ )
197
+ if sparse_features.id_list_features is not None
198
+ else None,
199
+ id_score_list_features=bucketize_kjt_before_all2all(
200
+ sparse_features.id_score_list_features,
201
+ num_buckets=self._local_size,
202
+ block_sizes=self._id_score_list_feature_block_sizes_tensor,
203
+ output_permute=False,
204
+ bucketize_pos=False,
205
+ )[0].permute(
206
+ self._id_score_list_sf_staggered_shuffle,
207
+ self._id_score_list_sf_staggered_shuffle_tensor,
208
+ )
209
+ if sparse_features.id_score_list_features is not None
210
+ else None,
211
+ )
212
+ return self._dist(bucketized_sparse_features)
213
+
214
+ def _staggered_shuffle(self, features_per_rank: List[int]) -> List[int]:
215
+ """
216
+ Reorders sparse data such that data is in contiguous blocks and correctly
217
+ ordered for global TWRW layout.
218
+ """
219
+
220
+ nodes = self._world_size // self._local_size
221
+ features_per_node = [
222
+ features_per_rank[node * self._local_size] for node in range(nodes)
223
+ ]
224
+ node_offsets = [0] + list(itertools.accumulate(features_per_node))
225
+ num_features = node_offsets[-1]
226
+
227
+ return [
228
+ bucket * num_features + feature
229
+ for node in range(nodes)
230
+ for bucket in range(self._local_size)
231
+ for feature in range(node_offsets[node], node_offsets[node + 1])
232
+ ]
233
+
234
+
235
+ class VariableBatchTwRwPooledEmbeddingDist(
236
+ BaseVariableBatchEmbeddingDist[torch.Tensor]
237
+ ):
238
+ def __init__(
239
+ self,
240
+ rank: int,
241
+ cross_pg: dist.ProcessGroup,
242
+ intra_pg: dist.ProcessGroup,
243
+ dim_sum_per_node: List[int],
244
+ device: Optional[torch.device] = None,
245
+ ) -> None:
246
+ super().__init__()
247
+ self._rank = rank
248
+ self._intra_pg: dist.ProcessGroup = intra_pg
249
+ self._cross_pg: dist.ProcessGroup = cross_pg
250
+ self._device: Optional[torch.device] = device
251
+ self._intra_dist = PooledEmbeddingsReduceScatter(intra_pg)
252
+ self._cross_dist = PooledEmbeddingsAllToAll(
253
+ cross_pg,
254
+ dim_sum_per_node,
255
+ device,
256
+ )
257
+
258
+ def forward(
259
+ self,
260
+ local_embs: torch.Tensor,
261
+ sharding_ctx: VariableBatchShardingContext,
262
+ ) -> Awaitable[torch.Tensor]:
263
+
264
+ # preprocess batch_size_per_rank
265
+ (
266
+ batch_size_per_rank_by_cross_group,
267
+ batch_size_sum_by_cross_group,
268
+ ) = self._preprocess_batch_size_per_rank(
269
+ self._intra_pg.size(),
270
+ self._cross_pg.size(),
271
+ sharding_ctx.batch_size_per_rank,
272
+ )
273
+ # Pad each chunk to same size, prepare for ReduceScatter
274
+ # Skip padding when a host has no table assigned, in which case its dim is 0
275
+ max_length = max(batch_size_sum_by_cross_group)
276
+ if local_embs.shape[1] != 0:
277
+ # pyre-fixme[28]: Unexpected keyword argument `pin_memory`.
278
+ lengths = torch.tensor(
279
+ batch_size_sum_by_cross_group,
280
+ pin_memory=True,
281
+ ).to(device=self._device, non_blocking=True)
282
+ local_embs = torch.ops.fbgemm.pack_segments(
283
+ t_in=local_embs,
284
+ max_length=max_length,
285
+ lengths=lengths,
286
+ )
287
+ # Perform ReduceScatter within one host
288
+ rs_result = self._intra_dist(
289
+ local_embs.view(self._intra_pg.size() * max_length, -1)
290
+ ).wait()
291
+
292
+ local_rank = self._rank % self._intra_pg.size()
293
+ rs_result = torch.narrow(
294
+ rs_result,
295
+ 0,
296
+ 0,
297
+ batch_size_sum_by_cross_group[local_rank],
298
+ )
299
+
300
+ return self._cross_dist(
301
+ rs_result,
302
+ batch_size_per_rank=batch_size_per_rank_by_cross_group[local_rank],
303
+ )
304
+
305
+ def _preprocess_batch_size_per_rank(
306
+ self, local_size: int, nodes: int, batch_size_per_rank: List[int]
307
+ ) -> Tuple[List[List[int]], List[int]]:
308
+ """
309
+ Reorders `batch_size_per_rank` so it's aligned with reordered features after
310
+ AlltoAll.
311
+ """
312
+ batch_size_per_rank_by_cross_group: List[List[int]] = []
313
+ batch_size_sum_by_cross_group: List[int] = []
314
+ for local_rank in range(local_size):
315
+ batch_size_per_rank_: List[int] = []
316
+ batch_size_sum = 0
317
+ for node in range(nodes):
318
+ batch_size_per_rank_.append(
319
+ batch_size_per_rank[local_rank + node * local_size]
320
+ )
321
+ batch_size_sum += batch_size_per_rank[local_rank + node * local_size]
322
+ batch_size_per_rank_by_cross_group.append(batch_size_per_rank_)
323
+ batch_size_sum_by_cross_group.append(batch_size_sum)
324
+
325
+ return batch_size_per_rank_by_cross_group, batch_size_sum_by_cross_group
326
+
327
+
328
+ class VariableBatchTwRwPooledEmbeddingSharding(
329
+ BaseTwRwEmbeddingSharding[SparseFeatures, torch.Tensor]
330
+ ):
331
+ """
332
+ Shards embedding bags table-wise then row-wise.
333
+
334
+ Supports variable batch size.
335
+ """
336
+
337
+ def create_input_dist(
338
+ self, device: Optional[torch.device] = None
339
+ ) -> BaseSparseFeaturesDist[SparseFeatures]:
340
+ id_list_features_per_rank = self._features_per_rank(
341
+ self._grouped_embedding_configs_per_rank
342
+ )
343
+ id_score_list_features_per_rank = self._features_per_rank(
344
+ self._score_grouped_embedding_configs_per_rank
345
+ )
346
+ id_list_feature_hash_sizes = self._get_id_list_features_hash_sizes()
347
+ id_score_list_feature_hash_sizes = self._get_id_score_list_features_hash_sizes()
348
+ return VariableBatchTwRwSparseFeaturesDist(
349
+ # pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
350
+ # `Optional[ProcessGroup]`.
351
+ pg=self._pg,
352
+ intra_pg=cast(dist.ProcessGroup, self._intra_pg),
353
+ id_list_features_per_rank=id_list_features_per_rank,
354
+ id_score_list_features_per_rank=id_score_list_features_per_rank,
355
+ id_list_feature_hash_sizes=id_list_feature_hash_sizes,
356
+ id_score_list_feature_hash_sizes=id_score_list_feature_hash_sizes,
357
+ device=device if device is not None else self._device,
358
+ has_feature_processor=self._has_feature_processor,
359
+ )
360
+
361
+ def create_lookup(
362
+ self,
363
+ device: Optional[torch.device] = None,
364
+ fused_params: Optional[Dict[str, Any]] = None,
365
+ feature_processor: Optional[BaseGroupedFeatureProcessor] = None,
366
+ ) -> BaseEmbeddingLookup:
367
+ return GroupedPooledEmbeddingsLookup(
368
+ grouped_configs=self._grouped_embedding_configs_per_rank[self._rank],
369
+ grouped_score_configs=self._score_grouped_embedding_configs_per_rank[
370
+ self._rank
371
+ ],
372
+ fused_params=fused_params,
373
+ pg=self._pg,
374
+ device=device if device is not None else self._device,
375
+ feature_processor=feature_processor,
376
+ )
377
+
378
+ def create_output_dist(
379
+ self,
380
+ device: Optional[torch.device] = None,
381
+ ) -> BaseEmbeddingDist[torch.Tensor]:
382
+ return VariableBatchTwRwPooledEmbeddingDist(
383
+ rank=self._rank,
384
+ cross_pg=cast(dist.ProcessGroup, self._cross_pg),
385
+ intra_pg=cast(dist.ProcessGroup, self._intra_pg),
386
+ dim_sum_per_node=self._dim_sum_per_node(),
387
+ device=device if device is not None else self._device,
388
+ )
File without changes
@@ -0,0 +1,132 @@
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
+ #!/usr/bin/env python3
9
+
10
+ import multiprocessing
11
+ import os
12
+ import unittest
13
+ from typing import Callable, Optional
14
+
15
+ import torch
16
+ import torch.distributed as dist
17
+ from torchrec.distributed.comm import _CROSS_PG, _INTRA_PG
18
+ from torchrec.test_utils import (
19
+ get_free_port,
20
+ init_distributed_single_host,
21
+ seed_and_log,
22
+ )
23
+
24
+
25
+ class MultiProcessContext:
26
+ def __init__(
27
+ self,
28
+ rank: int,
29
+ world_size: int,
30
+ backend: str = "gloo",
31
+ local_size: Optional[int] = None,
32
+ ) -> None:
33
+
34
+ self.rank = rank
35
+ self.world_size = world_size
36
+ self.backend = backend
37
+ self.local_size = local_size
38
+
39
+ if backend == "nccl":
40
+ device = torch.device(f"cuda:{rank}")
41
+ torch.cuda.set_device(device)
42
+ else:
43
+ device = torch.device("cpu")
44
+ self.device: torch.device = device
45
+ torch.use_deterministic_algorithms(True)
46
+ if torch.cuda.is_available():
47
+ torch.backends.cudnn.allow_tf32 = False
48
+ torch.backends.cuda.matmul.allow_tf32 = False
49
+ self.pg: Optional[dist.ProcessGroup] = None
50
+
51
+ # pyre-ignore
52
+ def __enter__(self):
53
+ """
54
+ Override local_size after pg construction because unit test device count is
55
+ larger than local_size setup. This can be problematic for twrw because we have
56
+ ShardedTensor placement check.
57
+
58
+ TODO (T108556130) Mock out functions in comm.py instead of overriding env vars
59
+ """
60
+
61
+ os.environ["LOCAL_WORLD_SIZE"] = str(self.local_size or self.world_size)
62
+ if self.local_size is not None:
63
+ os.environ["LOCAL_RANK"] = str(self.rank % self.local_size)
64
+
65
+ self.pg = init_distributed_single_host(
66
+ rank=self.rank,
67
+ world_size=self.world_size,
68
+ backend=self.backend,
69
+ local_size=self.local_size,
70
+ )
71
+ return self
72
+
73
+ # pyre-ignore
74
+ def __exit__(self, exc_type, exc_instance, traceback) -> None:
75
+ if _INTRA_PG is not None:
76
+ dist.destroy_process_group(_INTRA_PG)
77
+ if _CROSS_PG is not None:
78
+ dist.destroy_process_group(_CROSS_PG)
79
+ dist.destroy_process_group(self.pg)
80
+ torch.use_deterministic_algorithms(False)
81
+ if torch.cuda.is_available():
82
+ torch.backends.cudnn.allow_tf32 = True
83
+
84
+
85
+ class MultiProcessTestBase(unittest.TestCase):
86
+ @seed_and_log
87
+ def setUp(self) -> None:
88
+ os.environ["MASTER_ADDR"] = str("localhost")
89
+ os.environ["MASTER_PORT"] = str(get_free_port())
90
+ os.environ["GLOO_DEVICE_TRANSPORT"] = "TCP"
91
+ os.environ["NCCL_SOCKET_IFNAME"] = "lo"
92
+
93
+ torch.use_deterministic_algorithms(True)
94
+ if torch.cuda.is_available():
95
+ torch.backends.cudnn.allow_tf32 = False
96
+ torch.backends.cuda.matmul.allow_tf32 = False
97
+ os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
98
+
99
+ def tearDown(self) -> None:
100
+ torch.use_deterministic_algorithms(False)
101
+ del os.environ["GLOO_DEVICE_TRANSPORT"]
102
+ del os.environ["NCCL_SOCKET_IFNAME"]
103
+ if torch.cuda.is_available():
104
+ os.unsetenv("CUBLAS_WORKSPACE_CONFIG")
105
+ super().tearDown()
106
+
107
+ def _run_multi_process_test(
108
+ self,
109
+ *,
110
+ callable: Callable[
111
+ ...,
112
+ None,
113
+ ],
114
+ world_size: int,
115
+ # pyre-ignore
116
+ **kwargs,
117
+ ) -> None:
118
+ ctx = multiprocessing.get_context("forkserver")
119
+ processes = []
120
+ for rank in range(world_size):
121
+ kwargs["rank"] = rank
122
+ kwargs["world_size"] = world_size
123
+ p = ctx.Process(
124
+ target=callable,
125
+ kwargs=kwargs,
126
+ )
127
+ p.start()
128
+ processes.append(p)
129
+
130
+ for p in processes:
131
+ p.join()
132
+ self.assertEqual(0, p.exitcode)