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,818 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ from dataclasses import dataclass
9
+ from typing import Any, cast, Dict, List, Optional, Tuple, Union
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ from torchrec.distributed.embedding_tower_sharding import (
14
+ EmbeddingTowerCollectionSharder,
15
+ EmbeddingTowerSharder,
16
+ )
17
+ from torchrec.distributed.embedding_types import EmbeddingTableConfig
18
+ from torchrec.distributed.embeddingbag import (
19
+ EmbeddingBagCollectionSharder,
20
+ EmbeddingBagSharder,
21
+ )
22
+ from torchrec.distributed.fused_embeddingbag import FusedEmbeddingBagCollectionSharder
23
+ from torchrec.modules.embedding_configs import BaseEmbeddingConfig, EmbeddingBagConfig
24
+ from torchrec.modules.embedding_modules import EmbeddingBagCollection
25
+ from torchrec.modules.embedding_tower import EmbeddingTower, EmbeddingTowerCollection
26
+ from torchrec.sparse.jagged_tensor import KeyedJaggedTensor, KeyedTensor
27
+ from torchrec.streamable import Pipelineable
28
+
29
+
30
+ @dataclass
31
+ class ModelInput(Pipelineable):
32
+ float_features: torch.Tensor
33
+ idlist_features: KeyedJaggedTensor
34
+ idscore_features: KeyedJaggedTensor
35
+ label: torch.Tensor
36
+
37
+ @staticmethod
38
+ def generate(
39
+ batch_size: int,
40
+ world_size: int,
41
+ num_float_features: int,
42
+ tables: Union[List[EmbeddingTableConfig], List[EmbeddingBagConfig]],
43
+ weighted_tables: Union[List[EmbeddingTableConfig], List[EmbeddingBagConfig]],
44
+ pooling_avg: int = 10,
45
+ ) -> Tuple["ModelInput", List["ModelInput"]]:
46
+ """
47
+ Returns a global (single-rank training) batch
48
+ and a list of local (multi-rank training) batches of world_size.
49
+ """
50
+ idlist_features = [
51
+ feature for table in tables for feature in table.feature_names
52
+ ]
53
+ idscore_features = [
54
+ feature for table in weighted_tables for feature in table.feature_names
55
+ ]
56
+
57
+ idlist_ind_ranges = [table.num_embeddings for table in tables]
58
+ idscore_ind_ranges = [table.num_embeddings for table in weighted_tables]
59
+
60
+ # Generate global batch.
61
+ global_idlist_lengths = []
62
+ global_idlist_indices = []
63
+ global_idscore_lengths = []
64
+ global_idscore_indices = []
65
+ global_idscore_weights = []
66
+
67
+ for ind_range in idlist_ind_ranges:
68
+ lengths = torch.abs(
69
+ torch.randn(batch_size * world_size) + pooling_avg
70
+ ).int()
71
+ num_indices = cast(int, torch.sum(lengths).item())
72
+ indices = torch.randint(0, ind_range, (num_indices,))
73
+ global_idlist_lengths.append(lengths)
74
+ global_idlist_indices.append(indices)
75
+ global_idlist_kjt = KeyedJaggedTensor(
76
+ keys=idlist_features,
77
+ values=torch.cat(global_idlist_indices),
78
+ lengths=torch.cat(global_idlist_lengths),
79
+ )
80
+
81
+ for ind_range in idscore_ind_ranges:
82
+ lengths = torch.abs(
83
+ torch.randn(batch_size * world_size) + pooling_avg
84
+ ).int()
85
+ num_indices = cast(int, torch.sum(lengths).item())
86
+ indices = torch.randint(0, ind_range, (num_indices,))
87
+ weights = torch.rand((num_indices,))
88
+ global_idscore_lengths.append(lengths)
89
+ global_idscore_indices.append(indices)
90
+ global_idscore_weights.append(weights)
91
+ global_idscore_kjt = (
92
+ KeyedJaggedTensor(
93
+ keys=idscore_features,
94
+ values=torch.cat(global_idscore_indices),
95
+ lengths=torch.cat(global_idscore_lengths),
96
+ weights=torch.cat(global_idscore_weights),
97
+ )
98
+ if global_idscore_indices
99
+ else None
100
+ )
101
+
102
+ global_float = torch.rand((batch_size * world_size, num_float_features))
103
+ global_label = torch.rand(batch_size * world_size)
104
+
105
+ # Split global batch into local batches.
106
+ local_inputs = []
107
+ for r in range(world_size):
108
+ local_idlist_lengths = []
109
+ local_idlist_indices = []
110
+ local_idscore_lengths = []
111
+ local_idscore_indices = []
112
+ local_idscore_weights = []
113
+
114
+ for lengths, indices in zip(global_idlist_lengths, global_idlist_indices):
115
+ local_idlist_lengths.append(
116
+ lengths[r * batch_size : (r + 1) * batch_size]
117
+ )
118
+ lengths_cumsum = [0] + lengths.view(world_size, -1).sum(dim=1).cumsum(
119
+ dim=0
120
+ ).tolist()
121
+ local_idlist_indices.append(
122
+ indices[lengths_cumsum[r] : lengths_cumsum[r + 1]]
123
+ )
124
+
125
+ for lengths, indices, weights in zip(
126
+ global_idscore_lengths, global_idscore_indices, global_idscore_weights
127
+ ):
128
+ local_idscore_lengths.append(
129
+ lengths[r * batch_size : (r + 1) * batch_size]
130
+ )
131
+ lengths_cumsum = [0] + lengths.view(world_size, -1).sum(dim=1).cumsum(
132
+ dim=0
133
+ ).tolist()
134
+ local_idscore_indices.append(
135
+ indices[lengths_cumsum[r] : lengths_cumsum[r + 1]]
136
+ )
137
+ local_idscore_weights.append(
138
+ weights[lengths_cumsum[r] : lengths_cumsum[r + 1]]
139
+ )
140
+
141
+ local_idlist_kjt = KeyedJaggedTensor(
142
+ keys=idlist_features,
143
+ values=torch.cat(local_idlist_indices),
144
+ lengths=torch.cat(local_idlist_lengths),
145
+ )
146
+
147
+ local_idscore_kjt = (
148
+ KeyedJaggedTensor(
149
+ keys=idscore_features,
150
+ values=torch.cat(local_idscore_indices),
151
+ lengths=torch.cat(local_idscore_lengths),
152
+ weights=torch.cat(local_idscore_weights),
153
+ )
154
+ if local_idscore_indices
155
+ else None
156
+ )
157
+
158
+ local_input = ModelInput(
159
+ float_features=global_float[r * batch_size : (r + 1) * batch_size],
160
+ idlist_features=local_idlist_kjt,
161
+ # pyre-fixme[6]: For 3rd param expected `KeyedJaggedTensor` but got
162
+ # `Optional[KeyedJaggedTensor]`.
163
+ idscore_features=local_idscore_kjt,
164
+ label=global_label[r * batch_size : (r + 1) * batch_size],
165
+ )
166
+ local_inputs.append(local_input)
167
+
168
+ return (
169
+ ModelInput(
170
+ float_features=global_float,
171
+ idlist_features=global_idlist_kjt,
172
+ # pyre-fixme[6]: For 3rd param expected `KeyedJaggedTensor` but got
173
+ # `Optional[KeyedJaggedTensor]`.
174
+ idscore_features=global_idscore_kjt,
175
+ label=global_label,
176
+ ),
177
+ local_inputs,
178
+ )
179
+
180
+ def to(self, device: torch.device, non_blocking: bool = False) -> "ModelInput":
181
+ return ModelInput(
182
+ float_features=self.float_features.to(
183
+ device=device, non_blocking=non_blocking
184
+ ),
185
+ idlist_features=self.idlist_features.to(
186
+ device=device, non_blocking=non_blocking
187
+ ),
188
+ # pyre-ignore [6]
189
+ idscore_features=self.idscore_features.to(
190
+ device=device, non_blocking=non_blocking
191
+ )
192
+ if self.idscore_features is not None
193
+ else None,
194
+ label=self.label.to(device=device, non_blocking=non_blocking),
195
+ )
196
+
197
+ def record_stream(self, stream: torch.cuda.streams.Stream) -> None:
198
+ # pyre-fixme[6]: For 1st param expected `Stream` but got `Stream`.
199
+ self.float_features.record_stream(stream)
200
+ self.idlist_features.record_stream(stream)
201
+ if self.idscore_features is not None:
202
+ self.idscore_features.record_stream(stream)
203
+ # pyre-fixme[6]: For 1st param expected `Stream` but got `Stream`.
204
+ self.label.record_stream(stream)
205
+
206
+
207
+ class TestDenseArch(nn.Module):
208
+ """
209
+ Basic nn.Module for testing
210
+
211
+ Args:
212
+ device
213
+
214
+ Call Args:
215
+ dense_input: torch.Tensor
216
+
217
+ Returns:
218
+ KeyedTensor
219
+
220
+ Example::
221
+
222
+ TestDenseArch()
223
+ """
224
+
225
+ def __init__(
226
+ self,
227
+ num_float_features: int = 10,
228
+ device: Optional[torch.device] = None,
229
+ ) -> None:
230
+ super().__init__()
231
+ if device is None:
232
+ device = torch.device("cpu")
233
+ self.linear: nn.modules.Linear = nn.Linear(
234
+ in_features=num_float_features, out_features=8, device=device
235
+ )
236
+
237
+ def forward(self, dense_input: torch.Tensor) -> torch.Tensor:
238
+ return self.linear(dense_input)
239
+
240
+
241
+ class TestOverArch(nn.Module):
242
+ """
243
+ Basic nn.Module for testing
244
+
245
+ Args:
246
+ device
247
+
248
+ Call Args:
249
+ dense: torch.Tensor,
250
+ sparse: KeyedTensor,
251
+
252
+ Returns:
253
+ torch.Tensor
254
+
255
+ Example::
256
+
257
+ TestOverArch()
258
+ """
259
+
260
+ def __init__(
261
+ self,
262
+ tables: List[EmbeddingBagConfig],
263
+ weighted_tables: List[EmbeddingBagConfig],
264
+ device: Optional[torch.device] = None,
265
+ ) -> None:
266
+ super().__init__()
267
+ if device is None:
268
+ device = torch.device("cpu")
269
+ self._features: List[str] = [
270
+ feature for table in tables for feature in table.feature_names
271
+ ]
272
+ self._weighted_features: List[str] = [
273
+ feature for table in weighted_tables for feature in table.feature_names
274
+ ]
275
+ in_features = (
276
+ 8
277
+ + sum([table.embedding_dim * len(table.feature_names) for table in tables])
278
+ + sum(
279
+ [
280
+ table.embedding_dim * len(table.feature_names)
281
+ for table in weighted_tables
282
+ ]
283
+ )
284
+ )
285
+ self.linear: nn.modules.Linear = nn.Linear(
286
+ in_features=in_features, out_features=16, device=device
287
+ )
288
+
289
+ def forward(
290
+ self,
291
+ dense: torch.Tensor,
292
+ sparse: KeyedTensor,
293
+ ) -> torch.Tensor:
294
+ ret_list = []
295
+ ret_list.append(dense)
296
+ for feature_name in self._features:
297
+ ret_list.append(sparse[feature_name])
298
+ for feature_name in self._weighted_features:
299
+ ret_list.append(sparse[feature_name])
300
+ return self.linear(torch.cat(ret_list, dim=1))
301
+
302
+
303
+ class TestSparseArch(nn.Module):
304
+ """
305
+ Basic nn.Module for testing
306
+
307
+ Args:
308
+ tables
309
+ device
310
+
311
+ Call Args:
312
+ features
313
+
314
+ Returns:
315
+ KeyedTensor
316
+ """
317
+
318
+ def __init__(
319
+ self,
320
+ tables: List[EmbeddingBagConfig],
321
+ weighted_tables: List[EmbeddingBagConfig],
322
+ device: Optional[torch.device] = None,
323
+ ) -> None:
324
+ super().__init__()
325
+ if device is None:
326
+ device = torch.device("cpu")
327
+ self.ebc: EmbeddingBagCollection = EmbeddingBagCollection(
328
+ tables=tables,
329
+ device=device,
330
+ )
331
+ self.weighted_ebc: EmbeddingBagCollection = EmbeddingBagCollection(
332
+ tables=weighted_tables,
333
+ is_weighted=True,
334
+ device=device,
335
+ )
336
+
337
+ def forward(
338
+ self, features: KeyedJaggedTensor, weighted_features: KeyedJaggedTensor
339
+ ) -> KeyedTensor:
340
+ ebc = self.ebc(features)
341
+ w_ebc = self.weighted_ebc(weighted_features)
342
+ return KeyedTensor(
343
+ keys=ebc.keys() + w_ebc.keys(),
344
+ length_per_key=ebc.length_per_key() + w_ebc.length_per_key(),
345
+ values=torch.cat([ebc.values(), w_ebc.values()], dim=1),
346
+ )
347
+
348
+
349
+ class TestSparseNNBase(nn.Module):
350
+ """
351
+ Base class for a SparseNN model.
352
+
353
+ Args:
354
+ tables: List[BaseEmbeddingConfig],
355
+ weighted_tables: Optional[List[BaseEmbeddingConfig]],
356
+ embedding_groups: Optional[Dict[str, List[str]]],
357
+ dense_device: Optional[torch.device],
358
+ sparse_device: Optional[torch.device],
359
+ """
360
+
361
+ def __init__(
362
+ self,
363
+ tables: List[BaseEmbeddingConfig],
364
+ weighted_tables: Optional[List[BaseEmbeddingConfig]] = None,
365
+ embedding_groups: Optional[Dict[str, List[str]]] = None,
366
+ dense_device: Optional[torch.device] = None,
367
+ sparse_device: Optional[torch.device] = None,
368
+ ) -> None:
369
+ super().__init__()
370
+ if dense_device is None:
371
+ dense_device = torch.device("cpu")
372
+ if sparse_device is None:
373
+ sparse_device = torch.device("cpu")
374
+
375
+
376
+ class TestSparseNN(TestSparseNNBase):
377
+ """
378
+ Simple version of a SparseNN model.
379
+
380
+ Args:
381
+ tables: List[EmbeddingBagConfig],
382
+ weighted_tables: Optional[List[EmbeddingBagConfig]],
383
+ embedding_groups: Optional[Dict[str, List[str]]],
384
+ dense_device: Optional[torch.device],
385
+ sparse_device: Optional[torch.device],
386
+
387
+ Call Args:
388
+ input: ModelInput,
389
+
390
+ Returns:
391
+ torch.Tensor
392
+
393
+ Example::
394
+
395
+ TestSparseNN()
396
+ """
397
+
398
+ def __init__(
399
+ self,
400
+ tables: List[EmbeddingBagConfig],
401
+ num_float_features: int = 10,
402
+ weighted_tables: Optional[List[EmbeddingBagConfig]] = None,
403
+ embedding_groups: Optional[Dict[str, List[str]]] = None,
404
+ dense_device: Optional[torch.device] = None,
405
+ sparse_device: Optional[torch.device] = None,
406
+ ) -> None:
407
+ super().__init__(
408
+ tables=cast(List[BaseEmbeddingConfig], tables),
409
+ weighted_tables=cast(Optional[List[BaseEmbeddingConfig]], weighted_tables),
410
+ embedding_groups=embedding_groups,
411
+ dense_device=dense_device,
412
+ sparse_device=sparse_device,
413
+ )
414
+ if weighted_tables is None:
415
+ weighted_tables = []
416
+
417
+ self.dense = TestDenseArch(num_float_features, dense_device)
418
+ self.sparse = TestSparseArch(tables, weighted_tables, sparse_device)
419
+ self.over = TestOverArch(tables, weighted_tables, dense_device)
420
+
421
+ def forward(
422
+ self,
423
+ input: ModelInput,
424
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
425
+ dense_r = self.dense(input.float_features)
426
+ sparse_r = self.sparse(input.idlist_features, input.idscore_features)
427
+ over_r = self.over(dense_r, sparse_r)
428
+ pred = torch.sigmoid(torch.mean(over_r, dim=1))
429
+ if self.training:
430
+ return (
431
+ torch.nn.functional.binary_cross_entropy_with_logits(pred, input.label),
432
+ pred,
433
+ )
434
+ else:
435
+ return pred
436
+
437
+
438
+ class TestTowerInteraction(nn.Module):
439
+ """
440
+ Basic nn.Module for testing
441
+
442
+ Args:
443
+ tables: List[EmbeddingBagConfig],
444
+ device: Optional[torch.device],
445
+
446
+ Call Args:
447
+ sparse: KeyedTensor,
448
+
449
+ Returns:
450
+ torch.Tensor
451
+
452
+ Example:
453
+ >>> TestOverArch()
454
+ """
455
+
456
+ def __init__(
457
+ self,
458
+ tables: List[EmbeddingBagConfig],
459
+ device: Optional[torch.device] = None,
460
+ ) -> None:
461
+ super().__init__()
462
+ if device is None:
463
+ device = torch.device("cpu")
464
+ self._features: List[str] = [
465
+ feature for table in tables for feature in table.feature_names
466
+ ]
467
+ in_features = sum(
468
+ [table.embedding_dim * len(table.feature_names) for table in tables]
469
+ )
470
+ self.linear: nn.modules.Linear = nn.Linear(
471
+ in_features=in_features,
472
+ out_features=in_features,
473
+ device=device,
474
+ )
475
+
476
+ def forward(
477
+ self,
478
+ sparse: KeyedTensor,
479
+ ) -> torch.Tensor:
480
+ ret_list = []
481
+ for feature_name in self._features:
482
+ ret_list.append(sparse[feature_name])
483
+ return self.linear(torch.cat(ret_list, dim=1))
484
+
485
+
486
+ class TestTowerSparseNN(TestSparseNNBase):
487
+ """
488
+ Simple version of a SparseNN model.
489
+
490
+ Args:
491
+ tables: List[EmbeddingBagConfig],
492
+ embedding_groups: Optional[Dict[str, List[str]]],
493
+ dense_device: Optional[torch.device],
494
+ sparse_device: Optional[torch.device],
495
+
496
+ Call Args:
497
+ input: ModelInput,
498
+
499
+ Returns:
500
+ torch.Tensor
501
+
502
+ Example:
503
+ >>> TestSparseNN()
504
+ """
505
+
506
+ def __init__(
507
+ self,
508
+ tables: List[EmbeddingBagConfig],
509
+ num_float_features: int = 10,
510
+ weighted_tables: Optional[List[EmbeddingBagConfig]] = None,
511
+ embedding_groups: Optional[Dict[str, List[str]]] = None,
512
+ dense_device: Optional[torch.device] = None,
513
+ sparse_device: Optional[torch.device] = None,
514
+ ) -> None:
515
+ super().__init__(
516
+ tables=cast(List[BaseEmbeddingConfig], tables),
517
+ weighted_tables=cast(Optional[List[BaseEmbeddingConfig]], weighted_tables),
518
+ embedding_groups=embedding_groups,
519
+ dense_device=dense_device,
520
+ sparse_device=sparse_device,
521
+ )
522
+
523
+ self.dense = TestDenseArch(num_float_features, dense_device)
524
+
525
+ # TODO: after adding planner support for tower_module, we can random assign
526
+ # tables to towers, but for now the match planner default layout
527
+ self.tower_0 = EmbeddingTower(
528
+ embedding_module=EmbeddingBagCollection(tables=[tables[2], tables[3]]),
529
+ interaction_module=TestTowerInteraction(tables=[tables[2], tables[3]]),
530
+ )
531
+ self.tower_1 = EmbeddingTower(
532
+ embedding_module=EmbeddingBagCollection(tables=[tables[0]]),
533
+ interaction_module=TestTowerInteraction(tables=[tables[0]]),
534
+ )
535
+ self.sparse_arch = TestSparseArch(
536
+ [tables[1]],
537
+ # pyre-ignore [16]
538
+ [weighted_tables[0]],
539
+ sparse_device,
540
+ )
541
+ self.sparse_arch_feature_names: List[str] = (
542
+ tables[1].feature_names + weighted_tables[0].feature_names
543
+ )
544
+
545
+ self.over = nn.Linear(
546
+ in_features=8
547
+ # pyre-ignore [16]
548
+ + self.tower_0.interaction.linear.out_features
549
+ # pyre-ignore [16]
550
+ + self.tower_1.interaction.linear.out_features
551
+ + tables[1].embedding_dim * len(tables[1].feature_names)
552
+ + weighted_tables[0].embedding_dim * len(weighted_tables[0].feature_names),
553
+ out_features=16,
554
+ device=dense_device,
555
+ )
556
+
557
+ def forward(
558
+ self,
559
+ input: ModelInput,
560
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
561
+ dense_r = self.dense(input.float_features)
562
+ tower_0_r = self.tower_0(input.idlist_features)
563
+ tower_1_r = self.tower_1(input.idlist_features)
564
+ sparse_arch_r = self.sparse_arch(input.idlist_features, input.idscore_features)
565
+ sparse_arch_r = torch.cat(
566
+ [sparse_arch_r[f] for f in self.sparse_arch_feature_names], dim=1
567
+ )
568
+
569
+ sparse_r = torch.cat([tower_0_r, tower_1_r, sparse_arch_r], dim=1)
570
+ over_r = self.over(torch.cat([dense_r, sparse_r], dim=1))
571
+ pred = torch.sigmoid(torch.mean(over_r, dim=1))
572
+ if self.training:
573
+ return (
574
+ torch.nn.functional.binary_cross_entropy_with_logits(pred, input.label),
575
+ pred,
576
+ )
577
+ else:
578
+ return pred
579
+
580
+
581
+ class TestTowerCollectionSparseNN(TestSparseNNBase):
582
+ """
583
+ Simple version of a SparseNN model.
584
+
585
+ Constructor Args:
586
+ tables: List[EmbeddingBagConfig],
587
+ embedding_groups: Optional[Dict[str, List[str]]],
588
+ dense_device: Optional[torch.device],
589
+ sparse_device: Optional[torch.device],
590
+
591
+ Call Args:
592
+ input: ModelInput,
593
+
594
+ Returns:
595
+ torch.Tensor
596
+
597
+ Example:
598
+ >>> TestSparseNN()
599
+ """
600
+
601
+ def __init__(
602
+ self,
603
+ tables: List[EmbeddingBagConfig],
604
+ num_float_features: int = 10,
605
+ weighted_tables: Optional[List[EmbeddingBagConfig]] = None,
606
+ embedding_groups: Optional[Dict[str, List[str]]] = None,
607
+ dense_device: Optional[torch.device] = None,
608
+ sparse_device: Optional[torch.device] = None,
609
+ ) -> None:
610
+ super().__init__(
611
+ tables=cast(List[BaseEmbeddingConfig], tables),
612
+ weighted_tables=cast(Optional[List[BaseEmbeddingConfig]], weighted_tables),
613
+ embedding_groups=embedding_groups,
614
+ dense_device=dense_device,
615
+ sparse_device=sparse_device,
616
+ )
617
+
618
+ self.dense = TestDenseArch(num_float_features, dense_device)
619
+ # TODO: after adding planner support for tower_module, we can random assign
620
+ # tables to towers, but for now the match planner default layout
621
+ tower_0 = EmbeddingTower(
622
+ embedding_module=EmbeddingBagCollection(tables=[tables[0], tables[2]]),
623
+ interaction_module=TestTowerInteraction(tables=[tables[0], tables[2]]),
624
+ )
625
+ tower_1 = EmbeddingTower(
626
+ embedding_module=EmbeddingBagCollection(tables=[tables[1]]),
627
+ interaction_module=TestTowerInteraction(tables=[tables[1]]),
628
+ )
629
+ tower_2 = EmbeddingTower(
630
+ embedding_module=EmbeddingBagCollection(
631
+ # pyre-ignore [16]
632
+ tables=[weighted_tables[0]],
633
+ is_weighted=True,
634
+ ),
635
+ interaction_module=TestTowerInteraction(tables=[weighted_tables[0]]),
636
+ )
637
+ self.tower_arch = EmbeddingTowerCollection(towers=[tower_0, tower_1, tower_2])
638
+ self.over = nn.Linear(
639
+ in_features=8
640
+ # pyre-ignore [16]
641
+ + tower_0.interaction.linear.out_features
642
+ # pyre-ignore [16]
643
+ + tower_1.interaction.linear.out_features
644
+ # pyre-ignore [16]
645
+ + tower_2.interaction.linear.out_features,
646
+ out_features=16,
647
+ device=dense_device,
648
+ )
649
+
650
+ def forward(
651
+ self,
652
+ input: ModelInput,
653
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
654
+ dense_r = self.dense(input.float_features)
655
+ sparse_r = self.tower_arch(input.idlist_features, input.idscore_features)
656
+ over_r = self.over(torch.cat([dense_r, sparse_r], dim=1))
657
+ pred = torch.sigmoid(torch.mean(over_r, dim=1))
658
+ if self.training:
659
+ return (
660
+ torch.nn.functional.binary_cross_entropy_with_logits(pred, input.label),
661
+ pred,
662
+ )
663
+ else:
664
+ return pred
665
+
666
+
667
+ class TestEBCSharder(EmbeddingBagCollectionSharder):
668
+ def __init__(
669
+ self,
670
+ sharding_type: str,
671
+ kernel_type: str,
672
+ fused_params: Optional[Dict[str, Any]] = None,
673
+ ) -> None:
674
+ if fused_params is None:
675
+ fused_params = {}
676
+ super().__init__(fused_params)
677
+ self._sharding_type = sharding_type
678
+ self._kernel_type = kernel_type
679
+
680
+ """
681
+ Restricts sharding to single type only.
682
+ """
683
+
684
+ def sharding_types(self, compute_device_type: str) -> List[str]:
685
+ return [self._sharding_type]
686
+
687
+ """
688
+ Restricts to single impl.
689
+ """
690
+
691
+ def compute_kernels(
692
+ self, sharding_type: str, compute_device_type: str
693
+ ) -> List[str]:
694
+ return [self._kernel_type]
695
+
696
+ @property
697
+ def fused_params(self) -> Optional[Dict[str, Any]]:
698
+ return self._fused_params
699
+
700
+
701
+ class TestFusedEBCSharder(FusedEmbeddingBagCollectionSharder):
702
+ def __init__(
703
+ self,
704
+ sharding_type: str,
705
+ ) -> None:
706
+ super().__init__()
707
+ self._sharding_type = sharding_type
708
+
709
+ """
710
+ Restricts sharding to single type only.
711
+ """
712
+
713
+ def sharding_types(self, compute_device_type: str) -> List[str]:
714
+ return [self._sharding_type]
715
+
716
+
717
+ class TestEBSharder(EmbeddingBagSharder):
718
+ def __init__(
719
+ self, sharding_type: str, kernel_type: str, fused_params: Dict[str, Any]
720
+ ) -> None:
721
+ super().__init__(fused_params)
722
+ self._sharding_type = sharding_type
723
+ self._kernel_type = kernel_type
724
+
725
+ """
726
+ Restricts sharding to single type only.
727
+ """
728
+
729
+ def sharding_types(self, compute_device_type: str) -> List[str]:
730
+ return [self._sharding_type]
731
+
732
+ """
733
+ Restricts to single impl.
734
+ """
735
+
736
+ def compute_kernels(
737
+ self, sharding_type: str, compute_device_type: str
738
+ ) -> List[str]:
739
+ return [self._kernel_type]
740
+
741
+ @property
742
+ def fused_params(self) -> Optional[Dict[str, Any]]:
743
+ return self._fused_params
744
+
745
+
746
+ class TestETSharder(EmbeddingTowerSharder):
747
+ def __init__(
748
+ self, sharding_type: str, kernel_type: str, fused_params: Dict[str, Any]
749
+ ) -> None:
750
+ super().__init__(fused_params)
751
+ self._sharding_type = sharding_type
752
+ self._kernel_type = kernel_type
753
+
754
+ """
755
+ Restricts sharding to single type only.
756
+ """
757
+
758
+ def sharding_types(self, compute_device_type: str) -> List[str]:
759
+ return [self._sharding_type]
760
+
761
+ """
762
+ Restricts to single impl.
763
+ """
764
+
765
+ def compute_kernels(
766
+ self, sharding_type: str, compute_device_type: str
767
+ ) -> List[str]:
768
+ return [self._kernel_type]
769
+
770
+ @property
771
+ def fused_params(self) -> Optional[Dict[str, Any]]:
772
+ return self._fused_params
773
+
774
+
775
+ class TestETCSharder(EmbeddingTowerCollectionSharder):
776
+ def __init__(
777
+ self, sharding_type: str, kernel_type: str, fused_params: Dict[str, Any]
778
+ ) -> None:
779
+ super().__init__(fused_params)
780
+ self._sharding_type = sharding_type
781
+ self._kernel_type = kernel_type
782
+
783
+ """
784
+ Restricts sharding to single type only.
785
+ """
786
+
787
+ def sharding_types(self, compute_device_type: str) -> List[str]:
788
+ return [self._sharding_type]
789
+
790
+ """
791
+ Restricts to single impl.
792
+ """
793
+
794
+ def compute_kernels(
795
+ self, sharding_type: str, compute_device_type: str
796
+ ) -> List[str]:
797
+ return [self._kernel_type]
798
+
799
+ @property
800
+ def fused_params(self) -> Optional[Dict[str, Any]]:
801
+ return self._fused_params
802
+
803
+
804
+ def _get_default_rtol_and_atol(
805
+ actual: torch.Tensor, expected: torch.Tensor
806
+ ) -> Tuple[float, float]:
807
+ """
808
+ default tolerance values for torch.testing.assert_close,
809
+ consistent with the values of torch.testing.assert_allclose
810
+ """
811
+ _DTYPE_PRECISIONS = {
812
+ torch.float16: (1e-3, 1e-3),
813
+ torch.float32: (1e-4, 1e-5),
814
+ torch.float64: (1e-5, 1e-8),
815
+ }
816
+ actual_rtol, actual_atol = _DTYPE_PRECISIONS.get(actual.dtype, (0.0, 0.0))
817
+ expected_rtol, expected_atol = _DTYPE_PRECISIONS.get(expected.dtype, (0.0, 0.0))
818
+ return max(actual_rtol, expected_rtol), max(actual_atol, expected_atol)