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.
- examples/__init__.py +0 -0
- examples/datasets/__init__.py +8 -0
- examples/datasets/criteo_dataframes.py +101 -0
- examples/ray/__init__.py +0 -0
- examples/ray/compute_world_size.py +51 -0
- examples/ray/train_torchrec.py +133 -0
- examples/retrieval/__init__.py +6 -0
- examples/retrieval/data/__init__.py +6 -0
- examples/retrieval/data/dataloader.py +44 -0
- examples/retrieval/knn_index.py +67 -0
- examples/retrieval/modules/__init__.py +6 -0
- examples/retrieval/modules/two_tower.py +229 -0
- examples/retrieval/two_tower_retrieval.py +192 -0
- examples/retrieval/two_tower_train.py +253 -0
- examples/torcharrow/__init__.py +8 -0
- examples/torcharrow/dataloader.py +116 -0
- examples/torcharrow/run.py +126 -0
- fbgemm_gpu/__init__.py +16 -0
- fbgemm_gpu/batched_unary_embeddings_ops.py +82 -0
- fbgemm_gpu/enums.py +21 -0
- fbgemm_gpu/fbgemm_gpu_py.so +0 -0
- fbgemm_gpu/permute_pooled_embedding_modules.py +73 -0
- fbgemm_gpu/permute_pooled_embedding_modules_split.py +76 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/__init__.py +19 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_adagrad.py +120 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_adam.py +149 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad.py +128 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad_with_counter.py +134 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad_with_weight_decay.py +128 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_sgd.py +105 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_args.py +54 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_lamb.py +149 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_lars_sgd.py +128 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_partial_rowwise_adam.py +149 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_partial_rowwise_lamb.py +149 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad.py +128 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad_with_counter.py +134 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad_with_weight_decay.py +128 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_weighted_adagrad.py +130 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_sgd.py +105 -0
- fbgemm_gpu/split_embedding_configs.py +182 -0
- fbgemm_gpu/split_embedding_inference_converter.py +208 -0
- fbgemm_gpu/split_table_batched_embeddings_ops.py +2503 -0
- fbgemm_gpu/uvm.py +35 -0
- torchrec/__init__.py +27 -0
- torchrec/datasets/__init__.py +31 -0
- torchrec/datasets/criteo.py +831 -0
- torchrec/datasets/movielens.py +140 -0
- torchrec/datasets/random.py +188 -0
- torchrec/datasets/scripts/__init__.py +0 -0
- torchrec/datasets/scripts/contiguous_preproc_criteo.py +75 -0
- torchrec/datasets/scripts/npy_preproc_criteo.py +73 -0
- torchrec/datasets/test_utils/__init__.py +0 -0
- torchrec/datasets/test_utils/criteo_test_utils.py +139 -0
- torchrec/datasets/utils.py +341 -0
- torchrec/distributed/__init__.py +55 -0
- torchrec/distributed/batched_embedding_kernel.py +697 -0
- torchrec/distributed/collective_utils.py +71 -0
- torchrec/distributed/comm.py +149 -0
- torchrec/distributed/comm_ops.py +930 -0
- torchrec/distributed/dist_data.py +949 -0
- torchrec/distributed/embedding.py +638 -0
- torchrec/distributed/embedding_kernel.py +326 -0
- torchrec/distributed/embedding_lookup.py +760 -0
- torchrec/distributed/embedding_sharding.py +660 -0
- torchrec/distributed/embedding_tower_sharding.py +992 -0
- torchrec/distributed/embedding_types.py +369 -0
- torchrec/distributed/embeddingbag.py +731 -0
- torchrec/distributed/fused_embeddingbag.py +148 -0
- torchrec/distributed/grouped_position_weighted.py +103 -0
- torchrec/distributed/model_parallel.py +555 -0
- torchrec/distributed/planner/__init__.py +24 -0
- torchrec/distributed/planner/constants.py +77 -0
- torchrec/distributed/planner/enumerators.py +353 -0
- torchrec/distributed/planner/parallelized_planners.py +307 -0
- torchrec/distributed/planner/partitioners.py +280 -0
- torchrec/distributed/planner/perf_models.py +24 -0
- torchrec/distributed/planner/planners.py +290 -0
- torchrec/distributed/planner/proposers.py +270 -0
- torchrec/distributed/planner/shard_estimators.py +971 -0
- torchrec/distributed/planner/stats.py +477 -0
- torchrec/distributed/planner/storage_reservations.py +168 -0
- torchrec/distributed/planner/types.py +423 -0
- torchrec/distributed/planner/utils.py +30 -0
- torchrec/distributed/quant_embedding.py +307 -0
- torchrec/distributed/quant_embedding_kernel.py +295 -0
- torchrec/distributed/quant_embeddingbag.py +288 -0
- torchrec/distributed/sharding/__init__.py +0 -0
- torchrec/distributed/sharding/cw_sequence_sharding.py +71 -0
- torchrec/distributed/sharding/cw_sharding.py +242 -0
- torchrec/distributed/sharding/dp_sequence_sharding.py +87 -0
- torchrec/distributed/sharding/dp_sharding.py +217 -0
- torchrec/distributed/sharding/rw_sequence_sharding.py +130 -0
- torchrec/distributed/sharding/rw_sharding.py +393 -0
- torchrec/distributed/sharding/sequence_sharding.py +69 -0
- torchrec/distributed/sharding/tw_sequence_sharding.py +211 -0
- torchrec/distributed/sharding/tw_sharding.py +469 -0
- torchrec/distributed/sharding/twcw_sharding.py +32 -0
- torchrec/distributed/sharding/twrw_sharding.py +543 -0
- torchrec/distributed/sharding/vb_cw_sharding.py +91 -0
- torchrec/distributed/sharding/vb_rw_sharding.py +250 -0
- torchrec/distributed/sharding/vb_sharding.py +54 -0
- torchrec/distributed/sharding/vb_tw_sharding.py +148 -0
- torchrec/distributed/sharding/vb_twrw_sharding.py +388 -0
- torchrec/distributed/test_utils/__init__.py +0 -0
- torchrec/distributed/test_utils/multi_process.py +132 -0
- torchrec/distributed/test_utils/test_model.py +818 -0
- torchrec/distributed/test_utils/test_model_parallel.py +74 -0
- torchrec/distributed/test_utils/test_model_parallel_base.py +117 -0
- torchrec/distributed/test_utils/test_sharding.py +280 -0
- torchrec/distributed/train_pipeline.py +531 -0
- torchrec/distributed/types.py +594 -0
- torchrec/distributed/utils.py +186 -0
- torchrec/fused_planner.py +57 -0
- torchrec/fx/__init__.py +15 -0
- torchrec/fx/tracer.py +78 -0
- torchrec/inference/__init__.py +25 -0
- torchrec/inference/client.py +127 -0
- torchrec/inference/model_packager.py +102 -0
- torchrec/inference/modules.py +155 -0
- torchrec/inference/state_dict_transform.py +103 -0
- torchrec/metrics/__init__.py +0 -0
- torchrec/metrics/auc.py +159 -0
- torchrec/metrics/calibration.py +108 -0
- torchrec/metrics/ctr.py +104 -0
- torchrec/metrics/metric_module.py +358 -0
- torchrec/metrics/metrics_config.py +152 -0
- torchrec/metrics/metrics_namespace.py +114 -0
- torchrec/metrics/model_utils.py +85 -0
- torchrec/metrics/mse.py +134 -0
- torchrec/metrics/ne.py +164 -0
- torchrec/metrics/rec_metric.py +686 -0
- torchrec/metrics/throughput.py +174 -0
- torchrec/models/__init__.py +27 -0
- torchrec/models/deepfm.py +346 -0
- torchrec/models/dlrm.py +708 -0
- torchrec/modules/__init__.py +34 -0
- torchrec/modules/activation.py +55 -0
- torchrec/modules/crossnet.py +446 -0
- torchrec/modules/deepfm.py +213 -0
- torchrec/modules/embedding_configs.py +148 -0
- torchrec/modules/embedding_modules.py +381 -0
- torchrec/modules/embedding_tower.py +150 -0
- torchrec/modules/feature_processor.py +74 -0
- torchrec/modules/fused_embedding_modules.py +625 -0
- torchrec/modules/lazy_extension.py +258 -0
- torchrec/modules/mlp.py +172 -0
- torchrec/modules/utils.py +117 -0
- torchrec/optim/__init__.py +35 -0
- torchrec/optim/clipping.py +53 -0
- torchrec/optim/fused.py +42 -0
- torchrec/optim/keyed.py +399 -0
- torchrec/optim/rowwise_adagrad.py +222 -0
- torchrec/optim/test_utils/__init__.py +19 -0
- torchrec/optim/warmup.py +147 -0
- torchrec/quant/__init__.py +34 -0
- torchrec/quant/embedding_modules.py +545 -0
- torchrec/sparse/__init__.py +33 -0
- torchrec/sparse/jagged_tensor.py +1281 -0
- torchrec/sparse/test_utils/__init__.py +45 -0
- torchrec/streamable.py +46 -0
- torchrec/test_utils/__init__.py +111 -0
- torchrec-0.2.dev0.dist-info/LICENSE +29 -0
- torchrec-0.2.dev0.dist-info/METADATA +175 -0
- torchrec-0.2.dev0.dist-info/RECORD +167 -0
- torchrec-0.2.dev0.dist-info/WHEEL +5 -0
- torchrec-0.2.dev0.dist-info/top_level.txt +2 -0
torchrec/models/dlrm.py
ADDED
|
@@ -0,0 +1,708 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
3
|
+
# All rights reserved.
|
|
4
|
+
#
|
|
5
|
+
# This source code is licensed under the BSD-style license found in the
|
|
6
|
+
# LICENSE file in the root directory of this source tree.
|
|
7
|
+
|
|
8
|
+
from typing import Dict, List, Optional, Tuple
|
|
9
|
+
|
|
10
|
+
import torch
|
|
11
|
+
from torch import nn
|
|
12
|
+
from torchrec.datasets.utils import Batch
|
|
13
|
+
from torchrec.modules.embedding_modules import EmbeddingBagCollection
|
|
14
|
+
from torchrec.modules.mlp import MLP
|
|
15
|
+
from torchrec.sparse.jagged_tensor import KeyedJaggedTensor, KeyedTensor
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def choose(n: int, k: int) -> int:
|
|
19
|
+
"""
|
|
20
|
+
Simple implementation of math.comb for Python 3.7 compatibility.
|
|
21
|
+
"""
|
|
22
|
+
if 0 <= k <= n:
|
|
23
|
+
ntok = 1
|
|
24
|
+
ktok = 1
|
|
25
|
+
for t in range(1, min(k, n - k) + 1):
|
|
26
|
+
ntok *= n
|
|
27
|
+
ktok *= t
|
|
28
|
+
n -= 1
|
|
29
|
+
return ntok // ktok
|
|
30
|
+
else:
|
|
31
|
+
return 0
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SparseArch(nn.Module):
|
|
35
|
+
"""
|
|
36
|
+
Processes the sparse features of DLRM. Does embedding lookups for all EmbeddingBag
|
|
37
|
+
and embedding features of each collection.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
embedding_bag_collection (EmbeddingBagCollection): represents a collection of
|
|
41
|
+
pooled embeddings.
|
|
42
|
+
|
|
43
|
+
Example::
|
|
44
|
+
|
|
45
|
+
eb1_config = EmbeddingBagConfig(
|
|
46
|
+
name="t1", embedding_dim=3, num_embeddings=10, feature_names=["f1"]
|
|
47
|
+
)
|
|
48
|
+
eb2_config = EmbeddingBagConfig(
|
|
49
|
+
name="t2", embedding_dim=4, num_embeddings=10, feature_names=["f2"]
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
ebc = EmbeddingBagCollection(tables=[eb1_config, eb2_config])
|
|
53
|
+
sparse_arch = SparseArch(embedding_bag_collection)
|
|
54
|
+
|
|
55
|
+
# 0 1 2 <-- batch
|
|
56
|
+
# 0 [0,1] None [2]
|
|
57
|
+
# 1 [3] [4] [5,6,7]
|
|
58
|
+
# ^
|
|
59
|
+
# feature
|
|
60
|
+
features = KeyedJaggedTensor.from_offsets_sync(
|
|
61
|
+
keys=["f1", "f2"],
|
|
62
|
+
values=torch.tensor([0, 1, 2, 3, 4, 5, 6, 7]),
|
|
63
|
+
offsets=torch.tensor([0, 2, 2, 3, 4, 5, 8]),
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
sparse_embeddings = sparse_arch(features)
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def __init__(self, embedding_bag_collection: EmbeddingBagCollection) -> None:
|
|
70
|
+
super().__init__()
|
|
71
|
+
self.embedding_bag_collection: EmbeddingBagCollection = embedding_bag_collection
|
|
72
|
+
assert (
|
|
73
|
+
self.embedding_bag_collection.embedding_bag_configs
|
|
74
|
+
), "Embedding bag collection cannot be empty!"
|
|
75
|
+
self.D: int = self.embedding_bag_collection.embedding_bag_configs[
|
|
76
|
+
0
|
|
77
|
+
].embedding_dim
|
|
78
|
+
self._sparse_feature_names: List[str] = [
|
|
79
|
+
name
|
|
80
|
+
for conf in embedding_bag_collection.embedding_bag_configs
|
|
81
|
+
for name in conf.feature_names
|
|
82
|
+
]
|
|
83
|
+
|
|
84
|
+
self.F: int = len(self._sparse_feature_names)
|
|
85
|
+
|
|
86
|
+
def forward(
|
|
87
|
+
self,
|
|
88
|
+
features: KeyedJaggedTensor,
|
|
89
|
+
) -> torch.Tensor:
|
|
90
|
+
"""
|
|
91
|
+
Args:
|
|
92
|
+
features (KeyedJaggedTensor): an input tensor of sparse features.
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
torch.Tensor: tensor of shape B X F X D.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
sparse_features: KeyedTensor = self.embedding_bag_collection(features)
|
|
99
|
+
|
|
100
|
+
B: int = features.stride()
|
|
101
|
+
|
|
102
|
+
sparse: Dict[str, torch.Tensor] = sparse_features.to_dict()
|
|
103
|
+
sparse_values: List[torch.Tensor] = []
|
|
104
|
+
for name in self.sparse_feature_names:
|
|
105
|
+
sparse_values.append(sparse[name])
|
|
106
|
+
|
|
107
|
+
return torch.cat(sparse_values, dim=1).reshape(B, self.F, self.D)
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def sparse_feature_names(self) -> List[str]:
|
|
111
|
+
return self._sparse_feature_names
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class DenseArch(nn.Module):
|
|
115
|
+
"""
|
|
116
|
+
Processes the dense features of DLRM model.
|
|
117
|
+
|
|
118
|
+
Args:
|
|
119
|
+
in_features (int): dimensionality of the dense input features.
|
|
120
|
+
layer_sizes (List[int]): list of layer sizes.
|
|
121
|
+
device (Optional[torch.device]): default compute device.
|
|
122
|
+
|
|
123
|
+
Example::
|
|
124
|
+
|
|
125
|
+
B = 20
|
|
126
|
+
D = 3
|
|
127
|
+
dense_arch = DenseArch(10, layer_sizes=[15, D])
|
|
128
|
+
dense_embedded = dense_arch(torch.rand((B, 10)))
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
def __init__(
|
|
132
|
+
self,
|
|
133
|
+
in_features: int,
|
|
134
|
+
layer_sizes: List[int],
|
|
135
|
+
device: Optional[torch.device] = None,
|
|
136
|
+
) -> None:
|
|
137
|
+
super().__init__()
|
|
138
|
+
self.model: nn.Module = MLP(
|
|
139
|
+
in_features, layer_sizes, bias=True, activation="relu", device=device
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
|
143
|
+
"""
|
|
144
|
+
Args:
|
|
145
|
+
features (torch.Tensor): an input tensor of dense features.
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
torch.Tensor: an output tensor of size B X D.
|
|
149
|
+
"""
|
|
150
|
+
return self.model(features)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class InteractionArch(nn.Module):
|
|
154
|
+
"""
|
|
155
|
+
Processes the output of both `SparseArch` (sparse_features) and `DenseArch`
|
|
156
|
+
(dense_features). Returns the pairwise dot product of each sparse feature pair,
|
|
157
|
+
the dot product of each sparse features with the output of the dense layer,
|
|
158
|
+
and the dense layer itself (all concatenated).
|
|
159
|
+
|
|
160
|
+
.. note::
|
|
161
|
+
The dimensionality of the `dense_features` (D) is expected to match the
|
|
162
|
+
dimensionality of the `sparse_features` so that the dot products between them
|
|
163
|
+
can be computed.
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
num_sparse_features (int): F.
|
|
168
|
+
|
|
169
|
+
Example::
|
|
170
|
+
|
|
171
|
+
D = 3
|
|
172
|
+
B = 10
|
|
173
|
+
keys = ["f1", "f2"]
|
|
174
|
+
F = len(keys)
|
|
175
|
+
inter_arch = InteractionArch(num_sparse_features=len(keys))
|
|
176
|
+
|
|
177
|
+
dense_features = torch.rand((B, D))
|
|
178
|
+
sparse_features = torch.rand((B, F, D))
|
|
179
|
+
|
|
180
|
+
# B X (D + F + F choose 2)
|
|
181
|
+
concat_dense = inter_arch(dense_features, sparse_features)
|
|
182
|
+
"""
|
|
183
|
+
|
|
184
|
+
def __init__(self, num_sparse_features: int) -> None:
|
|
185
|
+
super().__init__()
|
|
186
|
+
self.F: int = num_sparse_features
|
|
187
|
+
self.triu_indices: torch.Tensor = torch.triu_indices(
|
|
188
|
+
self.F + 1, self.F + 1, offset=1
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
def forward(
|
|
192
|
+
self, dense_features: torch.Tensor, sparse_features: torch.Tensor
|
|
193
|
+
) -> torch.Tensor:
|
|
194
|
+
"""
|
|
195
|
+
Args:
|
|
196
|
+
dense_features (torch.Tensor): an input tensor of size B X D.
|
|
197
|
+
sparse_features (torch.Tensor): an input tensor of size B X F X D.
|
|
198
|
+
|
|
199
|
+
Returns:
|
|
200
|
+
torch.Tensor: an output tensor of size B X (D + F + F choose 2).
|
|
201
|
+
"""
|
|
202
|
+
if self.F <= 0:
|
|
203
|
+
return dense_features
|
|
204
|
+
(B, D) = dense_features.shape
|
|
205
|
+
|
|
206
|
+
combined_values = torch.cat(
|
|
207
|
+
(dense_features.unsqueeze(1), sparse_features), dim=1
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
# dense/sparse + sparse/sparse interaction
|
|
211
|
+
# size B X (F + F choose 2)
|
|
212
|
+
interactions = torch.bmm(
|
|
213
|
+
combined_values, torch.transpose(combined_values, 1, 2)
|
|
214
|
+
)
|
|
215
|
+
interactions_flat = interactions[:, self.triu_indices[0], self.triu_indices[1]]
|
|
216
|
+
|
|
217
|
+
return torch.cat((dense_features, interactions_flat), dim=1)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class InteractionV2Arch(nn.Module):
|
|
221
|
+
"""
|
|
222
|
+
Processes the output of both `SparseArch` (sparse_features) and `DenseArch`
|
|
223
|
+
(dense_features). Return Y*Z and the dense layer itself (all concatenated)
|
|
224
|
+
where Y is the output of interaction branch 1 and Z is the output of interaction
|
|
225
|
+
branch 2. Y and Z are of size Bx(F1xD) and Bx(DxF2) respectively for some F1 and F2.
|
|
226
|
+
|
|
227
|
+
.. note::
|
|
228
|
+
|
|
229
|
+
The dimensionality of the `dense_features` (D) is expected to match the
|
|
230
|
+
dimensionality of the `sparse_features` so that the dot products between them
|
|
231
|
+
can be computed.
|
|
232
|
+
The output dimension of the 2 interaction branches should be a multiple
|
|
233
|
+
of D.
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
Args:
|
|
237
|
+
num_sparse_features (int): F.
|
|
238
|
+
interaction_branch1 (nn.Module): MLP module for the first branch of
|
|
239
|
+
interaction layer
|
|
240
|
+
interaction_branch2 (nn.Module): MLP module for the second branch of
|
|
241
|
+
interaction layer
|
|
242
|
+
|
|
243
|
+
Example::
|
|
244
|
+
|
|
245
|
+
D = 3
|
|
246
|
+
B = 10
|
|
247
|
+
keys = ["f1", "f2"]
|
|
248
|
+
F = len(keys)
|
|
249
|
+
# Assume last layer of
|
|
250
|
+
I1 = DenseArch(
|
|
251
|
+
in_features= 3 * D + D,
|
|
252
|
+
layer_sizes=[4*D, 4*D], # F1 = 4
|
|
253
|
+
device=dense_device,
|
|
254
|
+
)
|
|
255
|
+
I2 = DenseArch(
|
|
256
|
+
in_features= 3 * D + D,
|
|
257
|
+
layer_sizes=[4*D, 4*D], # F2 = 4
|
|
258
|
+
device=dense_device,
|
|
259
|
+
)
|
|
260
|
+
inter_arch = InteractionV2Arch(
|
|
261
|
+
num_sparse_features=len(keys),
|
|
262
|
+
interaction_branch1 = I1,
|
|
263
|
+
interaction_branch2 = I2,
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
dense_features = torch.rand((B, D))
|
|
267
|
+
sparse_features = torch.rand((B, F, D))
|
|
268
|
+
|
|
269
|
+
# B X (D + F1 * F2)
|
|
270
|
+
concat_dense = inter_arch(dense_features, sparse_features)
|
|
271
|
+
"""
|
|
272
|
+
|
|
273
|
+
def __init__(
|
|
274
|
+
self,
|
|
275
|
+
num_sparse_features: int,
|
|
276
|
+
interaction_branch1: nn.Module,
|
|
277
|
+
interaction_branch2: nn.Module,
|
|
278
|
+
) -> None:
|
|
279
|
+
super().__init__()
|
|
280
|
+
self.F: int = num_sparse_features
|
|
281
|
+
self.interaction_branch1 = interaction_branch1
|
|
282
|
+
self.interaction_branch2 = interaction_branch2
|
|
283
|
+
|
|
284
|
+
def forward(
|
|
285
|
+
self, dense_features: torch.Tensor, sparse_features: torch.Tensor
|
|
286
|
+
) -> torch.Tensor:
|
|
287
|
+
"""
|
|
288
|
+
Args:
|
|
289
|
+
dense_features (torch.Tensor): an input tensor of size B X D.
|
|
290
|
+
sparse_features (torch.Tensor): an input tensor of size B X F X D.
|
|
291
|
+
|
|
292
|
+
Returns:
|
|
293
|
+
torch.Tensor: an output tensor of size B X (D + F1 * F2)) where
|
|
294
|
+
F1*D and F2*D are the output dimensions of the 2 interaction MLPs.
|
|
295
|
+
"""
|
|
296
|
+
if self.F <= 0:
|
|
297
|
+
return dense_features
|
|
298
|
+
(B, D) = dense_features.shape
|
|
299
|
+
|
|
300
|
+
combined_values = torch.cat(
|
|
301
|
+
(dense_features.unsqueeze(1), sparse_features), dim=1
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
interaction_branch1_out = self.interaction_branch1(
|
|
305
|
+
torch.reshape(combined_values, (B, -1))
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
interaction_branch2_out = self.interaction_branch2(
|
|
309
|
+
torch.reshape(combined_values, (B, -1))
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
interactions = torch.bmm(
|
|
313
|
+
interaction_branch1_out.reshape([B, -1, D]),
|
|
314
|
+
interaction_branch2_out.reshape([B, D, -1]),
|
|
315
|
+
)
|
|
316
|
+
interactions_flat = torch.reshape(interactions, (B, -1))
|
|
317
|
+
|
|
318
|
+
return torch.cat((dense_features, interactions_flat), dim=1)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
class OverArch(nn.Module):
|
|
322
|
+
"""
|
|
323
|
+
Final Arch of DLRM - simple MLP over OverArch.
|
|
324
|
+
|
|
325
|
+
Args:
|
|
326
|
+
in_features (int): size of the input.
|
|
327
|
+
layer_sizes (List[int]): sizes of the layers of the `OverArch`.
|
|
328
|
+
device (Optional[torch.device]): default compute device.
|
|
329
|
+
|
|
330
|
+
Example::
|
|
331
|
+
|
|
332
|
+
B = 20
|
|
333
|
+
D = 3
|
|
334
|
+
over_arch = OverArch(10, [5, 1])
|
|
335
|
+
logits = over_arch(torch.rand((B, 10)))
|
|
336
|
+
"""
|
|
337
|
+
|
|
338
|
+
def __init__(
|
|
339
|
+
self,
|
|
340
|
+
in_features: int,
|
|
341
|
+
layer_sizes: List[int],
|
|
342
|
+
device: Optional[torch.device] = None,
|
|
343
|
+
) -> None:
|
|
344
|
+
super().__init__()
|
|
345
|
+
if len(layer_sizes) <= 1:
|
|
346
|
+
raise ValueError("OverArch must have multiple layers.")
|
|
347
|
+
self.model: nn.Module = nn.Sequential(
|
|
348
|
+
MLP(
|
|
349
|
+
in_features,
|
|
350
|
+
layer_sizes[:-1],
|
|
351
|
+
bias=True,
|
|
352
|
+
activation="relu",
|
|
353
|
+
device=device,
|
|
354
|
+
),
|
|
355
|
+
nn.Linear(layer_sizes[-2], layer_sizes[-1], bias=True, device=device),
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
|
359
|
+
"""
|
|
360
|
+
Args:
|
|
361
|
+
features (torch.Tensor):
|
|
362
|
+
|
|
363
|
+
Returns:
|
|
364
|
+
torch.Tensor: size B X layer_sizes[-1]
|
|
365
|
+
"""
|
|
366
|
+
return self.model(features)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
class DLRM(nn.Module):
|
|
370
|
+
"""
|
|
371
|
+
Recsys model from "Deep Learning Recommendation Model for Personalization and
|
|
372
|
+
Recommendation Systems" (https://arxiv.org/abs/1906.00091). Processes sparse
|
|
373
|
+
features by learning pooled embeddings for each feature. Learns the relationship
|
|
374
|
+
between dense features and sparse features by projecting dense features into the
|
|
375
|
+
same embedding space. Also, learns the pairwise relationships between sparse
|
|
376
|
+
features.
|
|
377
|
+
|
|
378
|
+
The module assumes all sparse features have the same embedding dimension
|
|
379
|
+
(i.e. each EmbeddingBagConfig uses the same embedding_dim).
|
|
380
|
+
|
|
381
|
+
The following notation is used throughout the documentation for the models:
|
|
382
|
+
|
|
383
|
+
* F: number of sparse features
|
|
384
|
+
* D: embedding_dimension of sparse features
|
|
385
|
+
* B: batch size
|
|
386
|
+
* num_features: number of dense features
|
|
387
|
+
|
|
388
|
+
Args:
|
|
389
|
+
embedding_bag_collection (EmbeddingBagCollection): collection of embedding bags
|
|
390
|
+
used to define `SparseArch`.
|
|
391
|
+
dense_in_features (int): the dimensionality of the dense input features.
|
|
392
|
+
dense_arch_layer_sizes (List[int]): the layer sizes for the `DenseArch`.
|
|
393
|
+
over_arch_layer_sizes (List[int]): the layer sizes for the `OverArch`.
|
|
394
|
+
The output dimension of the `InteractionArch` should not be manually
|
|
395
|
+
specified here.
|
|
396
|
+
dense_device (Optional[torch.device]): default compute device.
|
|
397
|
+
|
|
398
|
+
Example::
|
|
399
|
+
|
|
400
|
+
B = 2
|
|
401
|
+
D = 8
|
|
402
|
+
|
|
403
|
+
eb1_config = EmbeddingBagConfig(
|
|
404
|
+
name="t1", embedding_dim=D, num_embeddings=100, feature_names=["f1", "f3"]
|
|
405
|
+
)
|
|
406
|
+
eb2_config = EmbeddingBagConfig(
|
|
407
|
+
name="t2",
|
|
408
|
+
embedding_dim=D,
|
|
409
|
+
num_embeddings=100,
|
|
410
|
+
feature_names=["f2"],
|
|
411
|
+
)
|
|
412
|
+
|
|
413
|
+
ebc = EmbeddingBagCollection(tables=[eb1_config, eb2_config])
|
|
414
|
+
model = DLRM(
|
|
415
|
+
embedding_bag_collection=ebc,
|
|
416
|
+
dense_in_features=100,
|
|
417
|
+
dense_arch_layer_sizes=[20],
|
|
418
|
+
over_arch_layer_sizes=[5, 1],
|
|
419
|
+
)
|
|
420
|
+
|
|
421
|
+
features = torch.rand((B, 100))
|
|
422
|
+
|
|
423
|
+
# 0 1
|
|
424
|
+
# 0 [1,2] [4,5]
|
|
425
|
+
# 1 [4,3] [2,9]
|
|
426
|
+
# ^
|
|
427
|
+
# feature
|
|
428
|
+
sparse_features = KeyedJaggedTensor.from_offsets_sync(
|
|
429
|
+
keys=["f1", "f3"],
|
|
430
|
+
values=torch.tensor([1, 2, 4, 5, 4, 3, 2, 9]),
|
|
431
|
+
offsets=torch.tensor([0, 2, 4, 6, 8]),
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
logits = model(
|
|
435
|
+
dense_features=features,
|
|
436
|
+
sparse_features=sparse_features,
|
|
437
|
+
)
|
|
438
|
+
"""
|
|
439
|
+
|
|
440
|
+
def __init__(
|
|
441
|
+
self,
|
|
442
|
+
embedding_bag_collection: EmbeddingBagCollection,
|
|
443
|
+
dense_in_features: int,
|
|
444
|
+
dense_arch_layer_sizes: List[int],
|
|
445
|
+
over_arch_layer_sizes: List[int],
|
|
446
|
+
dense_device: Optional[torch.device] = None,
|
|
447
|
+
) -> None:
|
|
448
|
+
super().__init__()
|
|
449
|
+
assert (
|
|
450
|
+
len(embedding_bag_collection.embedding_bag_configs) > 0
|
|
451
|
+
), "At least one embedding bag is required"
|
|
452
|
+
for i in range(1, len(embedding_bag_collection.embedding_bag_configs)):
|
|
453
|
+
conf_prev = embedding_bag_collection.embedding_bag_configs[i - 1]
|
|
454
|
+
conf = embedding_bag_collection.embedding_bag_configs[i]
|
|
455
|
+
assert (
|
|
456
|
+
conf_prev.embedding_dim == conf.embedding_dim
|
|
457
|
+
), "All EmbeddingBagConfigs must have the same dimension"
|
|
458
|
+
embedding_dim: int = embedding_bag_collection.embedding_bag_configs[
|
|
459
|
+
0
|
|
460
|
+
].embedding_dim
|
|
461
|
+
if dense_arch_layer_sizes[-1] != embedding_dim:
|
|
462
|
+
raise ValueError(
|
|
463
|
+
f"embedding_bag_collection dimension ({embedding_dim}) and final dense "
|
|
464
|
+
"arch layer size ({dense_arch_layer_sizes[-1]}) must match."
|
|
465
|
+
)
|
|
466
|
+
|
|
467
|
+
self.sparse_arch: SparseArch = SparseArch(embedding_bag_collection)
|
|
468
|
+
num_sparse_features: int = len(self.sparse_arch.sparse_feature_names)
|
|
469
|
+
|
|
470
|
+
self.dense_arch = DenseArch(
|
|
471
|
+
in_features=dense_in_features,
|
|
472
|
+
layer_sizes=dense_arch_layer_sizes,
|
|
473
|
+
device=dense_device,
|
|
474
|
+
)
|
|
475
|
+
|
|
476
|
+
self.inter_arch = InteractionArch(
|
|
477
|
+
num_sparse_features=num_sparse_features,
|
|
478
|
+
)
|
|
479
|
+
|
|
480
|
+
over_in_features: int = (
|
|
481
|
+
embedding_dim + choose(num_sparse_features, 2) + num_sparse_features
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
self.over_arch = OverArch(
|
|
485
|
+
in_features=over_in_features,
|
|
486
|
+
layer_sizes=over_arch_layer_sizes,
|
|
487
|
+
device=dense_device,
|
|
488
|
+
)
|
|
489
|
+
|
|
490
|
+
def forward(
|
|
491
|
+
self,
|
|
492
|
+
dense_features: torch.Tensor,
|
|
493
|
+
sparse_features: KeyedJaggedTensor,
|
|
494
|
+
) -> torch.Tensor:
|
|
495
|
+
"""
|
|
496
|
+
Args:
|
|
497
|
+
dense_features (torch.Tensor): the dense features.
|
|
498
|
+
sparse_features (KeyedJaggedTensor): the sparse features.
|
|
499
|
+
|
|
500
|
+
Returns:
|
|
501
|
+
torch.Tensor: logits.
|
|
502
|
+
"""
|
|
503
|
+
embedded_dense = self.dense_arch(dense_features)
|
|
504
|
+
embedded_sparse = self.sparse_arch(sparse_features)
|
|
505
|
+
concatenated_dense = self.inter_arch(
|
|
506
|
+
dense_features=embedded_dense, sparse_features=embedded_sparse
|
|
507
|
+
)
|
|
508
|
+
logits = self.over_arch(concatenated_dense)
|
|
509
|
+
return logits
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
class DLRMV2(DLRM):
|
|
513
|
+
"""
|
|
514
|
+
Recsys model v2 modified from the original model from "Deep Learning Recommendation
|
|
515
|
+
Model for Personalization and Recommendation Systems"
|
|
516
|
+
(https://arxiv.org/abs/1906.00091). Similar to DLRM module but has
|
|
517
|
+
additional MLPs in the interaction layer (along 2 branches).
|
|
518
|
+
|
|
519
|
+
The module assumes all sparse features have the same embedding dimension
|
|
520
|
+
(i.e. each EmbeddingBagConfig uses the same embedding_dim).
|
|
521
|
+
|
|
522
|
+
The following notation is used throughout the documentation for the models:
|
|
523
|
+
|
|
524
|
+
* F: number of sparse features
|
|
525
|
+
* D: embedding_dimension of sparse features
|
|
526
|
+
* B: batch size
|
|
527
|
+
* num_features: number of dense features
|
|
528
|
+
|
|
529
|
+
Args:
|
|
530
|
+
embedding_bag_collection (EmbeddingBagCollection): collection of embedding bags
|
|
531
|
+
used to define `SparseArch`.
|
|
532
|
+
dense_in_features (int): the dimensionality of the dense input features.
|
|
533
|
+
dense_arch_layer_sizes (List[int]): the layer sizes for the `DenseArch`.
|
|
534
|
+
over_arch_layer_sizes (List[int]): the layer sizes for the `OverArch`.
|
|
535
|
+
The output dimension of the `InteractionArch` should not be manually
|
|
536
|
+
specified here.
|
|
537
|
+
interaction_branch1_layer_sizes (List[int]): the layer sizes for first branch of
|
|
538
|
+
interaction layer. The output dimension must be a multiple of D.
|
|
539
|
+
interaction_branch2_layer_sizes (List[int]):the layer sizes for second branch of
|
|
540
|
+
interaction layer. The output dimension must be a multiple of D.
|
|
541
|
+
dense_device (Optional[torch.device]): default compute device.
|
|
542
|
+
|
|
543
|
+
Example::
|
|
544
|
+
|
|
545
|
+
B = 2
|
|
546
|
+
D = 8
|
|
547
|
+
|
|
548
|
+
eb1_config = EmbeddingBagConfig(
|
|
549
|
+
name="t1", embedding_dim=D, num_embeddings=100, feature_names=["f1", "f3"]
|
|
550
|
+
)
|
|
551
|
+
eb2_config = EmbeddingBagConfig(
|
|
552
|
+
name="t2",
|
|
553
|
+
embedding_dim=D,
|
|
554
|
+
num_embeddings=100,
|
|
555
|
+
feature_names=["f2"],
|
|
556
|
+
)
|
|
557
|
+
|
|
558
|
+
ebc = EmbeddingBagCollection(tables=[eb1_config, eb2_config])
|
|
559
|
+
model = DLRMV2(
|
|
560
|
+
embedding_bag_collection=ebc,
|
|
561
|
+
dense_in_features=100,
|
|
562
|
+
dense_arch_layer_sizes=[20, D],
|
|
563
|
+
interaction_branch1_layer_sizes=[3*D+D, 4*D],
|
|
564
|
+
interaction_branch2_layer_sizes=[3*D+D, 4*D],
|
|
565
|
+
over_arch_layer_sizes=[5, 1],
|
|
566
|
+
)
|
|
567
|
+
|
|
568
|
+
features = torch.rand((B, 100))
|
|
569
|
+
|
|
570
|
+
# 0 1
|
|
571
|
+
# 0 [1,2] [4,5]
|
|
572
|
+
# 1 [4,3] [2,9]
|
|
573
|
+
# ^
|
|
574
|
+
# feature
|
|
575
|
+
sparse_features = KeyedJaggedTensor.from_offsets_sync(
|
|
576
|
+
keys=["f1", "f3"],
|
|
577
|
+
values=torch.tensor([1, 2, 4, 5, 4, 3, 2, 9]),
|
|
578
|
+
offsets=torch.tensor([0, 2, 4, 6, 8]),
|
|
579
|
+
)
|
|
580
|
+
|
|
581
|
+
logits = model(
|
|
582
|
+
dense_features=features,
|
|
583
|
+
sparse_features=sparse_features,
|
|
584
|
+
)
|
|
585
|
+
"""
|
|
586
|
+
|
|
587
|
+
def __init__(
|
|
588
|
+
self,
|
|
589
|
+
embedding_bag_collection: EmbeddingBagCollection,
|
|
590
|
+
dense_in_features: int,
|
|
591
|
+
dense_arch_layer_sizes: List[int],
|
|
592
|
+
over_arch_layer_sizes: List[int],
|
|
593
|
+
interaction_branch1_layer_sizes: List[int],
|
|
594
|
+
interaction_branch2_layer_sizes: List[int],
|
|
595
|
+
dense_device: Optional[torch.device] = None,
|
|
596
|
+
) -> None:
|
|
597
|
+
# initialize DLRM
|
|
598
|
+
# sparse arch and dense arch are initialized via DLRM
|
|
599
|
+
super().__init__(
|
|
600
|
+
embedding_bag_collection,
|
|
601
|
+
dense_in_features,
|
|
602
|
+
dense_arch_layer_sizes,
|
|
603
|
+
over_arch_layer_sizes,
|
|
604
|
+
dense_device,
|
|
605
|
+
)
|
|
606
|
+
|
|
607
|
+
embedding_dim: int = embedding_bag_collection.embedding_bag_configs[
|
|
608
|
+
0
|
|
609
|
+
].embedding_dim
|
|
610
|
+
num_sparse_features: int = len(self.sparse_arch.sparse_feature_names)
|
|
611
|
+
|
|
612
|
+
# Fix interaction and over arch for DLRMv2
|
|
613
|
+
if interaction_branch1_layer_sizes[-1] % embedding_dim != 0:
|
|
614
|
+
raise ValueError(
|
|
615
|
+
"Final interaction branch1 layer size "
|
|
616
|
+
"({}) is not a multiple of embedding size ({})".format(
|
|
617
|
+
interaction_branch1_layer_sizes[-1], embedding_dim
|
|
618
|
+
)
|
|
619
|
+
)
|
|
620
|
+
projected_dim_1: int = interaction_branch1_layer_sizes[-1] // embedding_dim
|
|
621
|
+
interaction_branch1 = DenseArch(
|
|
622
|
+
in_features=num_sparse_features * embedding_dim
|
|
623
|
+
+ dense_arch_layer_sizes[-1],
|
|
624
|
+
layer_sizes=interaction_branch1_layer_sizes,
|
|
625
|
+
device=dense_device,
|
|
626
|
+
)
|
|
627
|
+
|
|
628
|
+
if interaction_branch2_layer_sizes[-1] % embedding_dim != 0:
|
|
629
|
+
raise ValueError(
|
|
630
|
+
"Final interaction branch2 layer size "
|
|
631
|
+
"({}) is not a multiple of embedding size ({})".format(
|
|
632
|
+
interaction_branch2_layer_sizes[-1], embedding_dim
|
|
633
|
+
)
|
|
634
|
+
)
|
|
635
|
+
projected_dim_2: int = interaction_branch2_layer_sizes[-1] // embedding_dim
|
|
636
|
+
interaction_branch2 = DenseArch(
|
|
637
|
+
in_features=num_sparse_features * embedding_dim
|
|
638
|
+
+ dense_arch_layer_sizes[-1],
|
|
639
|
+
layer_sizes=interaction_branch2_layer_sizes,
|
|
640
|
+
device=dense_device,
|
|
641
|
+
)
|
|
642
|
+
|
|
643
|
+
self.inter_arch = InteractionV2Arch(
|
|
644
|
+
num_sparse_features=num_sparse_features,
|
|
645
|
+
interaction_branch1=interaction_branch1,
|
|
646
|
+
interaction_branch2=interaction_branch2,
|
|
647
|
+
)
|
|
648
|
+
|
|
649
|
+
over_in_features: int = embedding_dim + projected_dim_1 * projected_dim_2
|
|
650
|
+
|
|
651
|
+
self.over_arch = OverArch(
|
|
652
|
+
in_features=over_in_features,
|
|
653
|
+
layer_sizes=over_arch_layer_sizes,
|
|
654
|
+
device=dense_device,
|
|
655
|
+
)
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
class DLRMTrain(nn.Module):
|
|
659
|
+
"""
|
|
660
|
+
nn.Module to wrap DLRM model to use with train_pipeline.
|
|
661
|
+
|
|
662
|
+
DLRM Recsys model from "Deep Learning Recommendation Model for Personalization and
|
|
663
|
+
Recommendation Systems" (https://arxiv.org/abs/1906.00091). Processes sparse
|
|
664
|
+
features by learning pooled embeddings for each feature. Learns the relationship
|
|
665
|
+
between dense features and sparse features by projecting dense features into the
|
|
666
|
+
same embedding space. Also, learns the pairwise relationships between sparse
|
|
667
|
+
features.
|
|
668
|
+
|
|
669
|
+
The module assumes all sparse features have the same embedding dimension
|
|
670
|
+
(i.e, each EmbeddingBagConfig uses the same embedding_dim)
|
|
671
|
+
|
|
672
|
+
Args:
|
|
673
|
+
dlrm_module: DLRM module (DLRM or DLRMV2) to be used in training
|
|
674
|
+
|
|
675
|
+
Example::
|
|
676
|
+
|
|
677
|
+
ebc = EmbeddingBagCollection(config=ebc_config)
|
|
678
|
+
dlrm_module = DLRM(
|
|
679
|
+
embedding_bag_collection=ebc,
|
|
680
|
+
dense_in_features=100,
|
|
681
|
+
dense_arch_layer_sizes=[20],
|
|
682
|
+
over_arch_layer_sizes=[5, 1],
|
|
683
|
+
)
|
|
684
|
+
dlrm_model = DLRMTrain(dlrm_module)
|
|
685
|
+
"""
|
|
686
|
+
|
|
687
|
+
def __init__(
|
|
688
|
+
self,
|
|
689
|
+
dlrm_module: DLRM,
|
|
690
|
+
) -> None:
|
|
691
|
+
super().__init__()
|
|
692
|
+
self.model = dlrm_module
|
|
693
|
+
self.loss_fn: nn.Module = nn.BCEWithLogitsLoss()
|
|
694
|
+
|
|
695
|
+
def forward(
|
|
696
|
+
self, batch: Batch
|
|
697
|
+
) -> Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:
|
|
698
|
+
"""
|
|
699
|
+
Args:
|
|
700
|
+
batch: batch used with criteo and random data from torchrec.datasets
|
|
701
|
+
Returns:
|
|
702
|
+
Tuple[loss, Tuple[loss, logits, labels]]
|
|
703
|
+
"""
|
|
704
|
+
logits = self.model(batch.dense_features, batch.sparse_features)
|
|
705
|
+
logits = logits.squeeze()
|
|
706
|
+
loss = self.loss_fn(logits, batch.labels.float())
|
|
707
|
+
|
|
708
|
+
return loss, (loss.detach(), logits.detach(), batch.labels.detach())
|