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,697 @@
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
+ import copy
10
+ import itertools
11
+ import logging
12
+ from dataclasses import dataclass
13
+ from typing import Any, cast, Dict, Iterator, List, Optional, Tuple, Union
14
+
15
+ import torch
16
+ import torch.distributed as dist
17
+ from fbgemm_gpu.split_embedding_configs import SparseType
18
+ from fbgemm_gpu.split_table_batched_embeddings_ops import (
19
+ ComputeDevice,
20
+ DenseTableBatchedEmbeddingBagsCodegen,
21
+ EmbeddingLocation,
22
+ IntNBitTableBatchedEmbeddingBagsCodegen,
23
+ PoolingMode,
24
+ SplitTableBatchedEmbeddingBagsCodegen,
25
+ )
26
+ from torch import nn
27
+ from torchrec.distributed.embedding_kernel import BaseEmbedding, get_state_dict
28
+ from torchrec.distributed.embedding_types import (
29
+ compute_kernel_to_embedding_location,
30
+ GroupedEmbeddingConfig,
31
+ )
32
+ from torchrec.distributed.types import (
33
+ Shard,
34
+ ShardedTensor,
35
+ ShardedTensorMetadata,
36
+ ShardMetadata,
37
+ TensorProperties,
38
+ )
39
+ from torchrec.distributed.utils import append_prefix
40
+ from torchrec.modules.embedding_configs import (
41
+ data_type_to_sparse_type,
42
+ pooling_type_to_pooling_mode,
43
+ )
44
+ from torchrec.optim.fused import FusedOptimizer, FusedOptimizerModule
45
+ from torchrec.sparse.jagged_tensor import KeyedJaggedTensor
46
+
47
+ logger: logging.Logger = logging.getLogger(__name__)
48
+
49
+
50
+ class EmbeddingFusedOptimizer(FusedOptimizer):
51
+ def __init__( # noqa C901
52
+ self,
53
+ config: GroupedEmbeddingConfig,
54
+ emb_module: SplitTableBatchedEmbeddingBagsCodegen,
55
+ pg: Optional[dist.ProcessGroup] = None,
56
+ ) -> None:
57
+ self._emb_module: SplitTableBatchedEmbeddingBagsCodegen = emb_module
58
+ self._pg = pg
59
+
60
+ @dataclass
61
+ class ShardParams:
62
+ optimizer_states: List[Optional[Tuple[torch.Tensor]]]
63
+ local_metadata: List[ShardMetadata]
64
+ embedding_weights: List[torch.Tensor]
65
+
66
+ def to_rowwise_sharded_metadata(
67
+ local_metadata: ShardMetadata,
68
+ global_metadata: ShardedTensorMetadata,
69
+ sharding_dim: int,
70
+ ) -> Tuple[ShardMetadata, ShardedTensorMetadata]:
71
+ rw_shards: List[ShardMetadata] = []
72
+ rw_local_shard: ShardMetadata = local_metadata
73
+ shards_metadata = global_metadata.shards_metadata
74
+ # column-wise sharding
75
+ # sort the metadata based on column offset and
76
+ # we construct the momentum tensor in row-wise sharded way
77
+ if sharding_dim == 1:
78
+ shards_metadata = sorted(
79
+ shards_metadata, key=lambda shard: shard.shard_offsets[1]
80
+ )
81
+
82
+ for idx, shard in enumerate(shards_metadata):
83
+ offset = shard.shard_offsets[0]
84
+ # for column-wise sharding, we still create row-wise sharded metadata for optimizer
85
+ # manually create a row-wise offset
86
+
87
+ if sharding_dim == 1:
88
+ offset = idx * shard.shard_sizes[0]
89
+ rw_shard = ShardMetadata(
90
+ shard_sizes=[shard.shard_sizes[0]],
91
+ shard_offsets=[offset],
92
+ placement=shard.placement,
93
+ )
94
+
95
+ if local_metadata == shard:
96
+ rw_local_shard = rw_shard
97
+
98
+ rw_shards.append(rw_shard)
99
+
100
+ tensor_properties = TensorProperties(
101
+ dtype=global_metadata.tensor_properties.dtype,
102
+ layout=global_metadata.tensor_properties.layout,
103
+ requires_grad=global_metadata.tensor_properties.requires_grad,
104
+ memory_format=global_metadata.tensor_properties.memory_format,
105
+ pin_memory=global_metadata.tensor_properties.pin_memory,
106
+ )
107
+ len_rw_shards = len(shards_metadata) if sharding_dim == 1 else 1
108
+ rw_metadata = ShardedTensorMetadata(
109
+ shards_metadata=rw_shards,
110
+ size=torch.Size([global_metadata.size[0] * len_rw_shards]),
111
+ tensor_properties=tensor_properties,
112
+ )
113
+ return rw_local_shard, rw_metadata
114
+
115
+ # pyre-ignore [33]
116
+ state: Dict[Any, Any] = {}
117
+ param_group: Dict[str, Any] = {
118
+ "params": [],
119
+ "lr": emb_module.optimizer_args.learning_rate,
120
+ }
121
+
122
+ params: Dict[str, Union[torch.Tensor, ShardedTensor]] = {}
123
+
124
+ # Fused optimizers use buffers (they don't use autograd) and we want to make sure
125
+ # that state_dict look identical to no-fused version.
126
+ table_to_shard_params = {}
127
+
128
+ split_embedding_weights = emb_module.split_embedding_weights()
129
+ split_optimizer_states = emb_module.split_optimizer_states()
130
+
131
+ for table_config, optimizer_states, weight in itertools.zip_longest(
132
+ config.embedding_tables,
133
+ split_optimizer_states,
134
+ split_embedding_weights,
135
+ ):
136
+ if table_config.name not in table_to_shard_params:
137
+ table_to_shard_params[table_config.name] = ShardParams(
138
+ optimizer_states=[], local_metadata=[], embedding_weights=[]
139
+ )
140
+
141
+ if optimizer_states:
142
+ for optimizer_state in optimizer_states:
143
+ assert table_config.local_rows == optimizer_state.size(0)
144
+
145
+ local_metadata = table_config.local_metadata
146
+
147
+ table_to_shard_params[table_config.name].optimizer_states.append(
148
+ optimizer_states
149
+ )
150
+ table_to_shard_params[table_config.name].local_metadata.append(
151
+ local_metadata
152
+ )
153
+ table_to_shard_params[table_config.name].embedding_weights.append(weight)
154
+
155
+ seen_tables = set()
156
+ for table_config in config.embedding_tables:
157
+ if table_config.name in seen_tables:
158
+ continue
159
+ seen_tables.add(table_config.name)
160
+ table_config_global_metadata: Optional[
161
+ ShardedTensorMetadata
162
+ ] = copy.deepcopy(table_config.global_metadata)
163
+
164
+ shard_params: ShardParams = table_to_shard_params[table_config.name]
165
+
166
+ assert table_config_global_metadata is not None
167
+ local_weight_shards = []
168
+ for local_weight, local_metadata in zip(
169
+ shard_params.embedding_weights, shard_params.local_metadata
170
+ ):
171
+ local_weight_shards.append(Shard(local_weight, local_metadata))
172
+ table_config_global_metadata.tensor_properties.dtype = (
173
+ local_weight.dtype
174
+ )
175
+ table_config_global_metadata.tensor_properties.requires_grad = (
176
+ local_weight.requires_grad
177
+ )
178
+
179
+ weight = ShardedTensor._init_from_local_shards_and_global_metadata(
180
+ local_shards=local_weight_shards,
181
+ sharded_tensor_metadata=table_config_global_metadata,
182
+ process_group=self._pg,
183
+ )
184
+
185
+ state[weight] = {}
186
+ param_group["params"].append(weight)
187
+ param_key = table_config.name + ".weight"
188
+ params[param_key] = weight
189
+
190
+ # Setting optimizer states
191
+ sharding_dim: int = (
192
+ 1 if table_config.local_cols != table_config.embedding_dim else 0
193
+ )
194
+
195
+ if all(
196
+ [opt_state is not None for opt_state in shard_params.optimizer_states]
197
+ ):
198
+ # pyre-ignore
199
+ def get_momentum(momentum_idx: int) -> ShardedTensor:
200
+ assert momentum_idx > 0
201
+ momentum_local_shards: List[Shard] = []
202
+
203
+ sharded_tensor_metadata = table_config.global_metadata
204
+ for (optimizer_state, shard_param_local_metadata) in zip(
205
+ shard_params.optimizer_states, shard_params.local_metadata
206
+ ):
207
+
208
+ local_metadata = table_config.local_metadata
209
+
210
+ if optimizer_state[momentum_idx - 1].dim() == 1:
211
+ (
212
+ local_metadata,
213
+ sharded_tensor_metadata,
214
+ ) = to_rowwise_sharded_metadata(
215
+ shard_param_local_metadata,
216
+ table_config.global_metadata,
217
+ sharding_dim,
218
+ )
219
+
220
+ assert local_metadata is not None
221
+ assert sharded_tensor_metadata is not None
222
+ momentum_local_shards.append(
223
+ Shard(optimizer_state[momentum_idx - 1], local_metadata)
224
+ )
225
+
226
+ return ShardedTensor._init_from_local_shards_and_global_metadata(
227
+ local_shards=momentum_local_shards,
228
+ sharded_tensor_metadata=sharded_tensor_metadata,
229
+ process_group=self._pg,
230
+ )
231
+
232
+ if all(
233
+ # pyre-ignore
234
+ [len(opt_state) >= 1 for opt_state in shard_params.optimizer_states]
235
+ ):
236
+ state[weight][f"{table_config.name}.momentum1"] = get_momentum(1)
237
+ if all(
238
+ # pyre-ignore
239
+ [len(opt_state) >= 2 for opt_state in shard_params.optimizer_states]
240
+ ):
241
+ state[weight][f"{table_config.name}.momentum2"] = get_momentum(2)
242
+
243
+ super().__init__(params, state, [param_group])
244
+
245
+ def zero_grad(self, set_to_none: bool = False) -> None:
246
+ # pyre-ignore [16]
247
+ self._emb_module.set_learning_rate(self.param_groups[0]["lr"])
248
+
249
+ # pyre-ignore [2]
250
+ def step(self, closure: Any = None) -> None:
251
+ # pyre-ignore [16]
252
+ self._emb_module.set_learning_rate(self.param_groups[0]["lr"])
253
+
254
+
255
+ def configure_fused_params(
256
+ fused_params: Optional[Dict[str, Any]], weights_precision: SparseType
257
+ ) -> Dict[str, Any]:
258
+
259
+ """
260
+ Configure the fused_params including cache_precision if the value is not preset
261
+
262
+ Args:
263
+ fused_params (Optional[Dict[str, Any]]): the original fused_params
264
+ weights_precision (SparseType): the weights_precision to be used for
265
+ the embedding lookup kernel
266
+
267
+ Returns:
268
+ [Dict[str, Any]]: a non-null configured fused_params dictionary to be
269
+ used to configure the embedding lookup kernel
270
+ """
271
+
272
+ if fused_params is None:
273
+ fused_params = {}
274
+ if "cache_precision" not in fused_params:
275
+ # Set cache_precision to be the same as weights_precision
276
+ # if it is not preset
277
+ fused_params["cache_precision"] = weights_precision
278
+
279
+ return fused_params
280
+
281
+
282
+ class BaseBatchedEmbedding(BaseEmbedding):
283
+ def __init__(
284
+ self,
285
+ config: GroupedEmbeddingConfig,
286
+ pg: Optional[dist.ProcessGroup] = None,
287
+ device: Optional[torch.device] = None,
288
+ ) -> None:
289
+ super().__init__()
290
+ torch._C._log_api_usage_once(f"torchrec.distributed.{self.__class__.__name__}")
291
+ self._config = config
292
+ self._pg = pg
293
+
294
+ self._local_rows: List[int] = []
295
+ self._weight_init_mins: List[float] = []
296
+ self._weight_init_maxs: List[float] = []
297
+ self._num_embeddings: List[int] = []
298
+ self._local_cols: List[int] = []
299
+ self._feature_table_map: List[int] = []
300
+
301
+ for idx, config in enumerate(self._config.embedding_tables):
302
+ self._local_rows.append(config.local_rows)
303
+ self._weight_init_mins.append(config.get_weight_init_min())
304
+ self._weight_init_maxs.append(config.get_weight_init_max())
305
+ self._num_embeddings.append(config.num_embeddings)
306
+ self._local_cols.append(config.local_cols)
307
+ self._feature_table_map.extend([idx] * config.num_features())
308
+
309
+ def init_parameters(self) -> None:
310
+ # initialize embedding weights
311
+ assert len(self._num_embeddings) == len(self.split_embedding_weights())
312
+ for (rows, emb_dim, weight_init_min, weight_init_max, param) in zip(
313
+ self._local_rows,
314
+ self._local_cols,
315
+ self._weight_init_mins,
316
+ self._weight_init_maxs,
317
+ self.split_embedding_weights(),
318
+ ):
319
+ assert param.shape == (rows, emb_dim)
320
+ param.data.uniform_(
321
+ weight_init_min,
322
+ weight_init_max,
323
+ )
324
+
325
+ def forward(self, features: KeyedJaggedTensor) -> torch.Tensor:
326
+ return self.emb_module(
327
+ indices=features.values().long(),
328
+ offsets=features.offsets().long(),
329
+ )
330
+
331
+ # pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently.
332
+ def state_dict(
333
+ self,
334
+ destination: Optional[Dict[str, Any]] = None,
335
+ prefix: str = "",
336
+ keep_vars: bool = False,
337
+ ) -> Dict[str, Any]:
338
+ self.flush()
339
+ return get_state_dict(
340
+ self._config.embedding_tables,
341
+ self.split_embedding_weights(),
342
+ self._pg,
343
+ destination,
344
+ prefix,
345
+ )
346
+
347
+ def split_embedding_weights(self) -> List[torch.Tensor]:
348
+ return self.emb_module.split_embedding_weights()
349
+
350
+ @property
351
+ @abc.abstractmethod
352
+ def emb_module(
353
+ self,
354
+ ) -> Union[
355
+ DenseTableBatchedEmbeddingBagsCodegen,
356
+ SplitTableBatchedEmbeddingBagsCodegen,
357
+ IntNBitTableBatchedEmbeddingBagsCodegen,
358
+ ]:
359
+ ...
360
+
361
+ @property
362
+ def config(self) -> GroupedEmbeddingConfig:
363
+ return self._config
364
+
365
+ def flush(self) -> None:
366
+ pass
367
+
368
+ def named_buffers(
369
+ self, prefix: str = "", recurse: bool = True
370
+ ) -> Iterator[Tuple[str, torch.Tensor]]:
371
+ for config, param in zip(
372
+ self._config.embedding_tables,
373
+ self.emb_module.split_embedding_weights(),
374
+ ):
375
+ key = append_prefix(prefix, f"{config.name}.weight")
376
+ yield key, param
377
+
378
+
379
+ class BatchedFusedEmbedding(BaseBatchedEmbedding, FusedOptimizerModule):
380
+ def __init__(
381
+ self,
382
+ config: GroupedEmbeddingConfig,
383
+ pg: Optional[dist.ProcessGroup] = None,
384
+ device: Optional[torch.device] = None,
385
+ fused_params: Optional[Dict[str, Any]] = None,
386
+ ) -> None:
387
+ super().__init__(config, pg, device)
388
+
389
+ managed: List[EmbeddingLocation] = []
390
+ compute_devices: List[ComputeDevice] = []
391
+ for table in config.embedding_tables:
392
+ if device is not None and device.type == "cuda":
393
+ compute_devices.append(ComputeDevice.CUDA)
394
+ managed.append(
395
+ compute_kernel_to_embedding_location(table.compute_kernel)
396
+ )
397
+ else:
398
+ compute_devices.append(ComputeDevice.CPU)
399
+ managed.append(EmbeddingLocation.HOST)
400
+ weights_precision = data_type_to_sparse_type(config.data_type)
401
+ fused_params = configure_fused_params(
402
+ fused_params=fused_params, weights_precision=weights_precision
403
+ )
404
+ self._emb_module: SplitTableBatchedEmbeddingBagsCodegen = (
405
+ SplitTableBatchedEmbeddingBagsCodegen(
406
+ embedding_specs=list(
407
+ zip(self._local_rows, self._local_cols, managed, compute_devices)
408
+ ),
409
+ feature_table_map=self._feature_table_map,
410
+ pooling_mode=PoolingMode.NONE,
411
+ weights_precision=weights_precision,
412
+ device=device,
413
+ **(fused_params or {}),
414
+ )
415
+ )
416
+ self._optim: EmbeddingFusedOptimizer = EmbeddingFusedOptimizer(
417
+ config,
418
+ self._emb_module,
419
+ pg,
420
+ )
421
+
422
+ self.init_parameters()
423
+
424
+ @property
425
+ def emb_module(
426
+ self,
427
+ ) -> SplitTableBatchedEmbeddingBagsCodegen:
428
+ return self._emb_module
429
+
430
+ @property
431
+ def fused_optimizer(self) -> FusedOptimizer:
432
+ return self._optim
433
+
434
+ def named_parameters(
435
+ self, prefix: str = "", recurse: bool = True
436
+ ) -> Iterator[Tuple[str, nn.Parameter]]:
437
+ yield from ()
438
+
439
+ def named_buffers(
440
+ self, prefix: str = "", recurse: bool = True
441
+ ) -> Iterator[Tuple[str, torch.Tensor]]:
442
+ for config, param in zip(
443
+ self._config.embedding_tables,
444
+ self.emb_module.split_embedding_weights(),
445
+ ):
446
+ key = append_prefix(prefix, f"{config.name}.weight")
447
+ yield key, param
448
+
449
+ def flush(self) -> None:
450
+ self._emb_module.flush()
451
+
452
+
453
+ class BatchedDenseEmbedding(BaseBatchedEmbedding):
454
+ def __init__(
455
+ self,
456
+ config: GroupedEmbeddingConfig,
457
+ pg: Optional[dist.ProcessGroup] = None,
458
+ device: Optional[torch.device] = None,
459
+ ) -> None:
460
+ super().__init__(config, pg, device)
461
+
462
+ self._emb_module: DenseTableBatchedEmbeddingBagsCodegen = (
463
+ DenseTableBatchedEmbeddingBagsCodegen(
464
+ list(zip(self._local_rows, self._local_cols)),
465
+ feature_table_map=self._feature_table_map,
466
+ pooling_mode=PoolingMode.NONE,
467
+ use_cpu=device is None
468
+ or device.type == "cpu"
469
+ or not torch.cuda.is_available(),
470
+ )
471
+ )
472
+
473
+ self.init_parameters()
474
+
475
+ @property
476
+ def emb_module(
477
+ self,
478
+ ) -> DenseTableBatchedEmbeddingBagsCodegen:
479
+ return self._emb_module
480
+
481
+ def named_parameters(
482
+ self, prefix: str = "", recurse: bool = True
483
+ ) -> Iterator[Tuple[str, nn.Parameter]]:
484
+ combined_key = "/".join(
485
+ [config.name for config in self._config.embedding_tables]
486
+ )
487
+ yield append_prefix(prefix, f"{combined_key}.weight"), cast(
488
+ nn.Parameter, self._emb_module.weights
489
+ )
490
+
491
+
492
+ class BaseBatchedEmbeddingBag(BaseEmbedding):
493
+ def __init__(
494
+ self,
495
+ config: GroupedEmbeddingConfig,
496
+ pg: Optional[dist.ProcessGroup] = None,
497
+ device: Optional[torch.device] = None,
498
+ ) -> None:
499
+ super().__init__()
500
+ torch._C._log_api_usage_once(f"torchrec.distributed.{self.__class__.__name__}")
501
+ self._config = config
502
+ self._pg = pg
503
+
504
+ self._pooling: PoolingMode = pooling_type_to_pooling_mode(config.pooling)
505
+
506
+ self._local_rows: List[int] = []
507
+ self._weight_init_mins: List[float] = []
508
+ self._weight_init_maxs: List[float] = []
509
+ self._num_embeddings: List[int] = []
510
+ self._local_cols: List[int] = []
511
+ self._feature_table_map: List[int] = []
512
+ self._emb_names: List[str] = []
513
+ self._lengths_per_emb: List[int] = []
514
+
515
+ for idx, config in enumerate(self._config.embedding_tables):
516
+ self._local_rows.append(config.local_rows)
517
+ self._weight_init_mins.append(config.get_weight_init_min())
518
+ self._weight_init_maxs.append(config.get_weight_init_max())
519
+ self._num_embeddings.append(config.num_embeddings)
520
+ self._local_cols.append(config.local_cols)
521
+ self._feature_table_map.extend([idx] * config.num_features())
522
+
523
+ def init_parameters(self) -> None:
524
+ # initialize embedding weights
525
+ assert len(self._num_embeddings) == len(self.split_embedding_weights())
526
+ for (rows, emb_dim, weight_init_min, weight_init_max, param) in zip(
527
+ self._local_rows,
528
+ self._local_cols,
529
+ self._weight_init_mins,
530
+ self._weight_init_maxs,
531
+ self.split_embedding_weights(),
532
+ ):
533
+ assert param.shape == (rows, emb_dim)
534
+ param.data.uniform_(
535
+ weight_init_min,
536
+ weight_init_max,
537
+ )
538
+
539
+ def forward(self, features: KeyedJaggedTensor) -> torch.Tensor:
540
+ weights = features.weights_or_none()
541
+ if weights is not None and not torch.is_floating_point(weights):
542
+ weights = None
543
+ return self.emb_module(
544
+ indices=features.values().long(),
545
+ offsets=features.offsets().long(),
546
+ per_sample_weights=weights,
547
+ )
548
+
549
+ # pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently.
550
+ def state_dict(
551
+ self,
552
+ destination: Optional[Dict[str, Any]] = None,
553
+ prefix: str = "",
554
+ keep_vars: bool = False,
555
+ ) -> Dict[str, Any]:
556
+ self.flush()
557
+ return get_state_dict(
558
+ self._config.embedding_tables,
559
+ self.split_embedding_weights(),
560
+ self._pg,
561
+ destination,
562
+ prefix,
563
+ )
564
+
565
+ def split_embedding_weights(self) -> List[torch.Tensor]:
566
+ return self.emb_module.split_embedding_weights()
567
+
568
+ @property
569
+ @abc.abstractmethod
570
+ def emb_module(
571
+ self,
572
+ ) -> Union[
573
+ DenseTableBatchedEmbeddingBagsCodegen,
574
+ SplitTableBatchedEmbeddingBagsCodegen,
575
+ IntNBitTableBatchedEmbeddingBagsCodegen,
576
+ ]:
577
+ ...
578
+
579
+ @property
580
+ def config(self) -> GroupedEmbeddingConfig:
581
+ return self._config
582
+
583
+ def flush(self) -> None:
584
+ pass
585
+
586
+ def named_buffers(
587
+ self, prefix: str = "", recurse: bool = True
588
+ ) -> Iterator[Tuple[str, torch.Tensor]]:
589
+ for config, param in zip(
590
+ self._config.embedding_tables,
591
+ self.emb_module.split_embedding_weights(),
592
+ ):
593
+ key = append_prefix(prefix, f"{config.name}.weight")
594
+ yield key, param
595
+
596
+
597
+ class BatchedFusedEmbeddingBag(BaseBatchedEmbeddingBag, FusedOptimizerModule):
598
+ def __init__(
599
+ self,
600
+ config: GroupedEmbeddingConfig,
601
+ pg: Optional[dist.ProcessGroup] = None,
602
+ device: Optional[torch.device] = None,
603
+ fused_params: Optional[Dict[str, Any]] = None,
604
+ ) -> None:
605
+ super().__init__(config, pg, device)
606
+
607
+ managed: List[EmbeddingLocation] = []
608
+ compute_devices: List[ComputeDevice] = []
609
+ for table in config.embedding_tables:
610
+ if device is not None and device.type == "cuda":
611
+ compute_devices.append(ComputeDevice.CUDA)
612
+ managed.append(
613
+ compute_kernel_to_embedding_location(table.compute_kernel)
614
+ )
615
+ else:
616
+ compute_devices.append(ComputeDevice.CPU)
617
+ managed.append(EmbeddingLocation.HOST)
618
+ weights_precision = data_type_to_sparse_type(config.data_type)
619
+ fused_params = configure_fused_params(
620
+ fused_params=fused_params, weights_precision=weights_precision
621
+ )
622
+ self._emb_module: SplitTableBatchedEmbeddingBagsCodegen = (
623
+ SplitTableBatchedEmbeddingBagsCodegen(
624
+ embedding_specs=list(
625
+ zip(self._local_rows, self._local_cols, managed, compute_devices)
626
+ ),
627
+ feature_table_map=self._feature_table_map,
628
+ pooling_mode=self._pooling,
629
+ weights_precision=weights_precision,
630
+ device=device,
631
+ **(fused_params or {}),
632
+ )
633
+ )
634
+ self._optim: EmbeddingFusedOptimizer = EmbeddingFusedOptimizer(
635
+ config,
636
+ self._emb_module,
637
+ pg,
638
+ )
639
+
640
+ self.init_parameters()
641
+
642
+ @property
643
+ def emb_module(
644
+ self,
645
+ ) -> SplitTableBatchedEmbeddingBagsCodegen:
646
+ return self._emb_module
647
+
648
+ @property
649
+ def fused_optimizer(self) -> FusedOptimizer:
650
+ return self._optim
651
+
652
+ def named_parameters(
653
+ self, prefix: str = "", recurse: bool = True
654
+ ) -> Iterator[Tuple[str, nn.Parameter]]:
655
+ yield from ()
656
+
657
+ def flush(self) -> None:
658
+ self._emb_module.flush()
659
+
660
+
661
+ class BatchedDenseEmbeddingBag(BaseBatchedEmbeddingBag):
662
+ def __init__(
663
+ self,
664
+ config: GroupedEmbeddingConfig,
665
+ pg: Optional[dist.ProcessGroup] = None,
666
+ device: Optional[torch.device] = None,
667
+ ) -> None:
668
+ super().__init__(config, pg, device)
669
+
670
+ self._emb_module: DenseTableBatchedEmbeddingBagsCodegen = (
671
+ DenseTableBatchedEmbeddingBagsCodegen(
672
+ list(zip(self._local_rows, self._local_cols)),
673
+ feature_table_map=self._feature_table_map,
674
+ pooling_mode=self._pooling,
675
+ use_cpu=device is None
676
+ or device.type == "cpu"
677
+ or not torch.cuda.is_available(),
678
+ )
679
+ )
680
+
681
+ self.init_parameters()
682
+
683
+ @property
684
+ def emb_module(
685
+ self,
686
+ ) -> DenseTableBatchedEmbeddingBagsCodegen:
687
+ return self._emb_module
688
+
689
+ def named_parameters(
690
+ self, prefix: str = "", recurse: bool = True
691
+ ) -> Iterator[Tuple[str, nn.Parameter]]:
692
+ combined_key = "/".join(
693
+ [config.name for config in self._config.embedding_tables]
694
+ )
695
+ yield append_prefix(prefix, f"{combined_key}.weight"), cast(
696
+ nn.Parameter, self._emb_module.weights
697
+ )