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,760 @@
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 logging
9
+ from abc import ABC
10
+ from collections import OrderedDict
11
+ from typing import Any, cast, Dict, Iterator, List, Optional, Tuple, Union
12
+
13
+ import torch
14
+ import torch.distributed as dist
15
+ from torch import nn
16
+ from torch.nn.modules.module import _IncompatibleKeys
17
+ from torchrec.distributed.batched_embedding_kernel import (
18
+ BaseBatchedEmbedding,
19
+ BaseBatchedEmbeddingBag,
20
+ BatchedDenseEmbedding,
21
+ BatchedDenseEmbeddingBag,
22
+ BatchedFusedEmbedding,
23
+ BatchedFusedEmbeddingBag,
24
+ )
25
+ from torchrec.distributed.embedding_kernel import (
26
+ BaseEmbedding,
27
+ GroupedEmbedding,
28
+ GroupedEmbeddingBag,
29
+ )
30
+ from torchrec.distributed.embedding_types import (
31
+ BaseEmbeddingLookup,
32
+ BaseGroupedFeatureProcessor,
33
+ EmbeddingComputeKernel,
34
+ GroupedEmbeddingConfig,
35
+ SparseFeatures,
36
+ SparseFeaturesList,
37
+ )
38
+ from torchrec.distributed.grouped_position_weighted import GroupedPositionWeightedModule
39
+ from torchrec.distributed.quant_embedding_kernel import (
40
+ QuantBatchedEmbedding,
41
+ QuantBatchedEmbeddingBag,
42
+ )
43
+ from torchrec.distributed.types import ShardedTensor
44
+
45
+ logger: logging.Logger = logging.getLogger(__name__)
46
+
47
+
48
+ def _load_state_dict(
49
+ emb_modules: "nn.ModuleList",
50
+ state_dict: "OrderedDict[str, Union[torch.Tensor, ShardedTensor]]",
51
+ ) -> Tuple[List[str], List[str]]:
52
+ missing_keys = []
53
+ unexpected_keys = list(state_dict.keys())
54
+ for emb_module in emb_modules:
55
+ for key, dst_param in emb_module.state_dict().items():
56
+ if key in state_dict:
57
+ src_param = state_dict[key]
58
+ if isinstance(dst_param, ShardedTensor):
59
+ assert isinstance(src_param, ShardedTensor)
60
+ assert len(dst_param.local_shards()) == len(
61
+ src_param.local_shards()
62
+ )
63
+ for dst_local_shard, src_local_shard in zip(
64
+ dst_param.local_shards(), src_param.local_shards()
65
+ ):
66
+ assert (
67
+ dst_local_shard.metadata.shard_offsets
68
+ == src_local_shard.metadata.shard_offsets
69
+ )
70
+ assert (
71
+ dst_local_shard.metadata.shard_sizes
72
+ == src_local_shard.metadata.shard_sizes
73
+ )
74
+
75
+ dst_local_shard.tensor.detach().copy_(src_local_shard.tensor)
76
+ else:
77
+ assert isinstance(src_param, torch.Tensor) and isinstance(
78
+ dst_param, torch.Tensor
79
+ )
80
+ dst_param.detach().copy_(src_param)
81
+ unexpected_keys.remove(key)
82
+ else:
83
+ missing_keys.append(cast(str, key))
84
+ return missing_keys, unexpected_keys
85
+
86
+
87
+ class GroupedEmbeddingsLookup(BaseEmbeddingLookup[SparseFeatures, torch.Tensor]):
88
+ def __init__(
89
+ self,
90
+ grouped_configs: List[GroupedEmbeddingConfig],
91
+ pg: Optional[dist.ProcessGroup] = None,
92
+ device: Optional[torch.device] = None,
93
+ fused_params: Optional[Dict[str, Any]] = None,
94
+ ) -> None:
95
+ def _create_lookup(
96
+ config: GroupedEmbeddingConfig,
97
+ ) -> BaseEmbedding:
98
+ if config.compute_kernel == EmbeddingComputeKernel.DENSE:
99
+ return BatchedDenseEmbedding(
100
+ config=config,
101
+ pg=pg,
102
+ device=device,
103
+ )
104
+ elif config.compute_kernel == EmbeddingComputeKernel.FUSED:
105
+ return BatchedFusedEmbedding(
106
+ config=config,
107
+ pg=pg,
108
+ device=device,
109
+ fused_params=fused_params,
110
+ )
111
+ else:
112
+ raise ValueError(
113
+ f"Compute kernel not supported {config.compute_kernel}"
114
+ )
115
+
116
+ super().__init__()
117
+ self._emb_modules: nn.ModuleList = nn.ModuleList()
118
+ for config in grouped_configs:
119
+ self._emb_modules.append(_create_lookup(config))
120
+
121
+ self._id_list_feature_splits: List[int] = []
122
+ for config in grouped_configs:
123
+ self._id_list_feature_splits.append(config.num_features())
124
+
125
+ # return a dummy empty tensor when grouped_configs is empty
126
+ self.register_buffer(
127
+ "_dummy_embs_tensor",
128
+ torch.empty(
129
+ [0],
130
+ dtype=torch.float32,
131
+ device=device,
132
+ requires_grad=True,
133
+ ),
134
+ )
135
+
136
+ self.grouped_configs = grouped_configs
137
+
138
+ def forward(
139
+ self,
140
+ sparse_features: SparseFeatures,
141
+ ) -> torch.Tensor:
142
+ assert sparse_features.id_list_features is not None
143
+ embeddings: List[torch.Tensor] = []
144
+ id_list_features_by_group = sparse_features.id_list_features.split(
145
+ self._id_list_feature_splits,
146
+ )
147
+ for emb_op, features in zip(self._emb_modules, id_list_features_by_group):
148
+ embeddings.append(emb_op(features).view(-1))
149
+
150
+ if len(embeddings) == 0:
151
+ # a hack for empty ranks
152
+ return self._dummy_embs_tensor
153
+ elif len(embeddings) == 1:
154
+ return embeddings[0]
155
+ else:
156
+ return torch.cat(embeddings)
157
+
158
+ # pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently.
159
+ def state_dict(
160
+ self,
161
+ destination: Optional[Dict[str, Any]] = None,
162
+ prefix: str = "",
163
+ keep_vars: bool = False,
164
+ ) -> Dict[str, Any]:
165
+ if destination is None:
166
+ destination = OrderedDict()
167
+ # pyre-ignore [16]
168
+ destination._metadata = OrderedDict()
169
+
170
+ for emb_module in self._emb_modules:
171
+ emb_module.state_dict(destination, prefix, keep_vars)
172
+
173
+ return destination
174
+
175
+ # pyre-fixme[14]: `load_state_dict` overrides method defined in `Module`
176
+ # inconsistently.
177
+ def load_state_dict(
178
+ self,
179
+ state_dict: "OrderedDict[str, Union[torch.Tensor, ShardedTensor]]",
180
+ strict: bool = True,
181
+ ) -> _IncompatibleKeys:
182
+ m, u = _load_state_dict(self._emb_modules, state_dict)
183
+ return _IncompatibleKeys(missing_keys=m, unexpected_keys=u)
184
+
185
+ def named_parameters(
186
+ self, prefix: str = "", recurse: bool = True
187
+ ) -> Iterator[Tuple[str, nn.Parameter]]:
188
+ for emb_module in self._emb_modules:
189
+ yield from emb_module.named_parameters(prefix, recurse)
190
+
191
+ def named_buffers(
192
+ self, prefix: str = "", recurse: bool = True
193
+ ) -> Iterator[Tuple[str, torch.Tensor]]:
194
+ for emb_module in self._emb_modules:
195
+ yield from emb_module.named_buffers(prefix, recurse)
196
+
197
+ def sparse_grad_parameter_names(
198
+ self, destination: Optional[List[str]] = None, prefix: str = ""
199
+ ) -> List[str]:
200
+ destination = [] if destination is None else destination
201
+ for emb_module in self._emb_modules:
202
+ emb_module.sparse_grad_parameter_names(destination, prefix)
203
+ return destination
204
+
205
+
206
+ class GroupedPooledEmbeddingsLookup(BaseEmbeddingLookup[SparseFeatures, torch.Tensor]):
207
+ def __init__(
208
+ self,
209
+ grouped_configs: List[GroupedEmbeddingConfig],
210
+ grouped_score_configs: List[GroupedEmbeddingConfig],
211
+ device: Optional[torch.device] = None,
212
+ fused_params: Optional[Dict[str, Any]] = None,
213
+ pg: Optional[dist.ProcessGroup] = None,
214
+ feature_processor: Optional[BaseGroupedFeatureProcessor] = None,
215
+ ) -> None:
216
+ def _create_lookup(
217
+ config: GroupedEmbeddingConfig,
218
+ device: Optional[torch.device] = None,
219
+ ) -> BaseEmbedding:
220
+ if config.compute_kernel == EmbeddingComputeKernel.DENSE:
221
+ return BatchedDenseEmbeddingBag(
222
+ config=config,
223
+ pg=pg,
224
+ device=device,
225
+ )
226
+ elif config.compute_kernel == EmbeddingComputeKernel.FUSED:
227
+ return BatchedFusedEmbeddingBag(
228
+ config=config,
229
+ pg=pg,
230
+ device=device,
231
+ fused_params=fused_params,
232
+ )
233
+ else:
234
+ raise ValueError(
235
+ f"Compute kernel not supported {config.compute_kernel}"
236
+ )
237
+
238
+ super().__init__()
239
+ self._emb_modules: nn.ModuleList = nn.ModuleList()
240
+ for config in grouped_configs:
241
+ self._emb_modules.append(_create_lookup(config, device))
242
+
243
+ self._score_emb_modules: nn.ModuleList = nn.ModuleList()
244
+ for config in grouped_score_configs:
245
+ self._score_emb_modules.append(_create_lookup(config, device))
246
+
247
+ self._id_list_feature_splits: List[int] = []
248
+ for config in grouped_configs:
249
+ self._id_list_feature_splits.append(config.num_features())
250
+ self._id_score_list_feature_splits: List[int] = []
251
+ for config in grouped_score_configs:
252
+ self._id_score_list_feature_splits.append(config.num_features())
253
+
254
+ # return a dummy empty tensor
255
+ # when grouped_configs and grouped_score_configs are empty
256
+ self.register_buffer(
257
+ "_dummy_embs_tensor",
258
+ torch.empty(
259
+ [0],
260
+ dtype=torch.float32,
261
+ device=device,
262
+ requires_grad=True,
263
+ ),
264
+ )
265
+
266
+ self.grouped_configs = grouped_configs
267
+ self.grouped_score_configs = grouped_score_configs
268
+ self._feature_processor = feature_processor
269
+
270
+ def forward(
271
+ self,
272
+ sparse_features: SparseFeatures,
273
+ ) -> torch.Tensor:
274
+ assert (
275
+ sparse_features.id_list_features is not None
276
+ or sparse_features.id_score_list_features is not None
277
+ )
278
+ embeddings: List[torch.Tensor] = []
279
+ if len(self._emb_modules) > 0:
280
+ assert sparse_features.id_list_features is not None
281
+ id_list_features_by_group = sparse_features.id_list_features.split(
282
+ self._id_list_feature_splits,
283
+ )
284
+ for config, emb_op, features in zip(
285
+ self.grouped_configs, self._emb_modules, id_list_features_by_group
286
+ ):
287
+ if (
288
+ config.has_feature_processor
289
+ and self._feature_processor is not None
290
+ and isinstance(self._feature_processor, BaseGroupedFeatureProcessor)
291
+ ):
292
+ features = self._feature_processor(features)
293
+ embeddings.append(emb_op(features))
294
+ if len(self._score_emb_modules) > 0:
295
+ assert sparse_features.id_score_list_features is not None
296
+ id_score_list_features_by_group = (
297
+ sparse_features.id_score_list_features.split(
298
+ self._id_score_list_feature_splits,
299
+ )
300
+ )
301
+ for config, emb_op, features in zip(
302
+ self.grouped_score_configs,
303
+ self._score_emb_modules,
304
+ id_score_list_features_by_group,
305
+ ):
306
+ if (
307
+ config.has_feature_processor
308
+ and self._feature_processor is not None
309
+ and isinstance(self._feature_processor, BaseGroupedFeatureProcessor)
310
+ ):
311
+ features = self._feature_processor(features)
312
+ embeddings.append(emb_op(features))
313
+
314
+ if len(embeddings) == 0:
315
+ # a hack for empty ranks
316
+ batch_size: int = (
317
+ sparse_features.id_list_features.stride()
318
+ if sparse_features.id_list_features is not None
319
+ # pyre-fixme[16]: `Optional` has no attribute `stride`.
320
+ else sparse_features.id_score_list_features.stride()
321
+ )
322
+ return self._dummy_embs_tensor.view(batch_size, 0)
323
+ elif len(embeddings) == 1:
324
+ return embeddings[0]
325
+ else:
326
+ return torch.cat(embeddings, dim=1)
327
+
328
+ # pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently.
329
+ def state_dict(
330
+ self,
331
+ destination: Optional[Dict[str, Any]] = None,
332
+ prefix: str = "",
333
+ keep_vars: bool = False,
334
+ ) -> Dict[str, Any]:
335
+ if destination is None:
336
+ destination = OrderedDict()
337
+ # pyre-ignore [16]
338
+ destination._metadata = OrderedDict()
339
+
340
+ for emb_module in self._emb_modules:
341
+ emb_module.state_dict(destination, prefix, keep_vars)
342
+ for emb_module in self._score_emb_modules:
343
+ emb_module.state_dict(destination, prefix, keep_vars)
344
+
345
+ return destination
346
+
347
+ # pyre-fixme[14]: `load_state_dict` overrides method defined in `Module`
348
+ # inconsistently.
349
+ def load_state_dict(
350
+ self,
351
+ state_dict: "OrderedDict[str, Union[ShardedTensor, torch.Tensor]]",
352
+ strict: bool = True,
353
+ ) -> _IncompatibleKeys:
354
+ m1, u1 = _load_state_dict(self._emb_modules, state_dict)
355
+ m2, u2 = _load_state_dict(self._score_emb_modules, state_dict)
356
+ return _IncompatibleKeys(missing_keys=m1 + m2, unexpected_keys=u1 + u2)
357
+
358
+ def named_parameters(
359
+ self, prefix: str = "", recurse: bool = True
360
+ ) -> Iterator[Tuple[str, nn.Parameter]]:
361
+ for emb_module in self._emb_modules:
362
+ yield from emb_module.named_parameters(prefix, recurse)
363
+ for emb_module in self._score_emb_modules:
364
+ yield from emb_module.named_parameters(prefix, recurse)
365
+
366
+ def named_buffers(
367
+ self, prefix: str = "", recurse: bool = True
368
+ ) -> Iterator[Tuple[str, torch.Tensor]]:
369
+ for emb_module in self._emb_modules:
370
+ yield from emb_module.named_buffers(prefix, recurse)
371
+ for emb_module in self._score_emb_modules:
372
+ yield from emb_module.named_buffers(prefix, recurse)
373
+
374
+ def sparse_grad_parameter_names(
375
+ self, destination: Optional[List[str]] = None, prefix: str = ""
376
+ ) -> List[str]:
377
+ destination = [] if destination is None else destination
378
+ for emb_module in self._emb_modules:
379
+ emb_module.sparse_grad_parameter_names(destination, prefix)
380
+ for emb_module in self._score_emb_modules:
381
+ emb_module.sparse_grad_parameter_names(destination, prefix)
382
+ return destination
383
+
384
+
385
+ class MetaInferGroupedEmbeddingsLookup(
386
+ BaseEmbeddingLookup[SparseFeatures, torch.Tensor]
387
+ ):
388
+ """
389
+ meta embedding lookup module for inference since inference lookup has references
390
+ for multiple TBE ops over all gpu workers.
391
+ inference grouped embedding lookup module contains meta modules allocated over gpu workers.
392
+ """
393
+
394
+ def __init__(
395
+ self,
396
+ grouped_configs: List[GroupedEmbeddingConfig],
397
+ device: Optional[torch.device] = None,
398
+ fused_params: Optional[Dict[str, Any]] = None,
399
+ ) -> None:
400
+ def _create_lookup(
401
+ config: GroupedEmbeddingConfig,
402
+ device: Optional[torch.device] = None,
403
+ fused_params: Optional[Dict[str, Any]] = None,
404
+ ) -> BaseBatchedEmbedding:
405
+ return QuantBatchedEmbedding(
406
+ config=config,
407
+ device=device,
408
+ fused_params=fused_params,
409
+ )
410
+
411
+ super().__init__()
412
+ self._emb_modules: nn.ModuleList = nn.ModuleList()
413
+ for config in grouped_configs:
414
+ self._emb_modules.append(_create_lookup(config, device, fused_params))
415
+
416
+ self._id_list_feature_splits: List[int] = [
417
+ config.num_features() for config in grouped_configs
418
+ ]
419
+
420
+ # return a dummy empty tensor when grouped_configs is empty
421
+ self.register_buffer(
422
+ "_dummy_embs_tensor",
423
+ torch.empty(
424
+ [0],
425
+ dtype=torch.float32,
426
+ device=device,
427
+ ),
428
+ )
429
+
430
+ self.grouped_configs = grouped_configs
431
+
432
+ def forward(
433
+ self,
434
+ sparse_features: SparseFeatures,
435
+ ) -> torch.Tensor:
436
+ assert sparse_features.id_list_features is not None
437
+ embeddings: List[torch.Tensor] = []
438
+ id_list_features_by_group = sparse_features.id_list_features.split(
439
+ self._id_list_feature_splits,
440
+ )
441
+ for emb_op, features in zip(self._emb_modules, id_list_features_by_group):
442
+ embeddings.append(emb_op(features).view(-1))
443
+
444
+ if len(embeddings) == 0:
445
+ # a hack for empty ranks
446
+ return self._dummy_embs_tensor
447
+ elif len(embeddings) == 1:
448
+ return embeddings[0]
449
+ else:
450
+ return torch.cat(embeddings)
451
+
452
+ # pyre-ignore [14]
453
+ def state_dict(
454
+ self,
455
+ destination: Optional[Dict[str, Any]] = None,
456
+ prefix: str = "",
457
+ keep_vars: bool = False,
458
+ ) -> Dict[str, Any]:
459
+ if destination is None:
460
+ destination = OrderedDict()
461
+ # pyre-ignore [16]
462
+ destination._metadata = OrderedDict()
463
+
464
+ for emb_module in self._emb_modules:
465
+ emb_module.state_dict(destination, prefix, keep_vars)
466
+
467
+ return destination
468
+
469
+ # pyre-fixme[14]: `load_state_dict` overrides method defined in `Module`
470
+ # inconsistently.
471
+ def load_state_dict(
472
+ self,
473
+ state_dict: "OrderedDict[str, Union[ShardedTensor, torch.Tensor]]",
474
+ strict: bool = True,
475
+ ) -> _IncompatibleKeys:
476
+ m, u = _load_state_dict(self._emb_modules, state_dict)
477
+ return _IncompatibleKeys(missing_keys=m, unexpected_keys=u)
478
+
479
+ def named_parameters(
480
+ self, prefix: str = "", recurse: bool = True
481
+ ) -> Iterator[Tuple[str, nn.Parameter]]:
482
+ for emb_module in self._emb_modules:
483
+ yield from emb_module.named_parameters(prefix, recurse)
484
+
485
+ def named_buffers(
486
+ self, prefix: str = "", recurse: bool = True
487
+ ) -> Iterator[Tuple[str, torch.Tensor]]:
488
+ for emb_module in self._emb_modules:
489
+ yield from emb_module.named_buffers(prefix, recurse)
490
+
491
+
492
+ class MetaInferGroupedPooledEmbeddingsLookup(
493
+ BaseEmbeddingLookup[SparseFeatures, torch.Tensor]
494
+ ):
495
+ """
496
+ meta embedding bag lookup module for inference since inference lookup has references
497
+ for multiple TBE ops over all gpu workers.
498
+ inference grouped embedding bag lookup module contains meta modules allocated over gpu workers.
499
+ """
500
+
501
+ def __init__(
502
+ self,
503
+ grouped_configs: List[GroupedEmbeddingConfig],
504
+ grouped_score_configs: List[GroupedEmbeddingConfig],
505
+ device: Optional[torch.device] = None,
506
+ feature_processor: Optional[BaseGroupedFeatureProcessor] = None,
507
+ fused_params: Optional[Dict[str, Any]] = None,
508
+ ) -> None:
509
+ def _create_lookup(
510
+ config: GroupedEmbeddingConfig,
511
+ device: Optional[torch.device] = None,
512
+ fused_params: Optional[Dict[str, Any]] = None,
513
+ ) -> BaseBatchedEmbeddingBag:
514
+ return QuantBatchedEmbeddingBag(
515
+ config=config,
516
+ device=device,
517
+ fused_params=fused_params,
518
+ )
519
+
520
+ super().__init__()
521
+ self._emb_modules: nn.ModuleList = nn.ModuleList()
522
+ for config in grouped_configs:
523
+ self._emb_modules.append(_create_lookup(config, device, fused_params))
524
+
525
+ self._score_emb_modules: nn.ModuleList = nn.ModuleList()
526
+ for config in grouped_score_configs:
527
+ self._score_emb_modules.append(_create_lookup(config, device))
528
+
529
+ self._id_list_feature_splits: List[int] = [
530
+ config.num_features() for config in grouped_configs
531
+ ]
532
+ self._id_score_list_feature_splits: List[int] = [
533
+ config.num_features() for config in grouped_score_configs
534
+ ]
535
+
536
+ # return a dummy empty tensor
537
+ # when grouped_configs and grouped_score_configs are empty
538
+ self.register_buffer(
539
+ "_dummy_embs_tensor",
540
+ torch.empty(
541
+ [0],
542
+ dtype=torch.float32,
543
+ device=device,
544
+ ),
545
+ )
546
+
547
+ self.grouped_configs = grouped_configs
548
+ self.grouped_score_configs = grouped_score_configs
549
+ self._feature_processor = feature_processor
550
+
551
+ def forward(
552
+ self,
553
+ sparse_features: SparseFeatures,
554
+ ) -> torch.Tensor:
555
+ assert (
556
+ sparse_features.id_list_features is not None
557
+ or sparse_features.id_score_list_features is not None
558
+ )
559
+ embeddings: List[torch.Tensor] = []
560
+ if len(self._emb_modules) > 0:
561
+ assert sparse_features.id_list_features is not None
562
+ id_list_features_by_group = sparse_features.id_list_features.split(
563
+ self._id_list_feature_splits,
564
+ )
565
+ for config, emb_op, features in zip(
566
+ self.grouped_configs, self._emb_modules, id_list_features_by_group
567
+ ):
568
+ if (
569
+ config.has_feature_processor
570
+ and self._feature_processor is not None
571
+ and isinstance(self._feature_processor, BaseGroupedFeatureProcessor)
572
+ ):
573
+ features = self._feature_processor(features)
574
+ embeddings.append(emb_op(features))
575
+ if len(self._score_emb_modules) > 0:
576
+ assert sparse_features.id_score_list_features is not None
577
+ id_score_list_features_by_group = (
578
+ sparse_features.id_score_list_features.split(
579
+ self._id_score_list_feature_splits,
580
+ )
581
+ )
582
+ for emb_op, features in zip(
583
+ self._score_emb_modules, id_score_list_features_by_group
584
+ ):
585
+ embeddings.append(emb_op(features))
586
+
587
+ if len(embeddings) == 0:
588
+ # a hack for empty ranks
589
+ batch_size: int = (
590
+ sparse_features.id_list_features.stride()
591
+ if sparse_features.id_list_features is not None
592
+ # pyre-fixme[16]: `Optional` has no attribute `stride`.
593
+ else sparse_features.id_score_list_features.stride()
594
+ )
595
+ return self._dummy_embs_tensor.view(batch_size, 0)
596
+ elif len(embeddings) == 1:
597
+ return embeddings[0]
598
+ else:
599
+ return torch.cat(embeddings, dim=1)
600
+
601
+ # pyre-ignore [14]
602
+ def state_dict(
603
+ self,
604
+ destination: Optional[Dict[str, Any]] = None,
605
+ prefix: str = "",
606
+ keep_vars: bool = False,
607
+ ) -> Dict[str, Any]:
608
+ if destination is None:
609
+ destination = OrderedDict()
610
+ # pyre-ignore [16]
611
+ destination._metadata = OrderedDict()
612
+
613
+ for emb_module in self._emb_modules:
614
+ emb_module.state_dict(destination, prefix, keep_vars)
615
+ for emb_module in self._score_emb_modules:
616
+ emb_module.state_dict(destination, prefix, keep_vars)
617
+
618
+ return destination
619
+
620
+ # pyre-fixme[14]: `load_state_dict` overrides method defined in `Module`
621
+ # inconsistently.
622
+ def load_state_dict(
623
+ self,
624
+ state_dict: "OrderedDict[str, Union[ShardedTensor, torch.Tensor]]",
625
+ strict: bool = True,
626
+ ) -> _IncompatibleKeys:
627
+ m1, u1 = _load_state_dict(self._emb_modules, state_dict)
628
+ m2, u2 = _load_state_dict(self._score_emb_modules, state_dict)
629
+ return _IncompatibleKeys(missing_keys=m1 + m2, unexpected_keys=u1 + u2)
630
+
631
+ def named_parameters(
632
+ self, prefix: str = "", recurse: bool = True
633
+ ) -> Iterator[Tuple[str, nn.Parameter]]:
634
+ for emb_module in self._emb_modules:
635
+ yield from emb_module.named_parameters(prefix, recurse)
636
+ for emb_module in self._score_emb_modules:
637
+ yield from emb_module.named_parameters(prefix, recurse)
638
+
639
+ def named_buffers(
640
+ self, prefix: str = "", recurse: bool = True
641
+ ) -> Iterator[Tuple[str, torch.Tensor]]:
642
+ for emb_module in self._emb_modules:
643
+ yield from emb_module.named_buffers(prefix, recurse)
644
+ for emb_module in self._score_emb_modules:
645
+ yield from emb_module.named_buffers(prefix, recurse)
646
+
647
+
648
+ class InferGroupedLookupMixin(ABC):
649
+ def forward(
650
+ self,
651
+ sparse_features: SparseFeaturesList,
652
+ ) -> List[torch.Tensor]:
653
+ embeddings: List[torch.Tensor] = []
654
+ for sparse_features_rank, embedding_lookup in zip(
655
+ sparse_features,
656
+ # pyre-fixme[16]
657
+ self._embedding_lookups_per_rank,
658
+ ):
659
+ assert (
660
+ sparse_features_rank.id_list_features is not None
661
+ or sparse_features_rank.id_score_list_features is not None
662
+ )
663
+ embeddings.append(embedding_lookup(sparse_features_rank))
664
+ return embeddings
665
+
666
+ def state_dict(
667
+ self,
668
+ destination: Optional[Dict[str, Any]] = None,
669
+ prefix: str = "",
670
+ keep_vars: bool = False,
671
+ ) -> Dict[str, Any]:
672
+ if destination is None:
673
+ destination = OrderedDict()
674
+ # pyre-ignore [16]
675
+ destination._metadata = OrderedDict()
676
+
677
+ # pyre-fixme[16]
678
+ for rank_modules in self._embedding_lookups_per_rank:
679
+ rank_modules.state_dict(destination, prefix, keep_vars)
680
+
681
+ return destination
682
+
683
+ def load_state_dict(
684
+ self,
685
+ state_dict: "OrderedDict[str, torch.Tensor]",
686
+ strict: bool = True,
687
+ ) -> _IncompatibleKeys:
688
+ missing_keys = []
689
+ unexpected_keys = []
690
+ # pyre-fixme[16]
691
+ for rank_modules in self._embedding_lookups_per_rank:
692
+ incompatible_keys = rank_modules.load_state_dict(state_dict)
693
+ missing_keys.extend(incompatible_keys.missing_keys)
694
+ unexpected_keys.extend(incompatible_keys.unexpected_keys)
695
+ return _IncompatibleKeys(
696
+ missing_keys=missing_keys, unexpected_keys=unexpected_keys
697
+ )
698
+
699
+ def named_parameters(
700
+ self, prefix: str = "", recurse: bool = True
701
+ ) -> Iterator[Tuple[str, nn.Parameter]]:
702
+ # pyre-fixme[16]
703
+ for rank_modules in self._embedding_lookups_per_rank:
704
+ yield from rank_modules.named_parameters(prefix, recurse)
705
+
706
+ def named_buffers(
707
+ self, prefix: str = "", recurse: bool = True
708
+ ) -> Iterator[Tuple[str, torch.Tensor]]:
709
+ # pyre-fixme[16]
710
+ for rank_modules in self._embedding_lookups_per_rank:
711
+ yield from rank_modules.named_buffers(prefix, recurse)
712
+
713
+
714
+ class InferGroupedPooledEmbeddingsLookup(
715
+ InferGroupedLookupMixin,
716
+ BaseEmbeddingLookup[SparseFeaturesList, List[torch.Tensor]],
717
+ ):
718
+ def __init__(
719
+ self,
720
+ grouped_configs_per_rank: List[List[GroupedEmbeddingConfig]],
721
+ grouped_score_configs_per_rank: List[List[GroupedEmbeddingConfig]],
722
+ world_size: int,
723
+ fused_params: Optional[Dict[str, Any]] = None,
724
+ ) -> None:
725
+ super().__init__()
726
+ self._embedding_lookups_per_rank: List[
727
+ MetaInferGroupedPooledEmbeddingsLookup
728
+ ] = []
729
+ for rank in range(world_size):
730
+ self._embedding_lookups_per_rank.append(
731
+ # TODO add position weighted module support
732
+ MetaInferGroupedPooledEmbeddingsLookup(
733
+ grouped_configs=grouped_configs_per_rank[rank],
734
+ grouped_score_configs=grouped_score_configs_per_rank[rank],
735
+ device=torch.device("cuda", rank),
736
+ fused_params=fused_params,
737
+ )
738
+ )
739
+
740
+
741
+ class InferGroupedEmbeddingsLookup(
742
+ InferGroupedLookupMixin,
743
+ BaseEmbeddingLookup[SparseFeaturesList, List[torch.Tensor]],
744
+ ):
745
+ def __init__(
746
+ self,
747
+ grouped_configs_per_rank: List[List[GroupedEmbeddingConfig]],
748
+ world_size: int,
749
+ fused_params: Optional[Dict[str, Any]] = None,
750
+ ) -> None:
751
+ super().__init__()
752
+ self._embedding_lookups_per_rank: List[MetaInferGroupedEmbeddingsLookup] = []
753
+ for rank in range(world_size):
754
+ self._embedding_lookups_per_rank.append(
755
+ MetaInferGroupedEmbeddingsLookup(
756
+ grouped_configs=grouped_configs_per_rank[rank],
757
+ device=torch.device("cuda", rank),
758
+ fused_params=fused_params,
759
+ )
760
+ )