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,250 @@
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
+ from typing import Any, Dict, List, Optional
11
+
12
+ import torch
13
+ import torch.distributed as dist
14
+ from torchrec.distributed.dist_data import PooledEmbeddingsReduceScatter
15
+ from torchrec.distributed.embedding_lookup import GroupedPooledEmbeddingsLookup
16
+ from torchrec.distributed.embedding_sharding import (
17
+ BaseEmbeddingLookup,
18
+ BaseSparseFeaturesDist,
19
+ bucketize_kjt_before_all2all,
20
+ SparseFeaturesAllToAll,
21
+ )
22
+ from torchrec.distributed.embedding_types import (
23
+ BaseGroupedFeatureProcessor,
24
+ SparseFeatures,
25
+ )
26
+ from torchrec.distributed.sharding.rw_sharding import BaseRwEmbeddingSharding
27
+ from torchrec.distributed.sharding.vb_sharding import (
28
+ BaseVariableBatchEmbeddingDist,
29
+ VariableBatchShardingContext,
30
+ )
31
+ from torchrec.distributed.types import Awaitable
32
+
33
+ torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops")
34
+ torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops_cpu")
35
+
36
+
37
+ class VariableBatchRwSparseFeaturesDist(BaseSparseFeaturesDist[SparseFeatures]):
38
+ """
39
+ Bucketizes sparse features in RW fashion and then redistributes with an AlltoAll
40
+ collective operation.
41
+
42
+ Supports variable batch size.
43
+
44
+ Args:
45
+ pg (dist.ProcessGroup): ProcessGroup for AlltoAll communication.
46
+ intra_pg (dist.ProcessGroup): ProcessGroup within single host group for AlltoAll
47
+ communication.
48
+ num_id_list_features (int): total number of id list features.
49
+ num_id_score_list_features (int): total number of id score list features
50
+ id_list_feature_hash_sizes (List[int]): hash sizes of id list features.
51
+ id_score_list_feature_hash_sizes (List[int]): hash sizes of id score list features.
52
+ device (Optional[torch.device]): device on which buffers will be allocated.
53
+ has_feature_processor (bool): existence of feature processor (ie. position
54
+ weighted features).
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ pg: dist.ProcessGroup,
60
+ num_id_list_features: int,
61
+ num_id_score_list_features: int,
62
+ id_list_feature_hash_sizes: List[int],
63
+ id_score_list_feature_hash_sizes: List[int],
64
+ device: Optional[torch.device] = None,
65
+ has_feature_processor: bool = False,
66
+ ) -> None:
67
+ super().__init__()
68
+ self._world_size: int = pg.size()
69
+ self._num_id_list_features = num_id_list_features
70
+ self._num_id_score_list_features = num_id_score_list_features
71
+ id_list_feature_block_sizes = [
72
+ (hash_size + self._world_size - 1) // self._world_size
73
+ for hash_size in id_list_feature_hash_sizes
74
+ ]
75
+ id_score_list_feature_block_sizes = [
76
+ (hash_size + self._world_size - 1) // self._world_size
77
+ for hash_size in id_score_list_feature_hash_sizes
78
+ ]
79
+ self.register_buffer(
80
+ "_id_list_feature_block_sizes_tensor",
81
+ torch.tensor(
82
+ id_list_feature_block_sizes,
83
+ device=device,
84
+ dtype=torch.int32,
85
+ ),
86
+ )
87
+ self.register_buffer(
88
+ "_id_score_list_feature_block_sizes_tensor",
89
+ torch.tensor(
90
+ id_score_list_feature_block_sizes,
91
+ device=device,
92
+ dtype=torch.int32,
93
+ ),
94
+ )
95
+ self._dist = SparseFeaturesAllToAll(
96
+ pg=pg,
97
+ id_list_features_per_rank=self._world_size * [self._num_id_list_features],
98
+ id_score_list_features_per_rank=self._world_size
99
+ * [self._num_id_score_list_features],
100
+ device=device,
101
+ variable_batch_size=True,
102
+ )
103
+ self._has_feature_processor = has_feature_processor
104
+ self.unbucketize_permute_tensor: Optional[torch.Tensor] = None
105
+
106
+ def forward(
107
+ self,
108
+ sparse_features: SparseFeatures,
109
+ ) -> Awaitable[Awaitable[SparseFeatures]]:
110
+ """
111
+ Bucketizes sparse feature values into world size number of buckets, and then
112
+ performs AlltoAll operation.
113
+
114
+ Args:
115
+ sparse_features (SparseFeatures): sparse features to bucketize and
116
+ redistribute.
117
+
118
+ Returns:
119
+ Awaitable[SparseFeatures]: awaitable of SparseFeatures.
120
+ """
121
+
122
+ if self._num_id_list_features > 0:
123
+ assert sparse_features.id_list_features is not None
124
+ (
125
+ id_list_features,
126
+ self.unbucketize_permute_tensor,
127
+ ) = bucketize_kjt_before_all2all(
128
+ sparse_features.id_list_features,
129
+ num_buckets=self._world_size,
130
+ block_sizes=self._id_list_feature_block_sizes_tensor,
131
+ output_permute=False,
132
+ bucketize_pos=self._has_feature_processor,
133
+ )
134
+ else:
135
+ id_list_features = None
136
+
137
+ if self._num_id_score_list_features > 0:
138
+ assert sparse_features.id_score_list_features is not None
139
+ id_score_list_features, _ = bucketize_kjt_before_all2all(
140
+ sparse_features.id_score_list_features,
141
+ num_buckets=self._world_size,
142
+ block_sizes=self._id_score_list_feature_block_sizes_tensor,
143
+ output_permute=False,
144
+ bucketize_pos=False,
145
+ )
146
+ else:
147
+ id_score_list_features = None
148
+
149
+ bucketized_sparse_features = SparseFeatures(
150
+ id_list_features=id_list_features,
151
+ id_score_list_features=id_score_list_features,
152
+ )
153
+ return self._dist(bucketized_sparse_features)
154
+
155
+
156
+ class VariableBatchRwEmbeddingDistAwaitable(Awaitable[torch.Tensor]):
157
+ def __init__(self, awaitable: Awaitable[torch.Tensor], batch_size: int) -> None:
158
+ super().__init__()
159
+ self._awaitable = awaitable
160
+ self._batch_size = batch_size
161
+
162
+ def _wait_impl(self) -> torch.Tensor:
163
+ embedding = self._awaitable.wait()
164
+ embedding = torch.narrow(embedding, 0, 0, self._batch_size)
165
+
166
+ return embedding
167
+
168
+
169
+ class VariableBatchRwPooledEmbeddingDist(BaseVariableBatchEmbeddingDist[torch.Tensor]):
170
+ def __init__(
171
+ self,
172
+ pg: dist.ProcessGroup,
173
+ ) -> None:
174
+ super().__init__()
175
+ self._workers: int = pg.size()
176
+ self._rank: int = pg.rank()
177
+ self._dist = PooledEmbeddingsReduceScatter(pg)
178
+
179
+ def forward(
180
+ self,
181
+ local_embs: torch.Tensor,
182
+ sharding_ctx: VariableBatchShardingContext,
183
+ ) -> Awaitable[torch.Tensor]:
184
+ batch_size_per_rank_tensor = sharding_ctx.batch_size_per_rank_tensor
185
+ batch_size_per_rank = sharding_ctx.batch_size_per_rank
186
+ max_length = max(batch_size_per_rank)
187
+ batch_size = batch_size_per_rank[self._rank]
188
+ packed_pooled_embs = torch.ops.fbgemm.pack_segments(
189
+ t_in=local_embs,
190
+ lengths=batch_size_per_rank_tensor,
191
+ max_length=max_length,
192
+ )
193
+ awaitable_tensor = self._dist(
194
+ packed_pooled_embs.view(self._workers * max_length, -1)
195
+ )
196
+ return VariableBatchRwEmbeddingDistAwaitable(awaitable_tensor, batch_size)
197
+
198
+
199
+ class VariableBatchRwPooledEmbeddingSharding(
200
+ BaseRwEmbeddingSharding[SparseFeatures, torch.Tensor]
201
+ ):
202
+ """
203
+ Shards pooled embeddings row-wise, i.e.. a given embedding table is evenly
204
+ distributed by rows and table slices are placed on all ranks.
205
+
206
+ Supports variable batch size.
207
+ """
208
+
209
+ def create_input_dist(
210
+ self,
211
+ device: Optional[torch.device] = None,
212
+ ) -> BaseSparseFeaturesDist[SparseFeatures]:
213
+ num_id_list_features = self._get_id_list_features_num()
214
+ num_id_score_list_features = self._get_id_score_list_features_num()
215
+ id_list_feature_hash_sizes = self._get_id_list_features_hash_sizes()
216
+ id_score_list_feature_hash_sizes = self._get_id_score_list_features_hash_sizes()
217
+ return VariableBatchRwSparseFeaturesDist(
218
+ # pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
219
+ # `Optional[ProcessGroup]`.
220
+ pg=self._pg,
221
+ num_id_list_features=num_id_list_features,
222
+ num_id_score_list_features=num_id_score_list_features,
223
+ id_list_feature_hash_sizes=id_list_feature_hash_sizes,
224
+ id_score_list_feature_hash_sizes=id_score_list_feature_hash_sizes,
225
+ device=self._device,
226
+ has_feature_processor=self._has_feature_processor,
227
+ )
228
+
229
+ def create_lookup(
230
+ self,
231
+ device: Optional[torch.device] = None,
232
+ fused_params: Optional[Dict[str, Any]] = None,
233
+ feature_processor: Optional[BaseGroupedFeatureProcessor] = None,
234
+ ) -> BaseEmbeddingLookup:
235
+ return GroupedPooledEmbeddingsLookup(
236
+ grouped_configs=self._grouped_embedding_configs,
237
+ grouped_score_configs=self._score_grouped_embedding_configs,
238
+ fused_params=fused_params,
239
+ pg=self._pg,
240
+ device=device if device is not None else self._device,
241
+ feature_processor=feature_processor,
242
+ )
243
+
244
+ def create_output_dist(
245
+ self,
246
+ device: Optional[torch.device] = None,
247
+ ) -> BaseVariableBatchEmbeddingDist[torch.Tensor]:
248
+ # pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
249
+ # `Optional[ProcessGroup]`.
250
+ return VariableBatchRwPooledEmbeddingDist(self._pg)
@@ -0,0 +1,54 @@
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, field
10
+ from typing import List, Optional, TypeVar
11
+
12
+ import torch
13
+ from torchrec.distributed.embedding_sharding import BaseEmbeddingDist
14
+ from torchrec.distributed.types import Awaitable
15
+ from torchrec.streamable import Multistreamable
16
+
17
+
18
+ @dataclass
19
+ class VariableBatchShardingContext(Multistreamable):
20
+ """
21
+ For variable batch size case, we need pass `batch_size_per_rank` to
22
+ PooledEmbeddingsAllToAll and it can be retrieved from SparseFeaturesAllToAll.
23
+
24
+ Attributes:
25
+ batch_size_per_rank (List[int]): stores batch size in each rank.
26
+ batch_size_per_rank_tensor (Optional[torch.Tensor]): batch_size_per_rank stored in
27
+ tensor.
28
+ """
29
+
30
+ batch_size_per_rank: List[int] = field(default_factory=list)
31
+ batch_size_per_rank_tensor: Optional[torch.Tensor] = None
32
+
33
+ def record_stream(self, stream: torch.cuda.streams.Stream) -> None:
34
+ if self.batch_size_per_rank_tensor is not None:
35
+ # pyre-fixme[6]: For 1st param expected `Stream` but got `Stream`.
36
+ self.batch_size_per_rank_tensor.record_stream(stream)
37
+
38
+
39
+ T = TypeVar("T")
40
+
41
+
42
+ class BaseVariableBatchEmbeddingDist(BaseEmbeddingDist[T]):
43
+ """
44
+ Base class for converting output of EmbeddingLookup from model-parallel to
45
+ data-parallel for variable batch size.
46
+ """
47
+
48
+ @abc.abstractmethod
49
+ def forward(
50
+ self,
51
+ local_embs: T,
52
+ sharding_ctx: VariableBatchShardingContext,
53
+ ) -> Awaitable[torch.Tensor]:
54
+ pass
@@ -0,0 +1,148 @@
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
9
+
10
+ import torch
11
+ import torch.distributed as dist
12
+ from torchrec.distributed.dist_data import PooledEmbeddingsAllToAll
13
+ from torchrec.distributed.embedding_lookup import GroupedPooledEmbeddingsLookup
14
+ from torchrec.distributed.embedding_sharding import (
15
+ BaseEmbeddingLookup,
16
+ BaseSparseFeaturesDist,
17
+ SparseFeaturesAllToAll,
18
+ )
19
+ from torchrec.distributed.embedding_types import (
20
+ BaseGroupedFeatureProcessor,
21
+ SparseFeatures,
22
+ )
23
+ from torchrec.distributed.sharding.tw_sharding import BaseTwEmbeddingSharding
24
+ from torchrec.distributed.sharding.vb_sharding import (
25
+ BaseVariableBatchEmbeddingDist,
26
+ VariableBatchShardingContext,
27
+ )
28
+ from torchrec.distributed.types import Awaitable
29
+
30
+
31
+ class VariableBatchTwSparseFeaturesDist(BaseSparseFeaturesDist[SparseFeatures]):
32
+ """
33
+ Redistributes sparse features in TW fashion with an AlltoAll collective
34
+ operation.
35
+
36
+ Supports variable batch size.
37
+
38
+ Args:
39
+ pg (dist.ProcessGroup): ProcessGroup for AlltoAll communication.
40
+ id_list_features_per_rank (List[int]): number of id list features to send to
41
+ each rank.
42
+ id_score_list_features_per_rank (List[int]): number of id score list features to
43
+ send to each rank
44
+ device (Optional[torch.device]): device on which buffers will be allocated.
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ pg: dist.ProcessGroup,
50
+ id_list_features_per_rank: List[int],
51
+ id_score_list_features_per_rank: List[int],
52
+ device: Optional[torch.device] = None,
53
+ ) -> None:
54
+ super().__init__()
55
+ self._dist = SparseFeaturesAllToAll(
56
+ pg=pg,
57
+ id_list_features_per_rank=id_list_features_per_rank,
58
+ id_score_list_features_per_rank=id_score_list_features_per_rank,
59
+ device=device,
60
+ variable_batch_size=True,
61
+ )
62
+
63
+ def forward(
64
+ self,
65
+ sparse_features: SparseFeatures,
66
+ ) -> Awaitable[Awaitable[SparseFeatures]]:
67
+ """
68
+ Performs AlltoAll operation on sparse features.
69
+
70
+ Args:
71
+ sparse_features (SparseFeatures): sparse features to redistribute.
72
+
73
+ Returns:
74
+ Awaitable[Awaitable[SparseFeatures]]: awaitable of awaitable of SparseFeatures.
75
+ """
76
+
77
+ return self._dist(sparse_features)
78
+
79
+
80
+ class VariableBatchTwPooledEmbeddingDist(BaseVariableBatchEmbeddingDist[torch.Tensor]):
81
+ def __init__(
82
+ self,
83
+ pg: dist.ProcessGroup,
84
+ dim_sum_per_rank: List[int],
85
+ device: Optional[torch.device] = None,
86
+ callbacks: Optional[List[Callable[[torch.Tensor], torch.Tensor]]] = None,
87
+ ) -> None:
88
+ super().__init__()
89
+ self._dist = PooledEmbeddingsAllToAll(pg, dim_sum_per_rank, device, callbacks)
90
+
91
+ def forward(
92
+ self, local_embs: torch.Tensor, sharding_ctx: VariableBatchShardingContext
93
+ ) -> Awaitable[torch.Tensor]:
94
+ # do not remove the keyword for quantized communication hook injection.
95
+ return self._dist(
96
+ local_embs, batch_size_per_rank=sharding_ctx.batch_size_per_rank
97
+ )
98
+
99
+
100
+ class VariableBatchTwPooledEmbeddingSharding(
101
+ BaseTwEmbeddingSharding[SparseFeatures, torch.Tensor]
102
+ ):
103
+ """
104
+ Shards pooled embeddings table-wise, i.e.. a given embedding table is entirely placed
105
+ on a selected rank.
106
+
107
+ Supports variable batch size.
108
+ """
109
+
110
+ def create_input_dist(
111
+ self,
112
+ device: Optional[torch.device] = None,
113
+ ) -> BaseSparseFeaturesDist[SparseFeatures]:
114
+ return VariableBatchTwSparseFeaturesDist(
115
+ # pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
116
+ # `Optional[ProcessGroup]`.
117
+ self._pg,
118
+ self._id_list_features_per_rank(),
119
+ self._id_score_list_features_per_rank(),
120
+ device if device is not None else self._device,
121
+ )
122
+
123
+ def create_lookup(
124
+ self,
125
+ device: Optional[torch.device] = None,
126
+ fused_params: Optional[Dict[str, Any]] = None,
127
+ feature_processor: Optional[BaseGroupedFeatureProcessor] = None,
128
+ ) -> BaseEmbeddingLookup:
129
+ return GroupedPooledEmbeddingsLookup(
130
+ grouped_configs=self._grouped_embedding_configs,
131
+ grouped_score_configs=self._score_grouped_embedding_configs,
132
+ fused_params=fused_params,
133
+ pg=self._pg,
134
+ device=device if device is not None else self._device,
135
+ feature_processor=feature_processor,
136
+ )
137
+
138
+ def create_output_dist(
139
+ self,
140
+ device: Optional[torch.device] = None,
141
+ ) -> BaseVariableBatchEmbeddingDist[torch.Tensor]:
142
+ return VariableBatchTwPooledEmbeddingDist(
143
+ # pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
144
+ # `Optional[ProcessGroup]`.
145
+ self._pg,
146
+ self._dim_sum_per_rank(),
147
+ device if device is not None else self._device,
148
+ )