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
|
@@ -0,0 +1,381 @@
|
|
|
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
|
+
from typing import Dict, List, Optional, Union
|
|
10
|
+
|
|
11
|
+
import torch
|
|
12
|
+
import torch.nn as nn
|
|
13
|
+
from torchrec.modules.embedding_configs import (
|
|
14
|
+
DataType,
|
|
15
|
+
EmbeddingBagConfig,
|
|
16
|
+
EmbeddingConfig,
|
|
17
|
+
pooling_type_to_str,
|
|
18
|
+
)
|
|
19
|
+
from torchrec.sparse.jagged_tensor import JaggedTensor, KeyedJaggedTensor, KeyedTensor
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class EmbeddingBagCollectionInterface(abc.ABC, nn.Module):
|
|
23
|
+
"""
|
|
24
|
+
Interface for `EmbeddingBagCollection`.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
@abc.abstractmethod
|
|
28
|
+
def forward(
|
|
29
|
+
self,
|
|
30
|
+
features: KeyedJaggedTensor,
|
|
31
|
+
) -> KeyedTensor:
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
@abc.abstractproperty
|
|
35
|
+
def embedding_bag_configs(
|
|
36
|
+
self,
|
|
37
|
+
) -> List[EmbeddingBagConfig]:
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
@abc.abstractproperty
|
|
41
|
+
def is_weighted(self) -> bool:
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def get_embedding_names_by_table(
|
|
46
|
+
tables: Union[List[EmbeddingBagConfig], List[EmbeddingConfig]],
|
|
47
|
+
) -> List[List[str]]:
|
|
48
|
+
shared_feature: Dict[str, bool] = {}
|
|
49
|
+
for embedding_config in tables:
|
|
50
|
+
for feature_name in embedding_config.feature_names:
|
|
51
|
+
if feature_name not in shared_feature:
|
|
52
|
+
shared_feature[feature_name] = False
|
|
53
|
+
else:
|
|
54
|
+
shared_feature[feature_name] = True
|
|
55
|
+
embedding_names_by_table: List[List[str]] = []
|
|
56
|
+
for embedding_config in tables:
|
|
57
|
+
embedding_names: List[str] = []
|
|
58
|
+
for feature_name in embedding_config.feature_names:
|
|
59
|
+
if shared_feature[feature_name]:
|
|
60
|
+
embedding_names.append(feature_name + "@" + embedding_config.name)
|
|
61
|
+
else:
|
|
62
|
+
embedding_names.append(feature_name)
|
|
63
|
+
embedding_names_by_table.append(embedding_names)
|
|
64
|
+
return embedding_names_by_table
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class EmbeddingBagCollection(EmbeddingBagCollectionInterface):
|
|
68
|
+
"""
|
|
69
|
+
EmbeddingBagCollection represents a collection of pooled embeddings (`EmbeddingBags`).
|
|
70
|
+
|
|
71
|
+
It processes sparse data in the form of `KeyedJaggedTensor` with values of the form
|
|
72
|
+
[F X B X L] where:
|
|
73
|
+
|
|
74
|
+
* F: features (keys)
|
|
75
|
+
* B: batch size
|
|
76
|
+
* L: length of sparse features (jagged)
|
|
77
|
+
|
|
78
|
+
and outputs a `KeyedTensor` with values of the form [B * (F * D)] where:
|
|
79
|
+
|
|
80
|
+
* F: features (keys)
|
|
81
|
+
* D: each feature's (key's) embedding dimension
|
|
82
|
+
* B: batch size
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
tables (List[EmbeddingBagConfig]): list of embedding tables.
|
|
86
|
+
is_weighted (bool): whether input `KeyedJaggedTensor` is weighted.
|
|
87
|
+
device (Optional[torch.device]): default compute device.
|
|
88
|
+
|
|
89
|
+
Example::
|
|
90
|
+
|
|
91
|
+
table_0 = EmbeddingBagConfig(
|
|
92
|
+
name="t1", embedding_dim=3, num_embeddings=10, feature_names=["f1"]
|
|
93
|
+
)
|
|
94
|
+
table_1 = EmbeddingBagConfig(
|
|
95
|
+
name="t2", embedding_dim=4, num_embeddings=10, feature_names=["f2"]
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
ebc = EmbeddingBagCollection(tables=[table_0, table_1])
|
|
99
|
+
|
|
100
|
+
# 0 1 2 <-- batch
|
|
101
|
+
# "f1" [0,1] None [2]
|
|
102
|
+
# "f2" [3] [4] [5,6,7]
|
|
103
|
+
# ^
|
|
104
|
+
# feature
|
|
105
|
+
|
|
106
|
+
features = KeyedJaggedTensor(
|
|
107
|
+
keys=["f1", "f2"],
|
|
108
|
+
values=torch.tensor([0, 1, 2, 3, 4, 5, 6, 7]),
|
|
109
|
+
offsets=torch.tensor([0, 2, 2, 3, 4, 5, 8]),
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
pooled_embeddings = ebc(features)
|
|
113
|
+
print(pooled_embeddings.values())
|
|
114
|
+
tensor([[-0.6149, 0.0000, -0.3176],
|
|
115
|
+
[-0.8876, 0.0000, -1.5606],
|
|
116
|
+
[ 1.6805, 0.0000, 0.6810],
|
|
117
|
+
[-1.4206, -1.0409, 0.2249],
|
|
118
|
+
[ 0.1823, -0.4697, 1.3823],
|
|
119
|
+
[-0.2767, -0.9965, -0.1797],
|
|
120
|
+
[ 0.8864, 0.1315, -2.0724]], grad_fn=<TransposeBackward0>)
|
|
121
|
+
print(pooled_embeddings.keys())
|
|
122
|
+
['f1', 'f2']
|
|
123
|
+
print(pooled_embeddings.offset_per_key())
|
|
124
|
+
tensor([0, 3, 7])
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
def __init__(
|
|
128
|
+
self,
|
|
129
|
+
tables: List[EmbeddingBagConfig],
|
|
130
|
+
is_weighted: bool = False,
|
|
131
|
+
device: Optional[torch.device] = None,
|
|
132
|
+
) -> None:
|
|
133
|
+
super().__init__()
|
|
134
|
+
torch._C._log_api_usage_once(f"torchrec.modules.{self.__class__.__name__}")
|
|
135
|
+
self._is_weighted = is_weighted
|
|
136
|
+
self.embedding_bags: nn.ModuleDict = nn.ModuleDict()
|
|
137
|
+
self._embedding_bag_configs = tables
|
|
138
|
+
self._lengths_per_embedding: List[int] = []
|
|
139
|
+
table_names = set()
|
|
140
|
+
for embedding_config in tables:
|
|
141
|
+
if embedding_config.name in table_names:
|
|
142
|
+
raise ValueError(f"Duplicate table name {embedding_config.name}")
|
|
143
|
+
table_names.add(embedding_config.name)
|
|
144
|
+
dtype = (
|
|
145
|
+
torch.float32
|
|
146
|
+
if embedding_config.data_type == DataType.FP32
|
|
147
|
+
else torch.float16
|
|
148
|
+
)
|
|
149
|
+
self.embedding_bags[embedding_config.name] = nn.EmbeddingBag(
|
|
150
|
+
num_embeddings=embedding_config.num_embeddings,
|
|
151
|
+
embedding_dim=embedding_config.embedding_dim,
|
|
152
|
+
mode=pooling_type_to_str(embedding_config.pooling),
|
|
153
|
+
device=device,
|
|
154
|
+
include_last_offset=True,
|
|
155
|
+
dtype=dtype,
|
|
156
|
+
)
|
|
157
|
+
if not embedding_config.feature_names:
|
|
158
|
+
embedding_config.feature_names = [embedding_config.name]
|
|
159
|
+
self._lengths_per_embedding.extend(
|
|
160
|
+
len(embedding_config.feature_names) * [embedding_config.embedding_dim]
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
self._embedding_names: List[str] = [
|
|
164
|
+
embedding
|
|
165
|
+
for embeddings in get_embedding_names_by_table(tables)
|
|
166
|
+
for embedding in embeddings
|
|
167
|
+
]
|
|
168
|
+
|
|
169
|
+
def forward(self, features: KeyedJaggedTensor) -> KeyedTensor:
|
|
170
|
+
"""
|
|
171
|
+
Args:
|
|
172
|
+
features (KeyedJaggedTensor): KJT of form [F X B X L].
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
KeyedTensor
|
|
176
|
+
"""
|
|
177
|
+
|
|
178
|
+
pooled_embeddings: List[torch.Tensor] = []
|
|
179
|
+
|
|
180
|
+
feature_dict = features.to_dict()
|
|
181
|
+
for embedding_config, embedding_bag in zip(
|
|
182
|
+
self._embedding_bag_configs, self.embedding_bags.values()
|
|
183
|
+
):
|
|
184
|
+
for feature_name in embedding_config.feature_names:
|
|
185
|
+
f = feature_dict[feature_name]
|
|
186
|
+
res = embedding_bag(
|
|
187
|
+
input=f.values(),
|
|
188
|
+
offsets=f.offsets(),
|
|
189
|
+
per_sample_weights=f.weights() if self._is_weighted else None,
|
|
190
|
+
)
|
|
191
|
+
pooled_embeddings.append(res)
|
|
192
|
+
data = torch.cat(pooled_embeddings, dim=1)
|
|
193
|
+
return KeyedTensor(
|
|
194
|
+
keys=self._embedding_names,
|
|
195
|
+
values=data,
|
|
196
|
+
length_per_key=self._lengths_per_embedding,
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
@property
|
|
200
|
+
def embedding_bag_configs(self) -> List[EmbeddingBagConfig]:
|
|
201
|
+
return self._embedding_bag_configs
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def is_weighted(self) -> bool:
|
|
205
|
+
return self._is_weighted
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class EmbeddingCollectionInterface(abc.ABC, nn.Module):
|
|
209
|
+
"""
|
|
210
|
+
Interface for `EmbeddingCollection`.
|
|
211
|
+
"""
|
|
212
|
+
|
|
213
|
+
@abc.abstractmethod
|
|
214
|
+
def forward(
|
|
215
|
+
self,
|
|
216
|
+
features: KeyedJaggedTensor,
|
|
217
|
+
) -> Dict[str, JaggedTensor]:
|
|
218
|
+
pass
|
|
219
|
+
|
|
220
|
+
@abc.abstractproperty
|
|
221
|
+
def embedding_configs(
|
|
222
|
+
self,
|
|
223
|
+
) -> List[EmbeddingConfig]:
|
|
224
|
+
pass
|
|
225
|
+
|
|
226
|
+
@abc.abstractproperty
|
|
227
|
+
def need_indices(self) -> bool:
|
|
228
|
+
pass
|
|
229
|
+
|
|
230
|
+
@abc.abstractproperty
|
|
231
|
+
def embedding_dim(self) -> int:
|
|
232
|
+
pass
|
|
233
|
+
|
|
234
|
+
@abc.abstractproperty
|
|
235
|
+
def embedding_names_by_table(self) -> List[List[str]]:
|
|
236
|
+
pass
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class EmbeddingCollection(EmbeddingCollectionInterface):
|
|
240
|
+
"""
|
|
241
|
+
EmbeddingCollection represents a collection of non-pooled embeddings.
|
|
242
|
+
|
|
243
|
+
It processes sparse data in the form of `KeyedJaggedTensor` of the form [F X B X L]
|
|
244
|
+
where:
|
|
245
|
+
|
|
246
|
+
* F: features (keys)
|
|
247
|
+
* B: batch size
|
|
248
|
+
* L: length of sparse features (variable)
|
|
249
|
+
|
|
250
|
+
and outputs `Dict[feature (key), JaggedTensor]`.
|
|
251
|
+
Each `JaggedTensor` contains values of the form (B * L) X D
|
|
252
|
+
where:
|
|
253
|
+
|
|
254
|
+
* B: batch size
|
|
255
|
+
* L: length of sparse features (jagged)
|
|
256
|
+
* D: each feature's (key's) embedding dimension and lengths are of the form L
|
|
257
|
+
|
|
258
|
+
Args:
|
|
259
|
+
tables (List[EmbeddingConfig]): list of embedding tables.
|
|
260
|
+
device (Optional[torch.device]): default compute device.
|
|
261
|
+
need_indices (bool): if we need to pass indices to the final lookup dict.
|
|
262
|
+
|
|
263
|
+
Example::
|
|
264
|
+
|
|
265
|
+
e1_config = EmbeddingConfig(
|
|
266
|
+
name="t1", embedding_dim=3, num_embeddings=10, feature_names=["f1"]
|
|
267
|
+
)
|
|
268
|
+
e2_config = EmbeddingConfig(
|
|
269
|
+
name="t2", embedding_dim=3, num_embeddings=10, feature_names=["f2"]
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
ec = EmbeddingCollection(tables=[e1_config, e2_config])
|
|
273
|
+
|
|
274
|
+
# 0 1 2 <-- batch
|
|
275
|
+
# 0 [0,1] None [2]
|
|
276
|
+
# 1 [3] [4] [5,6,7]
|
|
277
|
+
# ^
|
|
278
|
+
# feature
|
|
279
|
+
|
|
280
|
+
features = KeyedJaggedTensor.from_offsets_sync(
|
|
281
|
+
keys=["f1", "f2"],
|
|
282
|
+
values=torch.tensor([0, 1, 2, 3, 4, 5, 6, 7]),
|
|
283
|
+
offsets=torch.tensor([0, 2, 2, 3, 4, 5, 8]),
|
|
284
|
+
)
|
|
285
|
+
feature_embeddings = ec(features)
|
|
286
|
+
print(feature_embeddings['f2'].values())
|
|
287
|
+
tensor([[-0.2050, 0.5478, 0.6054],
|
|
288
|
+
[ 0.7352, 0.3210, -3.0399],
|
|
289
|
+
[ 0.1279, -0.1756, -0.4130],
|
|
290
|
+
[ 0.7519, -0.4341, -0.0499],
|
|
291
|
+
[ 0.9329, -1.0697, -0.8095]], grad_fn=<EmbeddingBackward>)
|
|
292
|
+
"""
|
|
293
|
+
|
|
294
|
+
def __init__( # noqa C901
|
|
295
|
+
self,
|
|
296
|
+
tables: List[EmbeddingConfig],
|
|
297
|
+
device: Optional[torch.device] = None,
|
|
298
|
+
need_indices: bool = False,
|
|
299
|
+
) -> None:
|
|
300
|
+
super().__init__()
|
|
301
|
+
torch._C._log_api_usage_once(f"torchrec.modules.{self.__class__.__name__}")
|
|
302
|
+
self.embeddings: nn.ModuleDict = nn.ModuleDict()
|
|
303
|
+
self._embedding_configs = tables
|
|
304
|
+
self._embedding_dim: int = -1
|
|
305
|
+
self._need_indices: bool = need_indices
|
|
306
|
+
table_names = set()
|
|
307
|
+
for config in tables:
|
|
308
|
+
if config.name in table_names:
|
|
309
|
+
raise ValueError(f"Duplicate table name {config.name}")
|
|
310
|
+
table_names.add(config.name)
|
|
311
|
+
self._embedding_dim = (
|
|
312
|
+
config.embedding_dim if self._embedding_dim < 0 else self._embedding_dim
|
|
313
|
+
)
|
|
314
|
+
if self._embedding_dim != config.embedding_dim:
|
|
315
|
+
raise ValueError(
|
|
316
|
+
"All tables in a EmbeddingCollection are required to have same embedding dimension."
|
|
317
|
+
)
|
|
318
|
+
dtype = (
|
|
319
|
+
torch.float32 if config.data_type == DataType.FP32 else torch.float16
|
|
320
|
+
)
|
|
321
|
+
self.embeddings[config.name] = nn.Embedding(
|
|
322
|
+
num_embeddings=config.num_embeddings,
|
|
323
|
+
embedding_dim=config.embedding_dim,
|
|
324
|
+
device=device,
|
|
325
|
+
dtype=dtype,
|
|
326
|
+
)
|
|
327
|
+
if not config.feature_names:
|
|
328
|
+
config.feature_names = [config.name]
|
|
329
|
+
|
|
330
|
+
self._embedding_names_by_table: List[List[str]] = get_embedding_names_by_table(
|
|
331
|
+
tables
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
def forward(
|
|
335
|
+
self,
|
|
336
|
+
features: KeyedJaggedTensor,
|
|
337
|
+
) -> Dict[str, JaggedTensor]:
|
|
338
|
+
"""
|
|
339
|
+
Args:
|
|
340
|
+
features (KeyedJaggedTensor): KJT of form [F X B X L].
|
|
341
|
+
|
|
342
|
+
Returns:
|
|
343
|
+
Dict[str, JaggedTensor]
|
|
344
|
+
"""
|
|
345
|
+
|
|
346
|
+
feature_embeddings: Dict[str, JaggedTensor] = {}
|
|
347
|
+
jt_dict: Dict[str, JaggedTensor] = features.to_dict()
|
|
348
|
+
for config, embedding_names, emb_module in zip(
|
|
349
|
+
self._embedding_configs,
|
|
350
|
+
self._embedding_names_by_table,
|
|
351
|
+
self.embeddings.values(),
|
|
352
|
+
):
|
|
353
|
+
for feature_name, embedding_name in zip(
|
|
354
|
+
config.feature_names, embedding_names
|
|
355
|
+
):
|
|
356
|
+
f = jt_dict[feature_name]
|
|
357
|
+
lookup = emb_module(
|
|
358
|
+
input=f.values(),
|
|
359
|
+
)
|
|
360
|
+
feature_embeddings[embedding_name] = JaggedTensor(
|
|
361
|
+
values=lookup,
|
|
362
|
+
lengths=f.lengths(),
|
|
363
|
+
weights=f.values() if self._need_indices else None,
|
|
364
|
+
)
|
|
365
|
+
return feature_embeddings
|
|
366
|
+
|
|
367
|
+
@property
|
|
368
|
+
def need_indices(self) -> bool:
|
|
369
|
+
return self._need_indices
|
|
370
|
+
|
|
371
|
+
@property
|
|
372
|
+
def embedding_dim(self) -> int:
|
|
373
|
+
return self._embedding_dim
|
|
374
|
+
|
|
375
|
+
@property
|
|
376
|
+
def embedding_configs(self) -> List[EmbeddingConfig]:
|
|
377
|
+
return self._embedding_configs
|
|
378
|
+
|
|
379
|
+
@property
|
|
380
|
+
def embedding_names_by_table(self) -> List[List[str]]:
|
|
381
|
+
return self._embedding_names_by_table
|
|
@@ -0,0 +1,150 @@
|
|
|
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
|
+
|
|
9
|
+
from typing import List, Optional, Tuple
|
|
10
|
+
|
|
11
|
+
import torch
|
|
12
|
+
import torch.nn as nn
|
|
13
|
+
from torchrec.modules.embedding_modules import (
|
|
14
|
+
EmbeddingBagCollection,
|
|
15
|
+
EmbeddingCollection,
|
|
16
|
+
)
|
|
17
|
+
from torchrec.sparse.jagged_tensor import KeyedJaggedTensor
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def tower_input_params(module: nn.Module) -> Tuple[bool, bool]:
|
|
21
|
+
"""
|
|
22
|
+
Utilty to compute the mapping of tower KJT args to pass to the embedding modules.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
module (nn.Module):
|
|
26
|
+
Returns:
|
|
27
|
+
Tuple[bool, bool]: tuple of 2 booleans representing if KJT and weighted KJT are required, respectively.
|
|
28
|
+
"""
|
|
29
|
+
if isinstance(module, EmbeddingCollection):
|
|
30
|
+
return True, False
|
|
31
|
+
elif isinstance(module, EmbeddingBagCollection):
|
|
32
|
+
return not module.is_weighted, module.is_weighted
|
|
33
|
+
# default to assuming both kjt and weight_kjt required
|
|
34
|
+
return True, True
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class EmbeddingTower(nn.Module):
|
|
38
|
+
"""
|
|
39
|
+
Logical "Tower" of embeddings directly passed to provided interaction.
|
|
40
|
+
All TorchRec shardable embedding modules are supported.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
embedding_module (nn.Module):
|
|
44
|
+
interaction_module (nn.Module):
|
|
45
|
+
device (Optional[torch.device]):
|
|
46
|
+
|
|
47
|
+
Example::
|
|
48
|
+
|
|
49
|
+
ebc, interaction = EmbeddingBagCollection(), MyInteractionModule()
|
|
50
|
+
tower = EmbeddingTower(ebc, interaction, device)
|
|
51
|
+
kjt = KeyedJaggedTensor()
|
|
52
|
+
output = tower(kjt)
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
embedding_module: nn.Module,
|
|
58
|
+
interaction_module: nn.Module,
|
|
59
|
+
device: Optional[torch.device] = None,
|
|
60
|
+
) -> None:
|
|
61
|
+
super().__init__()
|
|
62
|
+
self.embedding = embedding_module
|
|
63
|
+
self.interaction = interaction_module
|
|
64
|
+
|
|
65
|
+
def forward(
|
|
66
|
+
self,
|
|
67
|
+
# pyre-ignore [2]
|
|
68
|
+
*args,
|
|
69
|
+
# pyre-ignore [2]
|
|
70
|
+
**kwargs,
|
|
71
|
+
) -> torch.Tensor:
|
|
72
|
+
"""
|
|
73
|
+
Executes the embedding module and interaction module.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
*args (Any): user provided positional arguments.
|
|
77
|
+
**kwargs (Any): user provided keyword arguments.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
torch.Tensor: 2-D tensor of shape of `N X B`, where `B` is local batch size.
|
|
81
|
+
"""
|
|
82
|
+
embeddings = self.embedding(*args, **kwargs)
|
|
83
|
+
return self.interaction(embeddings)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class EmbeddingTowerCollection(nn.Module):
|
|
87
|
+
"""
|
|
88
|
+
Collection of EmbeddingTowers.
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
towers (List[EmbeddingTower]): list of embedding towers that make up the
|
|
92
|
+
collection.
|
|
93
|
+
device (Optional[torch.device]): default compute device.
|
|
94
|
+
|
|
95
|
+
Example::
|
|
96
|
+
|
|
97
|
+
ebc, ebc_interaction = EmbeddingBagCollection(), MyEBCInteractionModule()
|
|
98
|
+
eb, eb_interaction = EmbeddingCollection(), MyECInteractionModule()
|
|
99
|
+
tower_0 = EmbeddingTower(ebc, ebc_interaction, device)
|
|
100
|
+
tower_1 = EmbeddingTower(eb, eb_interaction, device)
|
|
101
|
+
tower_collection = EmbeddingTowerCollection([tower_0, tower_1])
|
|
102
|
+
kjt = KeyedJaggedTensor()
|
|
103
|
+
output = tower_collection(kjt)
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
def __init__(
|
|
107
|
+
self,
|
|
108
|
+
towers: List[EmbeddingTower],
|
|
109
|
+
device: Optional[torch.device] = None,
|
|
110
|
+
) -> None:
|
|
111
|
+
super().__init__()
|
|
112
|
+
self.towers = nn.ModuleList(towers)
|
|
113
|
+
self._input_params: List[Tuple[bool, bool]] = []
|
|
114
|
+
for tower in towers:
|
|
115
|
+
self._input_params.append(tower_input_params(tower.embedding))
|
|
116
|
+
|
|
117
|
+
def forward(
|
|
118
|
+
self,
|
|
119
|
+
features: Optional[KeyedJaggedTensor] = None,
|
|
120
|
+
weighted_features: Optional[KeyedJaggedTensor] = None,
|
|
121
|
+
) -> torch.Tensor:
|
|
122
|
+
"""
|
|
123
|
+
Executes the collection of towers.
|
|
124
|
+
|
|
125
|
+
Features and/or weighted features must be provided as required by the
|
|
126
|
+
underlying embedding modules.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
features (Optional[KeyedJaggedTensor]):
|
|
130
|
+
weighted_features (Optional[KeyedJaggedTensor]):
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
torch.Tensor: 2-D tensor of shape `M X B`, where `M = sum(N_i)` for tower output i, and `B` is local batch size.
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
tower_outputs = []
|
|
137
|
+
for tower, input_params in zip(self.towers, self._input_params):
|
|
138
|
+
has_kjt_param, has_wkjt_param = input_params
|
|
139
|
+
if has_kjt_param and has_wkjt_param:
|
|
140
|
+
assert features is not None
|
|
141
|
+
assert weighted_features is not None
|
|
142
|
+
tower_outputs.append(tower(features, weighted_features))
|
|
143
|
+
elif has_wkjt_param:
|
|
144
|
+
assert weighted_features is not None
|
|
145
|
+
tower_outputs.append(tower(weighted_features))
|
|
146
|
+
else:
|
|
147
|
+
assert features is not None
|
|
148
|
+
tower_outputs.append(tower(features))
|
|
149
|
+
|
|
150
|
+
return torch.cat(tower_outputs, dim=1)
|
|
@@ -0,0 +1,74 @@
|
|
|
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
|
+
from typing import Dict
|
|
10
|
+
|
|
11
|
+
import torch
|
|
12
|
+
import torch.nn as nn
|
|
13
|
+
from torchrec.sparse.jagged_tensor import JaggedTensor
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class BaseFeatureProcessor(nn.Module):
|
|
17
|
+
"""
|
|
18
|
+
Abstract base class for feature processor.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
@abc.abstractmethod
|
|
22
|
+
def forward(
|
|
23
|
+
self,
|
|
24
|
+
features: Dict[str, JaggedTensor],
|
|
25
|
+
) -> Dict[str, JaggedTensor]:
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class PositionWeightedModule(BaseFeatureProcessor):
|
|
30
|
+
"""
|
|
31
|
+
Adds position weights to id list features.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
max_feature_lengths (Dict[str, int]): feature name to `max_length` mapping.
|
|
35
|
+
`max_length`, a.k.a truncation size, specifies the maximum number of ids
|
|
36
|
+
each sample has. For each feature, its position weight parameter size is
|
|
37
|
+
`max_length`.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
max_feature_lengths: Dict[str, int],
|
|
43
|
+
) -> None:
|
|
44
|
+
super().__init__()
|
|
45
|
+
self.max_feature_lengths = max_feature_lengths
|
|
46
|
+
self.position_weights: nn.ParameterDict = nn.ParameterDict()
|
|
47
|
+
for key, length in max_feature_lengths.items():
|
|
48
|
+
self.position_weights[key] = nn.Parameter(torch.empty([length]).fill_(1.0))
|
|
49
|
+
|
|
50
|
+
def forward(
|
|
51
|
+
self,
|
|
52
|
+
features: Dict[str, JaggedTensor],
|
|
53
|
+
) -> Dict[str, JaggedTensor]:
|
|
54
|
+
"""
|
|
55
|
+
Args:
|
|
56
|
+
features (Dict[str, JaggedTensor]): dictionary of keys to `JaggedTensor`,
|
|
57
|
+
representing the features.
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
Dict[str, JaggedTensor]: same as input features with `weights` field being populated.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
weighted_features: Dict[str, JaggedTensor] = {}
|
|
64
|
+
for key, pos_weight in self.position_weights.items():
|
|
65
|
+
seq = torch.ops.fbgemm.offsets_range(
|
|
66
|
+
features[key].offsets().long(), torch.numel(features[key].values())
|
|
67
|
+
)
|
|
68
|
+
weighted_features[key] = JaggedTensor(
|
|
69
|
+
values=features[key].values(),
|
|
70
|
+
lengths=features[key].lengths(),
|
|
71
|
+
offsets=features[key].offsets(),
|
|
72
|
+
weights=torch.gather(pos_weight, dim=0, index=seq),
|
|
73
|
+
)
|
|
74
|
+
return weighted_features
|