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,660 @@
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
+ from dataclasses import dataclass
10
+ from typing import Any, Dict, Generic, List, Optional, Tuple, TypeVar
11
+
12
+ import torch
13
+ import torch.distributed as dist
14
+ from torch import nn
15
+ from torchrec.distributed.dist_data import (
16
+ KJTAllToAll,
17
+ KJTAllToAllIndicesAwaitable,
18
+ KJTOneToAll,
19
+ )
20
+ from torchrec.distributed.embedding_types import (
21
+ BaseEmbeddingLookup,
22
+ BaseGroupedFeatureProcessor,
23
+ EmbeddingComputeKernel,
24
+ GroupedEmbeddingConfig,
25
+ ListOfSparseFeaturesList,
26
+ ShardedEmbeddingTable,
27
+ SparseFeatures,
28
+ SparseFeaturesList,
29
+ )
30
+ from torchrec.distributed.types import (
31
+ Awaitable,
32
+ NoWait,
33
+ ParameterSharding,
34
+ ShardMetadata,
35
+ )
36
+ from torchrec.modules.embedding_configs import (
37
+ DataType,
38
+ EmbeddingTableConfig,
39
+ PoolingType,
40
+ )
41
+ from torchrec.sparse.jagged_tensor import KeyedJaggedTensor
42
+ from torchrec.streamable import Multistreamable
43
+
44
+
45
+ class SparseFeaturesIndicesAwaitable(Awaitable[SparseFeatures]):
46
+ """
47
+ Awaitable of sparse features redistributed with AlltoAll collective.
48
+
49
+ Args:
50
+ id_list_features_awaitable (Optional[Awaitable[KeyedJaggedTensor]]): awaitable
51
+ of sharded id list features.
52
+ id_score_list_features_awaitable (Optional[Awaitable[KeyedJaggedTensor]]):
53
+ awaitable of sharded id score list features.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ id_list_features_awaitable: Optional[Awaitable[KeyedJaggedTensor]],
59
+ id_score_list_features_awaitable: Optional[Awaitable[KeyedJaggedTensor]],
60
+ ) -> None:
61
+ super().__init__()
62
+ self._id_list_features_awaitable = id_list_features_awaitable
63
+ self._id_score_list_features_awaitable = id_score_list_features_awaitable
64
+
65
+ def _wait_impl(self) -> SparseFeatures:
66
+ """
67
+ Syncs sparse features after AlltoAll.
68
+
69
+ Returns:
70
+ SparseFeatures: synced sparse features.
71
+ """
72
+
73
+ return SparseFeatures(
74
+ id_list_features=self._id_list_features_awaitable.wait()
75
+ if self._id_list_features_awaitable is not None
76
+ else None,
77
+ id_score_list_features=self._id_score_list_features_awaitable.wait()
78
+ if self._id_score_list_features_awaitable is not None
79
+ else None,
80
+ )
81
+
82
+
83
+ class SparseFeaturesLengthsAwaitable(Awaitable[SparseFeaturesIndicesAwaitable]):
84
+ """
85
+ Awaitable of sparse features indices distribution.
86
+
87
+ Args:
88
+ id_list_features_awaitable (Optional[Awaitable[KJTAllToAllIndicesAwaitable]]):
89
+ awaitable of sharded id list features indices AlltoAll. Waiting on this
90
+ value will trigger indices AlltoAll (waiting again will yield final AlltoAll
91
+ results).
92
+ id_score_list_features_awaitable
93
+ (Optional[Awaitable[KJTAllToAllIndicesAwaitable]]):
94
+ awaitable of sharded id score list features indices AlltoAll. Waiting on
95
+ this value will trigger indices AlltoAll (waiting again will yield the final
96
+ AlltoAll results).
97
+ """
98
+
99
+ def __init__(
100
+ self,
101
+ id_list_features_awaitable: Optional[Awaitable[KJTAllToAllIndicesAwaitable]],
102
+ id_score_list_features_awaitable: Optional[
103
+ Awaitable[KJTAllToAllIndicesAwaitable]
104
+ ],
105
+ ) -> None:
106
+ super().__init__()
107
+ self._id_list_features_awaitable = id_list_features_awaitable
108
+ self._id_score_list_features_awaitable = id_score_list_features_awaitable
109
+
110
+ def _wait_impl(self) -> SparseFeaturesIndicesAwaitable:
111
+ """
112
+ Gets lengths of AlltoAll results, instantiates `SparseFeaturesIndicesAwaitable` for
113
+ indices AlltoAll.
114
+
115
+ Returns:
116
+ SparseFeaturesIndicesAwaitable.
117
+ """
118
+ return SparseFeaturesIndicesAwaitable(
119
+ id_list_features_awaitable=self._id_list_features_awaitable.wait()
120
+ if self._id_list_features_awaitable is not None
121
+ else None,
122
+ id_score_list_features_awaitable=self._id_score_list_features_awaitable.wait()
123
+ if self._id_score_list_features_awaitable is not None
124
+ else None,
125
+ )
126
+
127
+
128
+ def bucketize_kjt_before_all2all(
129
+ kjt: KeyedJaggedTensor,
130
+ num_buckets: int,
131
+ block_sizes: torch.Tensor,
132
+ output_permute: bool = False,
133
+ bucketize_pos: bool = False,
134
+ ) -> Tuple[KeyedJaggedTensor, Optional[torch.Tensor]]:
135
+ """
136
+ Bucketizes the `values` in KeyedJaggedTensor into `num_buckets` buckets,
137
+ `lengths` are readjusted based on the bucketization results.
138
+
139
+ Note: This function should be used only for row-wise sharding before calling
140
+ `SparseFeaturesAllToAll`.
141
+
142
+ Args:
143
+ num_buckets (int): number of buckets to bucketize the values into.
144
+ block_sizes: (torch.Tensor): bucket sizes for the keyed dimension.
145
+ output_permute (bool): output the memory location mapping from the unbucketized
146
+ values to bucketized values or not.
147
+ bucketize_pos (bool): output the changed position of the bucketized values or
148
+ not.
149
+
150
+ Returns:
151
+ Tuple[KeyedJaggedTensor, Optional[torch.Tensor]]: the bucketized `KeyedJaggedTensor` and the optional permute mapping from the unbucketized values to bucketized value.
152
+ """
153
+
154
+ num_features = len(kjt.keys())
155
+ assert (
156
+ block_sizes.numel() == num_features
157
+ ), f"Expecting block sizes for {num_features} features, but {block_sizes.numel()} received."
158
+
159
+ # kernel expects them to be same type, cast to avoid type mismatch
160
+ block_sizes_new_type = block_sizes.type(kjt.values().type())
161
+ (
162
+ bucketized_lengths,
163
+ bucketized_indices,
164
+ bucketized_weights,
165
+ pos,
166
+ unbucketize_permute,
167
+ ) = torch.ops.fbgemm.block_bucketize_sparse_features(
168
+ kjt.lengths().view(-1),
169
+ kjt.values(),
170
+ bucketize_pos=bucketize_pos,
171
+ sequence=output_permute,
172
+ block_sizes=block_sizes_new_type,
173
+ my_size=num_buckets,
174
+ weights=kjt.weights_or_none(),
175
+ )
176
+
177
+ return (
178
+ KeyedJaggedTensor(
179
+ # duplicate keys will be resolved by AllToAll
180
+ keys=kjt.keys() * num_buckets,
181
+ values=bucketized_indices,
182
+ weights=pos if bucketize_pos else bucketized_weights,
183
+ lengths=bucketized_lengths.view(-1),
184
+ offsets=None,
185
+ stride=kjt.stride(),
186
+ length_per_key=None,
187
+ offset_per_key=None,
188
+ index_per_key=None,
189
+ ),
190
+ unbucketize_permute,
191
+ )
192
+
193
+
194
+ class SparseFeaturesAllToAll(nn.Module):
195
+ """
196
+ Redistributes sparse features to a `ProcessGroup` utilizing an AlltoAll collective.
197
+
198
+ Args:
199
+ pg (dist.ProcessGroup): process group for AlltoAll communication.
200
+ id_list_features_per_rank (List[int]): number of id list features to send to
201
+ each rank.
202
+ id_score_list_features_per_rank (List[int]): number of id score list features to
203
+ send to each rank
204
+ device (Optional[torch.device]): device on which buffers will be allocated.
205
+ stagger (int): stagger value to apply to recat tensor, see `_recat` function for
206
+ more detail.
207
+ variable_batch_size (bool): variable batch size in each rank.
208
+
209
+ Example::
210
+
211
+ id_list_features_per_rank = [2, 1]
212
+ id_score_list_features_per_rank = [1, 3]
213
+ sfa2a = SparseFeaturesAllToAll(
214
+ pg,
215
+ id_list_features_per_rank,
216
+ id_score_list_features_per_rank
217
+ )
218
+ awaitable = sfa2a(rank0_input: SparseFeatures)
219
+
220
+ # where:
221
+ # rank0_input.id_list_features is KeyedJaggedTensor holding
222
+
223
+ # 0 1 2
224
+ # 'A' [A.V0] None [A.V1, A.V2]
225
+ # 'B' None [B.V0] [B.V1]
226
+ # 'C' [C.V0] [C.V1] None
227
+
228
+ # rank1_input.id_list_features is KeyedJaggedTensor holding
229
+
230
+ # 0 1 2
231
+ # 'A' [A.V3] [A.V4] None
232
+ # 'B' None [B.V2] [B.V3, B.V4]
233
+ # 'C' [C.V2] [C.V3] None
234
+
235
+ # rank0_input.id_score_list_features is KeyedJaggedTensor holding
236
+
237
+ # 0 1 2
238
+ # 'A' [A.V0] None [A.V1, A.V2]
239
+ # 'B' None [B.V0] [B.V1]
240
+ # 'C' [C.V0] [C.V1] None
241
+ # 'D' None [D.V0] None
242
+
243
+ # rank1_input.id_score_list_features is KeyedJaggedTensor holding
244
+
245
+ # 0 1 2
246
+ # 'A' [A.V3] [A.V4] None
247
+ # 'B' None [B.V2] [B.V3, B.V4]
248
+ # 'C' [C.V2] [C.V3] None
249
+ # 'D' [D.V1] [D.V2] [D.V3, D.V4]
250
+
251
+ rank0_output: SparseFeatures = awaitable.wait()
252
+
253
+ # rank0_output.id_list_features is KeyedJaggedTensor holding
254
+
255
+ # 0 1 2 3 4 5
256
+ # 'A' [A.V0] None [A.V1, A.V2] [A.V3] [A.V4] None
257
+ # 'B' None [B.V0] [B.V1] None [B.V2] [B.V3, B.V4]
258
+
259
+ # rank1_output.id_list_features is KeyedJaggedTensor holding
260
+ # 0 1 2 3 4 5
261
+ # 'C' [C.V0] [C.V1] None [C.V2] [C.V3] None
262
+
263
+ # rank0_output.id_score_list_features is KeyedJaggedTensor holding
264
+
265
+ # 0 1 2 3 4 5
266
+ # 'A' [A.V0] None [A.V1, A.V2] [A.V3] [A.V4] None
267
+
268
+ # rank1_output.id_score_list_features is KeyedJaggedTensor holding
269
+
270
+ # 0 1 2 3 4 5
271
+ # 'B' None [B.V0] [B.V1] None [B.V2] [B.V3, B.V4]
272
+ # 'C' [C.V0] [C.V1] None [C.V2] [C.V3] None
273
+ # 'D None [D.V0] None [D.V1] [D.V2] [D.V3, D.V4]
274
+ """
275
+
276
+ def __init__(
277
+ self,
278
+ pg: dist.ProcessGroup,
279
+ id_list_features_per_rank: List[int],
280
+ id_score_list_features_per_rank: List[int],
281
+ device: Optional[torch.device] = None,
282
+ stagger: int = 1,
283
+ variable_batch_size: bool = False,
284
+ ) -> None:
285
+ super().__init__()
286
+ self._id_list_features_all2all: KJTAllToAll = KJTAllToAll(
287
+ pg=pg,
288
+ splits=id_list_features_per_rank,
289
+ device=device,
290
+ stagger=stagger,
291
+ variable_batch_size=variable_batch_size,
292
+ )
293
+ self._id_score_list_features_all2all: KJTAllToAll = KJTAllToAll(
294
+ pg=pg,
295
+ splits=id_score_list_features_per_rank,
296
+ device=device,
297
+ stagger=stagger,
298
+ variable_batch_size=variable_batch_size,
299
+ )
300
+
301
+ def forward(
302
+ self,
303
+ sparse_features: SparseFeatures,
304
+ ) -> Awaitable[SparseFeaturesIndicesAwaitable]:
305
+ """
306
+ Sends sparse features to relevant ProcessGroup ranks. Instantiates lengths
307
+ AlltoAll.
308
+ First wait will get lengths AlltoAll results, then issues indices AlltoAll.
309
+ Second wait will get indices AlltoAll results.
310
+
311
+ Args:
312
+ sparse_features (SparseFeatures): sparse features to redistribute.
313
+
314
+ Returns:
315
+ Awaitable[SparseFeatures]: awaitable of SparseFeatures.
316
+ """
317
+
318
+ return SparseFeaturesLengthsAwaitable(
319
+ id_list_features_awaitable=self._id_list_features_all2all.forward(
320
+ sparse_features.id_list_features
321
+ )
322
+ if sparse_features.id_list_features is not None
323
+ else None,
324
+ id_score_list_features_awaitable=self._id_score_list_features_all2all.forward(
325
+ sparse_features.id_score_list_features
326
+ )
327
+ if sparse_features.id_score_list_features is not None
328
+ else None,
329
+ )
330
+
331
+
332
+ class SparseFeaturesOneToAll(nn.Module):
333
+ """
334
+ Redistributes sparse features to all devices.
335
+
336
+ Args:
337
+ id_list_features_per_rank (List[int]): number of id list features to send to
338
+ each rank.
339
+ id_score_list_features_per_rank (List[int]): number of id score list features to
340
+ send to each rank
341
+ world_size (int): number of devices in the topology.
342
+ """
343
+
344
+ def __init__(
345
+ self,
346
+ id_list_features_per_rank: List[int],
347
+ id_score_list_features_per_rank: List[int],
348
+ world_size: int,
349
+ ) -> None:
350
+ super().__init__()
351
+ self._world_size = world_size
352
+ self._id_list_features_one2all: KJTOneToAll = KJTOneToAll(
353
+ id_list_features_per_rank,
354
+ world_size,
355
+ )
356
+ self._id_score_list_features_one2all: KJTOneToAll = KJTOneToAll(
357
+ id_score_list_features_per_rank, world_size
358
+ )
359
+
360
+ def forward(
361
+ self,
362
+ sparse_features: SparseFeatures,
363
+ ) -> Awaitable[SparseFeaturesList]:
364
+ """
365
+ Performs OnetoAll operation on sparse features.
366
+
367
+ Args:
368
+ sparse_features (SparseFeatures): sparse features to redistribute.
369
+
370
+ Returns:
371
+ Awaitable[SparseFeatures]: awaitable of SparseFeatures.
372
+ """
373
+
374
+ return NoWait(
375
+ SparseFeaturesList(
376
+ [
377
+ SparseFeatures(
378
+ id_list_features=id_list_features,
379
+ id_score_list_features=id_score_list_features,
380
+ )
381
+ for id_list_features, id_score_list_features in zip(
382
+ self._id_list_features_one2all.forward(
383
+ sparse_features.id_list_features
384
+ ).wait()
385
+ if sparse_features.id_list_features is not None
386
+ else [None] * self._world_size,
387
+ self._id_score_list_features_one2all.forward(
388
+ sparse_features.id_score_list_features
389
+ ).wait()
390
+ if sparse_features.id_score_list_features is not None
391
+ else [None] * self._world_size,
392
+ )
393
+ ]
394
+ )
395
+ )
396
+
397
+
398
+ # group tables by DataType, PoolingType, Weighted, and EmbeddingComputeKernel.
399
+ def group_tables(
400
+ tables_per_rank: List[List[ShardedEmbeddingTable]],
401
+ ) -> Tuple[List[List[GroupedEmbeddingConfig]], List[List[GroupedEmbeddingConfig]]]:
402
+ """
403
+ Groups tables by `DataType`, `PoolingType`, `Weighted`, and `EmbeddingComputeKernel`.
404
+
405
+ Args:
406
+ tables_per_rank (List[List[ShardedEmbeddingTable]]): list of sharding embedding
407
+ tables per rank.
408
+
409
+ Returns:
410
+ Tuple[List[List[GroupedEmbeddingConfig]], List[List[GroupedEmbeddingConfig]]]: per rank list of GroupedEmbeddingConfig for unscored and scored features.
411
+ """
412
+
413
+ def _group_tables_per_rank(
414
+ embedding_tables: List[ShardedEmbeddingTable],
415
+ ) -> Tuple[List[GroupedEmbeddingConfig], List[GroupedEmbeddingConfig]]:
416
+ grouped_embedding_configs: List[GroupedEmbeddingConfig] = []
417
+ score_grouped_embedding_configs: List[GroupedEmbeddingConfig] = []
418
+ for data_type in DataType:
419
+ for pooling in PoolingType:
420
+ for is_weighted in [True, False]:
421
+ for has_feature_processor in [False, True]:
422
+ for compute_kernel in [
423
+ EmbeddingComputeKernel.DENSE,
424
+ EmbeddingComputeKernel.FUSED,
425
+ EmbeddingComputeKernel.QUANT,
426
+ ]:
427
+ grouped_tables: List[ShardedEmbeddingTable] = []
428
+ grouped_score_tables: List[ShardedEmbeddingTable] = []
429
+ for table in embedding_tables:
430
+ compute_kernel_type = table.compute_kernel
431
+ if table.compute_kernel in [
432
+ EmbeddingComputeKernel.FUSED_UVM,
433
+ EmbeddingComputeKernel.FUSED_UVM_CACHING,
434
+ ]:
435
+ compute_kernel_type = EmbeddingComputeKernel.FUSED
436
+ elif table.compute_kernel in [
437
+ EmbeddingComputeKernel.QUANT_UVM,
438
+ EmbeddingComputeKernel.QUANT_UVM_CACHING,
439
+ ]:
440
+ compute_kernel_type = EmbeddingComputeKernel.QUANT
441
+ if (
442
+ table.data_type == data_type
443
+ and table.pooling == pooling
444
+ and table.is_weighted == is_weighted
445
+ and table.has_feature_processor
446
+ == has_feature_processor
447
+ and compute_kernel_type == compute_kernel
448
+ ):
449
+ if table.is_weighted:
450
+ grouped_score_tables.append(table)
451
+ else:
452
+ grouped_tables.append(table)
453
+ if grouped_tables:
454
+ grouped_embedding_configs.append(
455
+ GroupedEmbeddingConfig(
456
+ data_type=data_type,
457
+ pooling=pooling,
458
+ is_weighted=is_weighted,
459
+ has_feature_processor=has_feature_processor,
460
+ compute_kernel=compute_kernel,
461
+ embedding_tables=grouped_tables,
462
+ )
463
+ )
464
+ if grouped_score_tables:
465
+ score_grouped_embedding_configs.append(
466
+ GroupedEmbeddingConfig(
467
+ data_type=data_type,
468
+ pooling=pooling,
469
+ is_weighted=is_weighted,
470
+ has_feature_processor=has_feature_processor,
471
+ compute_kernel=compute_kernel,
472
+ embedding_tables=grouped_score_tables,
473
+ )
474
+ )
475
+ return grouped_embedding_configs, score_grouped_embedding_configs
476
+
477
+ grouped_embedding_configs_by_rank: List[List[GroupedEmbeddingConfig]] = []
478
+ score_grouped_embedding_configs_by_rank: List[List[GroupedEmbeddingConfig]] = []
479
+ for tables in tables_per_rank:
480
+ (
481
+ grouped_embedding_configs,
482
+ score_grouped_embedding_configs,
483
+ ) = _group_tables_per_rank(tables)
484
+ grouped_embedding_configs_by_rank.append(grouped_embedding_configs)
485
+ score_grouped_embedding_configs_by_rank.append(score_grouped_embedding_configs)
486
+ return (
487
+ grouped_embedding_configs_by_rank,
488
+ score_grouped_embedding_configs_by_rank,
489
+ )
490
+
491
+
492
+ class SparseFeaturesListAwaitable(Awaitable[SparseFeaturesList]):
493
+ """
494
+ Awaitable of SparseFeaturesList.
495
+
496
+ Args:
497
+ awaitables (List[Awaitable[SparseFeatures]]): list of `Awaitable` of sparse
498
+ features.
499
+ """
500
+
501
+ def __init__(
502
+ self,
503
+ awaitables: List[Awaitable[SparseFeatures]],
504
+ ) -> None:
505
+ super().__init__()
506
+ self.awaitables = awaitables
507
+
508
+ def _wait_impl(self) -> SparseFeaturesList:
509
+ """
510
+ Syncs sparse features in `SparseFeaturesList`.
511
+
512
+ Returns:
513
+ SparseFeaturesList: synced `SparseFeaturesList`.
514
+ """
515
+
516
+ return SparseFeaturesList([w.wait() for w in self.awaitables])
517
+
518
+
519
+ class SparseFeaturesListIndicesAwaitable(Awaitable[List[Awaitable[SparseFeatures]]]):
520
+ """
521
+ Handles the first wait for a list of two-layer awaitables of `SparseFeatures`.
522
+ Wait on this module will get lengths AlltoAll results for each `SparseFeatures`, and
523
+ instantiate its indices AlltoAll.
524
+
525
+ Args:
526
+ awaitables (List[Awaitable[Awaitable[SparseFeatures]]]): list of `Awaitable` of
527
+ `Awaitable` sparse features.
528
+ """
529
+
530
+ def __init__(
531
+ self,
532
+ awaitables: List[Awaitable[Awaitable[SparseFeatures]]],
533
+ ) -> None:
534
+ super().__init__()
535
+ self.awaitables = awaitables
536
+
537
+ def _wait_impl(self) -> List[Awaitable[SparseFeatures]]:
538
+ """
539
+ Syncs sparse features in SparseFeaturesList.
540
+
541
+ Returns:
542
+ List[Awaitable[SparseFeatures]]
543
+ """
544
+
545
+ return [m.wait() for m in self.awaitables]
546
+
547
+
548
+ class ListOfSparseFeaturesListAwaitable(Awaitable[ListOfSparseFeaturesList]):
549
+ """
550
+ This module handles the tables-wise sharding input features distribution for inference.
551
+ For inference, we currently do not separate lengths from indices.
552
+
553
+ Args:
554
+ awaitables (List[Awaitable[SparseFeaturesList]]): list of `Awaitable` of
555
+ `SparseFeaturesList`.
556
+ """
557
+
558
+ def __init__(
559
+ self,
560
+ awaitables: List[Awaitable[SparseFeaturesList]],
561
+ ) -> None:
562
+ super().__init__()
563
+ self.awaitables = awaitables
564
+
565
+ def _wait_impl(self) -> ListOfSparseFeaturesList:
566
+ """
567
+ Syncs sparse features in List of SparseFeaturesList.
568
+
569
+ Returns:
570
+ ListOfSparseFeaturesList: synced `ListOfSparseFeaturesList`.
571
+
572
+ """
573
+ return ListOfSparseFeaturesList([w.wait() for w in self.awaitables])
574
+
575
+
576
+ F = TypeVar("F", bound=Multistreamable)
577
+ T = TypeVar("T")
578
+
579
+
580
+ class BaseSparseFeaturesDist(abc.ABC, nn.Module, Generic[F]):
581
+ """
582
+ Converts input from data-parallel to model-parallel.
583
+ """
584
+
585
+ @abc.abstractmethod
586
+ def forward(
587
+ self,
588
+ sparse_features: SparseFeatures,
589
+ ) -> Awaitable[Awaitable[F]]:
590
+ pass
591
+
592
+
593
+ class BaseEmbeddingDist(abc.ABC, nn.Module, Generic[T]):
594
+ """
595
+ Converts output of EmbeddingLookup from model-parallel to data-parallel.
596
+ """
597
+
598
+ @abc.abstractmethod
599
+ def forward(
600
+ self,
601
+ local_embs: T,
602
+ ) -> Awaitable[torch.Tensor]:
603
+ pass
604
+
605
+
606
+ class EmbeddingSharding(abc.ABC, Generic[F, T]):
607
+ """
608
+ Used to implement different sharding types for `EmbeddingBagCollection`, e.g.
609
+ table_wise.
610
+ """
611
+
612
+ @abc.abstractmethod
613
+ def create_input_dist(
614
+ self,
615
+ device: Optional[torch.device] = None,
616
+ ) -> BaseSparseFeaturesDist[F]:
617
+ pass
618
+
619
+ @abc.abstractmethod
620
+ def create_output_dist(
621
+ self,
622
+ device: Optional[torch.device] = None,
623
+ ) -> BaseEmbeddingDist[T]:
624
+ pass
625
+
626
+ @abc.abstractmethod
627
+ def create_lookup(
628
+ self,
629
+ device: Optional[torch.device] = None,
630
+ fused_params: Optional[Dict[str, Any]] = None,
631
+ feature_processor: Optional[BaseGroupedFeatureProcessor] = None,
632
+ ) -> BaseEmbeddingLookup[F, T]:
633
+ pass
634
+
635
+ @abc.abstractmethod
636
+ def embedding_dims(self) -> List[int]:
637
+ pass
638
+
639
+ @abc.abstractmethod
640
+ def embedding_shard_metadata(self) -> List[Optional[ShardMetadata]]:
641
+ pass
642
+
643
+ @abc.abstractmethod
644
+ def embedding_names(self) -> List[str]:
645
+ pass
646
+
647
+ @abc.abstractmethod
648
+ def id_list_feature_names(self) -> List[str]:
649
+ pass
650
+
651
+ @abc.abstractmethod
652
+ def id_score_list_feature_names(self) -> List[str]:
653
+ pass
654
+
655
+
656
+ @dataclass
657
+ class EmbeddingShardingInfo:
658
+ embedding_config: EmbeddingTableConfig
659
+ param_sharding: ParameterSharding
660
+ param: torch.Tensor