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,731 @@
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 copy
9
+ from collections import OrderedDict
10
+ from typing import Any, Dict, Iterator, List, Mapping, Optional, Set, Tuple, Type, Union
11
+
12
+ import torch
13
+ from torch import nn, Tensor
14
+ from torch.nn.modules.module import _IncompatibleKeys
15
+ from torchrec.distributed.embedding_sharding import (
16
+ EmbeddingSharding,
17
+ EmbeddingShardingInfo,
18
+ SparseFeaturesListAwaitable,
19
+ )
20
+ from torchrec.distributed.embedding_types import (
21
+ BaseEmbeddingSharder,
22
+ EmbeddingComputeKernel,
23
+ SparseFeatures,
24
+ SparseFeaturesList,
25
+ )
26
+ from torchrec.distributed.sharding.cw_sharding import CwPooledEmbeddingSharding
27
+ from torchrec.distributed.sharding.dp_sharding import DpPooledEmbeddingSharding
28
+ from torchrec.distributed.sharding.rw_sharding import RwPooledEmbeddingSharding
29
+ from torchrec.distributed.sharding.tw_sharding import TwPooledEmbeddingSharding
30
+ from torchrec.distributed.sharding.twcw_sharding import TwCwPooledEmbeddingSharding
31
+ from torchrec.distributed.sharding.twrw_sharding import TwRwPooledEmbeddingSharding
32
+ from torchrec.distributed.types import (
33
+ Awaitable,
34
+ EnumerableShardingSpec,
35
+ LazyAwaitable,
36
+ ParameterSharding,
37
+ ShardedModule,
38
+ ShardedModuleContext,
39
+ ShardedTensor,
40
+ ShardingEnv,
41
+ ShardingType,
42
+ )
43
+ from torchrec.distributed.utils import append_prefix, filter_state_dict
44
+ from torchrec.modules.embedding_configs import EmbeddingTableConfig, PoolingType
45
+ from torchrec.modules.embedding_modules import (
46
+ EmbeddingBagCollection,
47
+ EmbeddingBagCollectionInterface,
48
+ )
49
+ from torchrec.optim.fused import FusedOptimizerModule
50
+ from torchrec.optim.keyed import CombinedOptimizer, KeyedOptimizer
51
+ from torchrec.sparse.jagged_tensor import KeyedJaggedTensor, KeyedTensor
52
+
53
+
54
+ def replace_placement_with_meta_device(
55
+ sharding_infos: List[EmbeddingShardingInfo],
56
+ ) -> None:
57
+ """Placement device and tensor device could be unmatched in some
58
+ scenarios, e.g. passing meta device to DMP and passing cuda
59
+ to EmbeddingShardingPlanner. We need to make device consistent
60
+ after getting sharding planner.
61
+ """
62
+ for info in sharding_infos:
63
+ sharding_spec = info.param_sharding.sharding_spec
64
+ if sharding_spec is None:
65
+ continue
66
+ if isinstance(sharding_spec, EnumerableShardingSpec):
67
+ for shard_metadata in sharding_spec.shards:
68
+ placement = shard_metadata.placement
69
+ if isinstance(placement, str):
70
+ placement = torch.distributed._remote_device(placement)
71
+ assert isinstance(placement, torch.distributed._remote_device)
72
+ placement._device = torch.device("meta")
73
+ shard_metadata.placement = placement
74
+ else:
75
+ # We only support EnumerableShardingSpec at present.
76
+ raise RuntimeError(
77
+ f"Unsupported ShardingSpec {type(sharding_spec)} with meta device"
78
+ )
79
+
80
+
81
+ def create_embedding_bag_sharding(
82
+ sharding_type: str,
83
+ sharding_infos: List[EmbeddingShardingInfo],
84
+ env: ShardingEnv,
85
+ device: Optional[torch.device] = None,
86
+ permute_embeddings: bool = False,
87
+ ) -> EmbeddingSharding[SparseFeatures, torch.Tensor]:
88
+ if device is not None and device.type == "meta":
89
+ replace_placement_with_meta_device(sharding_infos)
90
+ if sharding_type == ShardingType.TABLE_WISE.value:
91
+ return TwPooledEmbeddingSharding(sharding_infos, env, device)
92
+ elif sharding_type == ShardingType.ROW_WISE.value:
93
+ return RwPooledEmbeddingSharding(sharding_infos, env, device)
94
+ elif sharding_type == ShardingType.DATA_PARALLEL.value:
95
+ return DpPooledEmbeddingSharding(sharding_infos, env, device)
96
+ elif sharding_type == ShardingType.TABLE_ROW_WISE.value:
97
+ return TwRwPooledEmbeddingSharding(sharding_infos, env, device)
98
+ elif sharding_type == ShardingType.COLUMN_WISE.value:
99
+ return CwPooledEmbeddingSharding(
100
+ sharding_infos, env, device, permute_embeddings=permute_embeddings
101
+ )
102
+ elif sharding_type == ShardingType.TABLE_COLUMN_WISE.value:
103
+ return TwCwPooledEmbeddingSharding(
104
+ sharding_infos, env, device, permute_embeddings=permute_embeddings
105
+ )
106
+ else:
107
+ raise ValueError(f"Sharding type not supported {sharding_type}")
108
+
109
+
110
+ def create_sharding_infos_by_sharding(
111
+ module: EmbeddingBagCollectionInterface,
112
+ table_name_to_parameter_sharding: Dict[str, ParameterSharding],
113
+ prefix: str,
114
+ ) -> Dict[str, List[EmbeddingShardingInfo]]:
115
+ shared_feature: Dict[str, bool] = {}
116
+ for embedding_config in module.embedding_bag_configs:
117
+ if not embedding_config.feature_names:
118
+ embedding_config.feature_names = [embedding_config.name]
119
+ for feature_name in embedding_config.feature_names:
120
+ if feature_name not in shared_feature:
121
+ shared_feature[feature_name] = False
122
+ else:
123
+ shared_feature[feature_name] = True
124
+
125
+ sharding_type_to_sharding_infos: Dict[str, List[EmbeddingShardingInfo]] = {}
126
+ state_dict = module.state_dict()
127
+ for config in module.embedding_bag_configs:
128
+ table_name = config.name
129
+ assert table_name in table_name_to_parameter_sharding
130
+ parameter_sharding = table_name_to_parameter_sharding[table_name]
131
+ if parameter_sharding.compute_kernel not in [
132
+ kernel.value for kernel in EmbeddingComputeKernel
133
+ ]:
134
+ raise ValueError(
135
+ f"Compute kernel not supported {parameter_sharding.compute_kernel}"
136
+ )
137
+ embedding_names: List[str] = []
138
+ for feature_name in config.feature_names:
139
+ if shared_feature[feature_name]:
140
+ embedding_names.append(feature_name + "@" + config.name)
141
+ else:
142
+ embedding_names.append(feature_name)
143
+
144
+ param_name = prefix + table_name + ".weight"
145
+ assert param_name in state_dict
146
+ param = state_dict[param_name]
147
+
148
+ if parameter_sharding.sharding_type not in sharding_type_to_sharding_infos:
149
+ sharding_type_to_sharding_infos[parameter_sharding.sharding_type] = []
150
+ sharding_type_to_sharding_infos[parameter_sharding.sharding_type].append(
151
+ EmbeddingShardingInfo(
152
+ embedding_config=EmbeddingTableConfig(
153
+ num_embeddings=config.num_embeddings,
154
+ embedding_dim=config.embedding_dim,
155
+ name=config.name,
156
+ data_type=config.data_type,
157
+ feature_names=copy.deepcopy(config.feature_names),
158
+ pooling=config.pooling,
159
+ is_weighted=module.is_weighted,
160
+ has_feature_processor=False,
161
+ embedding_names=embedding_names,
162
+ weight_init_max=config.weight_init_max,
163
+ weight_init_min=config.weight_init_min,
164
+ ),
165
+ param_sharding=parameter_sharding,
166
+ param=param,
167
+ )
168
+ )
169
+ return sharding_type_to_sharding_infos
170
+
171
+
172
+ class EmbeddingBagCollectionAwaitable(LazyAwaitable[KeyedTensor]):
173
+ def __init__(
174
+ self,
175
+ awaitables: List[Awaitable[torch.Tensor]],
176
+ embedding_dims: List[int],
177
+ embedding_names: List[str],
178
+ ) -> None:
179
+ super().__init__()
180
+ self._awaitables = awaitables
181
+ self._embedding_dims = embedding_dims
182
+ self._embedding_names = embedding_names
183
+
184
+ def _wait_impl(self) -> KeyedTensor:
185
+ embeddings = [w.wait() for w in self._awaitables]
186
+ if len(embeddings) == 1:
187
+ embeddings = embeddings[0]
188
+ else:
189
+ embeddings = torch.cat(embeddings, dim=1)
190
+ return KeyedTensor(
191
+ keys=self._embedding_names,
192
+ length_per_key=self._embedding_dims,
193
+ values=embeddings,
194
+ key_dim=1,
195
+ )
196
+
197
+
198
+ class ShardedEmbeddingBagCollection(
199
+ ShardedModule[SparseFeaturesList, List[torch.Tensor], KeyedTensor],
200
+ FusedOptimizerModule,
201
+ ):
202
+ """
203
+ Sharded implementation of EmbeddingBagCollection.
204
+ This is part of the public API to allow for manual data dist pipelining.
205
+ """
206
+
207
+ def __init__(
208
+ self,
209
+ module: EmbeddingBagCollectionInterface,
210
+ table_name_to_parameter_sharding: Dict[str, ParameterSharding],
211
+ env: ShardingEnv,
212
+ fused_params: Optional[Dict[str, Any]] = None,
213
+ device: Optional[torch.device] = None,
214
+ ) -> None:
215
+ super().__init__()
216
+ sharding_type_to_sharding_infos = create_sharding_infos_by_sharding(
217
+ module, table_name_to_parameter_sharding, "embedding_bags."
218
+ )
219
+ self._sharding_type_to_sharding: Dict[
220
+ str, EmbeddingSharding[SparseFeatures, torch.Tensor]
221
+ ] = {
222
+ sharding_type: create_embedding_bag_sharding(
223
+ sharding_type, embedding_confings, env, device, permute_embeddings=True
224
+ )
225
+ for sharding_type, embedding_confings in sharding_type_to_sharding_infos.items()
226
+ }
227
+
228
+ self._is_weighted: bool = module.is_weighted
229
+ self._device = device
230
+ self._input_dists = nn.ModuleList()
231
+ self._lookups: nn.ModuleList = nn.ModuleList()
232
+ self._create_lookups(fused_params)
233
+ self._output_dists: nn.ModuleList = nn.ModuleList()
234
+ self._embedding_names: List[str] = []
235
+ self._embedding_dims: List[int] = []
236
+ self._feature_splits: List[int] = []
237
+ self._features_order: List[int] = []
238
+ # to support the FP16 hook
239
+ self._create_output_dist()
240
+
241
+ # forward pass flow control
242
+ self._has_uninitialized_input_dist: bool = True
243
+ self._has_features_permute: bool = True
244
+ # Get all fused optimizers and combine them.
245
+ optims = []
246
+ for lookup in self._lookups:
247
+ for _, module in lookup.named_modules():
248
+ if isinstance(module, FusedOptimizerModule):
249
+ # modify param keys to match EmbeddingBagCollection
250
+ params: Mapping[str, Union[torch.Tensor, ShardedTensor]] = {}
251
+ for param_key, weight in module.fused_optimizer.params.items():
252
+ # pyre-fixme[16]: `Mapping` has no attribute `__setitem__`.
253
+ params["embedding_bags." + param_key] = weight
254
+ module.fused_optimizer.params = params
255
+ optims.append(("", module.fused_optimizer))
256
+ self._optim: CombinedOptimizer = CombinedOptimizer(optims)
257
+
258
+ def _create_input_dist(
259
+ self,
260
+ input_feature_names: List[str],
261
+ ) -> None:
262
+ feature_names: List[str] = []
263
+ for sharding in self._sharding_type_to_sharding.values():
264
+ self._input_dists.append(sharding.create_input_dist())
265
+ feature_names.extend(
266
+ sharding.id_score_list_feature_names()
267
+ if self._is_weighted
268
+ else sharding.id_list_feature_names()
269
+ )
270
+ self._feature_splits.append(
271
+ len(
272
+ sharding.id_score_list_feature_names()
273
+ if self._is_weighted
274
+ else sharding.id_list_feature_names()
275
+ )
276
+ )
277
+
278
+ if feature_names == input_feature_names:
279
+ self._has_features_permute = False
280
+ else:
281
+ for f in feature_names:
282
+ self._features_order.append(input_feature_names.index(f))
283
+ self.register_buffer(
284
+ "_features_order_tensor",
285
+ torch.tensor(
286
+ self._features_order, device=self._device, dtype=torch.int32
287
+ ),
288
+ )
289
+
290
+ def _create_lookups(
291
+ self,
292
+ fused_params: Optional[Dict[str, Any]],
293
+ ) -> None:
294
+ for sharding in self._sharding_type_to_sharding.values():
295
+ self._lookups.append(sharding.create_lookup(fused_params=fused_params))
296
+
297
+ def _create_output_dist(self) -> None:
298
+ for sharding in self._sharding_type_to_sharding.values():
299
+ self._output_dists.append(sharding.create_output_dist(device=self._device))
300
+ self._embedding_names.extend(sharding.embedding_names())
301
+ self._embedding_dims.extend(sharding.embedding_dims())
302
+
303
+ # pyre-ignore [14]
304
+ def input_dist(
305
+ self, ctx: ShardedModuleContext, features: KeyedJaggedTensor
306
+ ) -> Awaitable[SparseFeaturesList]:
307
+ if self._has_uninitialized_input_dist:
308
+ self._create_input_dist(features.keys())
309
+ self._has_uninitialized_input_dist = False
310
+ with torch.no_grad():
311
+ if self._has_features_permute:
312
+ features = features.permute(
313
+ self._features_order,
314
+ # pyre-ignore [6]
315
+ self._features_order_tensor,
316
+ )
317
+ features_by_shards = features.split(
318
+ self._feature_splits,
319
+ )
320
+ awaitables = []
321
+ for module, features_by_shard in zip(self._input_dists, features_by_shards):
322
+ all2all_lengths = module(
323
+ SparseFeatures(
324
+ id_list_features=None
325
+ if self._is_weighted
326
+ else features_by_shard,
327
+ id_score_list_features=features_by_shard
328
+ if self._is_weighted
329
+ else None,
330
+ )
331
+ )
332
+ awaitables.append(all2all_lengths.wait())
333
+ return SparseFeaturesListAwaitable(awaitables)
334
+
335
+ def compute(
336
+ self,
337
+ ctx: ShardedModuleContext,
338
+ dist_input: SparseFeaturesList,
339
+ ) -> List[torch.Tensor]:
340
+ return [lookup(features) for lookup, features in zip(self._lookups, dist_input)]
341
+
342
+ def output_dist(
343
+ self,
344
+ ctx: ShardedModuleContext,
345
+ output: List[torch.Tensor],
346
+ ) -> LazyAwaitable[KeyedTensor]:
347
+ return EmbeddingBagCollectionAwaitable(
348
+ awaitables=[
349
+ dist(embeddings) for dist, embeddings in zip(self._output_dists, output)
350
+ ],
351
+ embedding_dims=self._embedding_dims,
352
+ embedding_names=self._embedding_names,
353
+ )
354
+
355
+ def compute_and_output_dist(
356
+ self, ctx: ShardedModuleContext, input: SparseFeaturesList
357
+ ) -> LazyAwaitable[KeyedTensor]:
358
+ return EmbeddingBagCollectionAwaitable(
359
+ awaitables=[
360
+ dist(lookup(features))
361
+ for lookup, dist, features in zip(
362
+ self._lookups,
363
+ self._output_dists,
364
+ input,
365
+ )
366
+ ],
367
+ embedding_dims=self._embedding_dims,
368
+ embedding_names=self._embedding_names,
369
+ )
370
+
371
+ # pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently.
372
+ def state_dict(
373
+ self,
374
+ destination: Optional[Dict[str, Any]] = None,
375
+ prefix: str = "",
376
+ keep_vars: bool = False,
377
+ ) -> Dict[str, Any]:
378
+ if destination is None:
379
+ destination = OrderedDict()
380
+ # pyre-ignore [16]
381
+ destination._metadata = OrderedDict()
382
+ for lookup in self._lookups:
383
+ lookup.state_dict(destination, prefix + "embedding_bags.", keep_vars)
384
+ return destination
385
+
386
+ def named_modules(
387
+ self,
388
+ memo: Optional[Set[nn.Module]] = None,
389
+ prefix: str = "",
390
+ remove_duplicate: bool = True,
391
+ ) -> Iterator[Tuple[str, nn.Module]]:
392
+ yield from [(prefix, self)]
393
+
394
+ def named_parameters(
395
+ self, prefix: str = "", recurse: bool = True
396
+ ) -> Iterator[Tuple[str, nn.Parameter]]:
397
+ for lookup in self._lookups:
398
+ yield from lookup.named_parameters(
399
+ append_prefix(prefix, "embedding_bags"), recurse
400
+ )
401
+
402
+ def sharded_parameter_names(self, prefix: str = "") -> Iterator[str]:
403
+ for lookup, sharding_type in zip(
404
+ self._lookups, self._sharding_type_to_sharding.keys()
405
+ ):
406
+ if sharding_type == ShardingType.DATA_PARALLEL.value:
407
+ continue
408
+ for name, _ in lookup.named_parameters(
409
+ append_prefix(prefix, "embedding_bags")
410
+ ):
411
+ yield name
412
+
413
+ def named_buffers(
414
+ self, prefix: str = "", recurse: bool = True
415
+ ) -> Iterator[Tuple[str, torch.Tensor]]:
416
+ for lookup in self._lookups:
417
+ yield from lookup.named_buffers(
418
+ append_prefix(prefix, "embedding_bags"), recurse
419
+ )
420
+
421
+ # pyre-fixme[14]: `load_state_dict` overrides method defined in `Module`
422
+ # inconsistently.
423
+ def load_state_dict(
424
+ self,
425
+ state_dict: "OrderedDict[str, torch.Tensor]",
426
+ strict: bool = True,
427
+ ) -> _IncompatibleKeys:
428
+ missing_keys = []
429
+ unexpected_keys = []
430
+ for lookup in self._lookups:
431
+ missing, unexpected = lookup.load_state_dict(
432
+ filter_state_dict(state_dict, "embedding_bags"),
433
+ strict,
434
+ )
435
+ missing_keys.extend(missing)
436
+ unexpected_keys.extend(unexpected)
437
+ return _IncompatibleKeys(
438
+ missing_keys=missing_keys, unexpected_keys=unexpected_keys
439
+ )
440
+
441
+ def sparse_grad_parameter_names(
442
+ self,
443
+ destination: Optional[List[str]] = None,
444
+ prefix: str = "",
445
+ ) -> List[str]:
446
+ destination = [] if destination is None else destination
447
+ for lookup in self._lookups:
448
+ lookup.sparse_grad_parameter_names(
449
+ destination, append_prefix(prefix, "embedding_bags")
450
+ )
451
+ return destination
452
+
453
+ @property
454
+ def fused_optimizer(self) -> KeyedOptimizer:
455
+ return self._optim
456
+
457
+
458
+ class EmbeddingBagCollectionSharder(BaseEmbeddingSharder[EmbeddingBagCollection]):
459
+ """
460
+ This implementation uses non-fused `EmbeddingBagCollection`
461
+ """
462
+
463
+ def shard(
464
+ self,
465
+ module: EmbeddingBagCollection,
466
+ params: Dict[str, ParameterSharding],
467
+ env: ShardingEnv,
468
+ device: Optional[torch.device] = None,
469
+ ) -> ShardedEmbeddingBagCollection:
470
+ return ShardedEmbeddingBagCollection(
471
+ module, params, env, self.fused_params, device
472
+ )
473
+
474
+ def shardable_parameters(
475
+ self, module: EmbeddingBagCollection
476
+ ) -> Dict[str, nn.Parameter]:
477
+ return {
478
+ name.split(".")[0]: param
479
+ for name, param in module.embedding_bags.named_parameters()
480
+ }
481
+
482
+ @property
483
+ def module_type(self) -> Type[EmbeddingBagCollection]:
484
+ return EmbeddingBagCollection
485
+
486
+
487
+ class EmbeddingAwaitable(LazyAwaitable[torch.Tensor]):
488
+ def __init__(
489
+ self,
490
+ awaitable: Awaitable[torch.Tensor],
491
+ ) -> None:
492
+ super().__init__()
493
+ self._awaitable = awaitable
494
+
495
+ def _wait_impl(self) -> torch.Tensor:
496
+ embedding = self._awaitable.wait()
497
+ return embedding
498
+
499
+
500
+ class ShardedEmbeddingBag(
501
+ ShardedModule[
502
+ SparseFeatures,
503
+ torch.Tensor,
504
+ torch.Tensor,
505
+ ],
506
+ FusedOptimizerModule,
507
+ ):
508
+ """
509
+ Sharded implementation of `nn.EmbeddingBag`.
510
+ This is part of the public API to allow for manual data dist pipelining.
511
+ """
512
+
513
+ def __init__(
514
+ self,
515
+ module: nn.EmbeddingBag,
516
+ table_name_to_parameter_sharding: Dict[str, ParameterSharding],
517
+ env: ShardingEnv,
518
+ fused_params: Optional[Dict[str, Any]] = None,
519
+ device: Optional[torch.device] = None,
520
+ ) -> None:
521
+ super().__init__()
522
+
523
+ assert (
524
+ len(table_name_to_parameter_sharding) == 1
525
+ ), "expect 1 table, but got len(table_name_to_parameter_sharding)"
526
+ assert module.mode == "sum", "ShardedEmbeddingBag only supports sum pooling"
527
+
528
+ self._dummy_embedding_table_name = "dummy_embedding_table_name"
529
+ self._dummy_feature_name = "dummy_feature_name"
530
+ self.parameter_sharding: ParameterSharding = next(
531
+ iter(table_name_to_parameter_sharding.values())
532
+ )
533
+ embedding_table_config = EmbeddingTableConfig(
534
+ num_embeddings=module.num_embeddings,
535
+ embedding_dim=module.embedding_dim,
536
+ name=self._dummy_embedding_table_name,
537
+ feature_names=[self._dummy_feature_name],
538
+ pooling=PoolingType.SUM,
539
+ # We set is_weighted to True for now,
540
+ # if per_sample_weights is None in forward(),
541
+ # we could assign a all-one vector to per_sample_weights
542
+ is_weighted=True,
543
+ embedding_names=[self._dummy_feature_name],
544
+ )
545
+
546
+ if self.parameter_sharding.sharding_type == ShardingType.TABLE_WISE.value:
547
+ # TODO: enable it with correct semantics, see T104397332
548
+ raise RuntimeError(
549
+ "table-wise sharding on a single EmbeddingBag is not supported yet"
550
+ )
551
+
552
+ self._embedding_sharding: EmbeddingSharding[
553
+ SparseFeatures, torch.Tensor
554
+ ] = create_embedding_bag_sharding(
555
+ sharding_type=self.parameter_sharding.sharding_type,
556
+ sharding_infos=[
557
+ EmbeddingShardingInfo(
558
+ embedding_config=embedding_table_config,
559
+ param_sharding=self.parameter_sharding,
560
+ param=next(iter(module.parameters())),
561
+ ),
562
+ ],
563
+ env=env,
564
+ device=device,
565
+ permute_embeddings=True,
566
+ )
567
+ self._input_dist: nn.Module = self._embedding_sharding.create_input_dist()
568
+ self._lookup: nn.Module = self._embedding_sharding.create_lookup(
569
+ fused_params=fused_params
570
+ )
571
+ self._output_dist: nn.Module = self._embedding_sharding.create_output_dist()
572
+
573
+ # Get all fused optimizers and combine them.
574
+ optims = []
575
+ for _, module in self._lookup.named_modules():
576
+ if isinstance(module, FusedOptimizerModule):
577
+ # modify param keys to match EmbeddingBag
578
+ params: Mapping[str, Union[torch.Tensor, ShardedTensor]] = {}
579
+ for param_key, weight in module.fused_optimizer.params.items():
580
+ # pyre-fixme[16]: `Mapping` has no attribute `__setitem__`.
581
+ params[param_key.split(".")[-1]] = weight
582
+ module.fused_optimizer.params = params
583
+ optims.append(("", module.fused_optimizer))
584
+ self._optim: CombinedOptimizer = CombinedOptimizer(optims)
585
+
586
+ # pyre-ignore [14]
587
+ def input_dist(
588
+ self,
589
+ ctx: ShardedModuleContext,
590
+ input: Tensor,
591
+ offsets: Optional[Tensor] = None,
592
+ per_sample_weights: Optional[Tensor] = None,
593
+ ) -> Awaitable[SparseFeatures]:
594
+ if per_sample_weights is None:
595
+ per_sample_weights = torch.ones_like(input, dtype=torch.float)
596
+ features = KeyedJaggedTensor(
597
+ keys=[self._dummy_feature_name],
598
+ values=input,
599
+ offsets=offsets,
600
+ weights=per_sample_weights,
601
+ )
602
+ return self._input_dist(
603
+ SparseFeatures(
604
+ id_list_features=None,
605
+ id_score_list_features=features,
606
+ )
607
+ ).wait()
608
+
609
+ def compute(
610
+ self, ctx: ShardedModuleContext, dist_input: SparseFeatures
611
+ ) -> torch.Tensor:
612
+ return self._lookup(dist_input)
613
+
614
+ def output_dist(
615
+ self, ctx: ShardedModuleContext, output: torch.Tensor
616
+ ) -> LazyAwaitable[torch.Tensor]:
617
+ return EmbeddingAwaitable(
618
+ awaitable=self._output_dist(output),
619
+ )
620
+
621
+ # pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently.
622
+ def state_dict(
623
+ self,
624
+ destination: Optional[Dict[str, Any]] = None,
625
+ prefix: str = "",
626
+ keep_vars: bool = False,
627
+ ) -> Dict[str, Any]:
628
+ if destination is None:
629
+ destination = OrderedDict()
630
+ # pyre-ignore [16]
631
+ destination._metadata = OrderedDict()
632
+ # pyre-fixme[19]: Expected 0 positional arguments.
633
+ lookup_state_dict = self._lookup.state_dict(None, "", keep_vars)
634
+ # update key to match embeddingBag state_dict key
635
+ for key, item in lookup_state_dict.items():
636
+ new_key = prefix + key.split(".")[-1]
637
+ destination[new_key] = item
638
+ return destination
639
+
640
+ def named_modules(
641
+ self,
642
+ memo: Optional[Set[nn.Module]] = None,
643
+ prefix: str = "",
644
+ remove_duplicate: bool = True,
645
+ ) -> Iterator[Tuple[str, nn.Module]]:
646
+ yield from [(prefix, self)]
647
+
648
+ def named_parameters(
649
+ self, prefix: str = "", recurse: bool = True
650
+ ) -> Iterator[Tuple[str, nn.Parameter]]:
651
+ for name, parameter in self._lookup.named_parameters("", recurse):
652
+ # update name to match embeddingBag parameter name
653
+ yield append_prefix(prefix, name.split(".")[-1]), parameter
654
+
655
+ def sharded_parameter_names(self, prefix: str = "") -> Iterator[str]:
656
+ if self.parameter_sharding.sharding_type == ShardingType.DATA_PARALLEL.value:
657
+ yield from []
658
+ else:
659
+ for name, _ in self._lookup.named_parameters(""):
660
+ yield append_prefix(prefix, name.split(".")[-1])
661
+
662
+ def named_buffers(
663
+ self, prefix: str = "", recurse: bool = True
664
+ ) -> Iterator[Tuple[str, torch.Tensor]]:
665
+ for name, buffer in self._lookup.named_buffers("", recurse):
666
+ yield append_prefix(prefix, name.split(".")[-1]), buffer
667
+
668
+ # pyre-fixme[14]: `load_state_dict` overrides method defined in `Module`
669
+ # inconsistently.
670
+ def load_state_dict(
671
+ self,
672
+ state_dict: "OrderedDict[str, torch.Tensor]",
673
+ strict: bool = True,
674
+ ) -> _IncompatibleKeys:
675
+ missing_keys = []
676
+ unexpected_keys = []
677
+ # update key to match embeddingBag state_dict key
678
+ for key, value in state_dict.items():
679
+ new_key = ".".join([self._dummy_embedding_table_name, key])
680
+ state_dict[new_key] = value
681
+ state_dict.pop(key)
682
+ missing, unexpected = self._lookup.load_state_dict(
683
+ state_dict,
684
+ strict,
685
+ )
686
+ missing_keys.extend(missing)
687
+ unexpected_keys.extend(unexpected)
688
+
689
+ return _IncompatibleKeys(
690
+ missing_keys=missing_keys, unexpected_keys=unexpected_keys
691
+ )
692
+
693
+ def sparse_grad_parameter_names(
694
+ self,
695
+ destination: Optional[List[str]] = None,
696
+ prefix: str = "",
697
+ ) -> List[str]:
698
+ destination = [] if destination is None else destination
699
+ # pyre-ignore [29]
700
+ lookup_sparse_grad_parameter_names = self._lookup.sparse_grad_parameter_names(
701
+ None, ""
702
+ )
703
+ for name in lookup_sparse_grad_parameter_names:
704
+ destination.append(name.split(".")[-1])
705
+ return destination
706
+
707
+ @property
708
+ def fused_optimizer(self) -> KeyedOptimizer:
709
+ return self._optim
710
+
711
+
712
+ class EmbeddingBagSharder(BaseEmbeddingSharder[nn.EmbeddingBag]):
713
+ """
714
+ This implementation uses non-fused `nn.EmbeddingBag`
715
+ """
716
+
717
+ def shard(
718
+ self,
719
+ module: nn.EmbeddingBag,
720
+ params: Dict[str, ParameterSharding],
721
+ env: ShardingEnv,
722
+ device: Optional[torch.device] = None,
723
+ ) -> ShardedEmbeddingBag:
724
+ return ShardedEmbeddingBag(module, params, env, self.fused_params, device)
725
+
726
+ def shardable_parameters(self, module: nn.EmbeddingBag) -> Dict[str, nn.Parameter]:
727
+ return {name: param for name, param in module.named_parameters()}
728
+
729
+ @property
730
+ def module_type(self) -> Type[nn.EmbeddingBag]:
731
+ return nn.EmbeddingBag