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,625 @@
|
|
|
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
|
+
#!/usr/bin/env python3
|
|
9
|
+
|
|
10
|
+
import copy
|
|
11
|
+
import itertools
|
|
12
|
+
from collections import defaultdict, OrderedDict
|
|
13
|
+
from typing import Any, cast, Dict, Iterator, List, Optional, Set, Tuple, Type, Union
|
|
14
|
+
|
|
15
|
+
import torch
|
|
16
|
+
import torch.nn as nn
|
|
17
|
+
import torchrec.optim as trec_optim
|
|
18
|
+
from fbgemm_gpu.split_embedding_configs import EmbOptimType
|
|
19
|
+
from fbgemm_gpu.split_table_batched_embeddings_ops import (
|
|
20
|
+
ComputeDevice,
|
|
21
|
+
EmbeddingLocation,
|
|
22
|
+
SplitTableBatchedEmbeddingBagsCodegen,
|
|
23
|
+
)
|
|
24
|
+
from torch.nn.modules.module import _IncompatibleKeys
|
|
25
|
+
from torchrec.modules.embedding_configs import (
|
|
26
|
+
DataType,
|
|
27
|
+
EmbeddingBagConfig,
|
|
28
|
+
pooling_type_to_pooling_mode,
|
|
29
|
+
PoolingType,
|
|
30
|
+
)
|
|
31
|
+
from torchrec.modules.embedding_modules import (
|
|
32
|
+
EmbeddingBagCollection,
|
|
33
|
+
EmbeddingBagCollectionInterface,
|
|
34
|
+
EmbeddingCollection,
|
|
35
|
+
get_embedding_names_by_table,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
from torchrec.optim.fused import FusedOptimizer, FusedOptimizerModule
|
|
39
|
+
from torchrec.optim.keyed import CombinedOptimizer, KeyedOptimizer
|
|
40
|
+
from torchrec.sparse.jagged_tensor import KeyedJaggedTensor, KeyedTensor
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class EmbeddingFusedOptimizer(FusedOptimizer):
|
|
44
|
+
"""
|
|
45
|
+
EmbeddingFusedOptimizer exposes the internal SplitTableBatchedEmbeddingBagsCodeGen optimizer state.
|
|
46
|
+
It can be used like a normal optimizer to perform functionalities such as loading/saving optimizers
|
|
47
|
+
and updating learning rates.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
tables (List[EmbeddingBagConfig]): list of embedding tables.
|
|
51
|
+
emb_module (SplitTableBatchedEmbeddingBagsCodeGen): Fbgemm module whose optimizer state we want to expose
|
|
52
|
+
Example:
|
|
53
|
+
See usage in _BatchedFusedEmbeddingBag
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__( # noqa C901
|
|
57
|
+
self,
|
|
58
|
+
tables: List[EmbeddingBagConfig],
|
|
59
|
+
emb_module: SplitTableBatchedEmbeddingBagsCodegen,
|
|
60
|
+
) -> None:
|
|
61
|
+
self._emb_module: SplitTableBatchedEmbeddingBagsCodegen = emb_module
|
|
62
|
+
|
|
63
|
+
# pyre-ignore [33]
|
|
64
|
+
state: Dict[Any, Any] = {}
|
|
65
|
+
param_group: Dict[str, Any] = {
|
|
66
|
+
"params": [],
|
|
67
|
+
"lr": emb_module.optimizer_args.learning_rate,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
params: Dict[str, torch.Tensor] = {}
|
|
71
|
+
|
|
72
|
+
# Fused optimizers use buffers (they don't use autograd) and we want to make sure
|
|
73
|
+
# that state_dict look identical to no-fused version.
|
|
74
|
+
split_embedding_weights = emb_module.split_embedding_weights()
|
|
75
|
+
split_optimizer_states = emb_module.split_optimizer_states()
|
|
76
|
+
|
|
77
|
+
for embedding_weight, optimizer_states, table in zip(
|
|
78
|
+
split_embedding_weights, split_optimizer_states, tables
|
|
79
|
+
):
|
|
80
|
+
weight = embedding_weight
|
|
81
|
+
|
|
82
|
+
state[weight] = {}
|
|
83
|
+
param_group["params"].append(weight)
|
|
84
|
+
param_key = table.name + ".weight"
|
|
85
|
+
params[param_key] = weight
|
|
86
|
+
|
|
87
|
+
if len(optimizer_states) >= 1:
|
|
88
|
+
state[weight][f"{param_key}.momentum_1"] = optimizer_states[0]
|
|
89
|
+
if len(optimizer_states) >= 2:
|
|
90
|
+
state[weight][f"{param_key}.momentum_2"] = optimizer_states[1]
|
|
91
|
+
|
|
92
|
+
super().__init__(params, state, [param_group])
|
|
93
|
+
|
|
94
|
+
def zero_grad(self, set_to_none: bool = False) -> None:
|
|
95
|
+
# pyre-ignore [16]
|
|
96
|
+
self._emb_module.set_learning_rate(self.param_groups[0]["lr"])
|
|
97
|
+
|
|
98
|
+
# pyre-ignore [2]
|
|
99
|
+
def step(self, closure: Any = None) -> None:
|
|
100
|
+
# pyre-ignore [16]
|
|
101
|
+
self._emb_module.set_learning_rate(self.param_groups[0]["lr"])
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class _BatchedFusedEmbeddingBag(nn.Module, FusedOptimizerModule):
|
|
105
|
+
"""
|
|
106
|
+
_BatchedFusedEmbeddingBag is a thin wrapper we have around SplitTableBatchedEmbeddingBagsCodegen.
|
|
107
|
+
This is not meant to be directly used. Instead use FusedEmbeddingBagCollection (which in turn utilizes this).
|
|
108
|
+
|
|
109
|
+
Example
|
|
110
|
+
-------
|
|
111
|
+
>>> See usage in FusedEmbeddingBagcCollection
|
|
112
|
+
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
def __init__(
|
|
116
|
+
self,
|
|
117
|
+
embedding_tables: List[EmbeddingBagConfig],
|
|
118
|
+
data_type: DataType,
|
|
119
|
+
pooling: PoolingType,
|
|
120
|
+
optimizer_type: EmbOptimType,
|
|
121
|
+
optimizer_kwargs: Dict[str, Any],
|
|
122
|
+
device: torch.device,
|
|
123
|
+
embedding_location: EmbeddingLocation,
|
|
124
|
+
) -> None:
|
|
125
|
+
super().__init__()
|
|
126
|
+
|
|
127
|
+
self._rows: List[int] = []
|
|
128
|
+
self._weight_init_mins: List[float] = []
|
|
129
|
+
self._weight_init_maxs: List[float] = []
|
|
130
|
+
self._num_embeddings: List[int] = []
|
|
131
|
+
self._cols: List[int] = []
|
|
132
|
+
self._feature_table_map: List[int] = []
|
|
133
|
+
self._emb_names: List[str] = []
|
|
134
|
+
self._embedding_tables = embedding_tables
|
|
135
|
+
|
|
136
|
+
for idx, table in enumerate(embedding_tables):
|
|
137
|
+
self._rows.append(table.num_embeddings)
|
|
138
|
+
self._weight_init_mins.append(table.get_weight_init_min())
|
|
139
|
+
self._weight_init_maxs.append(table.get_weight_init_max())
|
|
140
|
+
self._num_embeddings.append(table.num_embeddings)
|
|
141
|
+
self._cols.append(table.embedding_dim)
|
|
142
|
+
self._feature_table_map.extend([idx] * table.num_features())
|
|
143
|
+
|
|
144
|
+
compute_device = ComputeDevice.CPU
|
|
145
|
+
if device.type == "cuda":
|
|
146
|
+
compute_device = ComputeDevice.CUDA
|
|
147
|
+
|
|
148
|
+
self._emb_module: SplitTableBatchedEmbeddingBagsCodegen = (
|
|
149
|
+
SplitTableBatchedEmbeddingBagsCodegen(
|
|
150
|
+
list(
|
|
151
|
+
zip(
|
|
152
|
+
self._num_embeddings,
|
|
153
|
+
self._cols,
|
|
154
|
+
[embedding_location] * len(embedding_tables),
|
|
155
|
+
[compute_device] * len(embedding_tables),
|
|
156
|
+
)
|
|
157
|
+
),
|
|
158
|
+
feature_table_map=self._feature_table_map,
|
|
159
|
+
pooling_mode=pooling_type_to_pooling_mode(pooling),
|
|
160
|
+
device=device,
|
|
161
|
+
optimizer=optimizer_type,
|
|
162
|
+
**optimizer_kwargs,
|
|
163
|
+
)
|
|
164
|
+
)
|
|
165
|
+
self._optim: EmbeddingFusedOptimizer = EmbeddingFusedOptimizer(
|
|
166
|
+
embedding_tables,
|
|
167
|
+
self._emb_module,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
self._init_parameters()
|
|
171
|
+
|
|
172
|
+
def forward(
|
|
173
|
+
self,
|
|
174
|
+
values: torch.Tensor,
|
|
175
|
+
offsets: torch.Tensor,
|
|
176
|
+
weights: Optional[torch.Tensor],
|
|
177
|
+
) -> torch.Tensor:
|
|
178
|
+
"""
|
|
179
|
+
Args:
|
|
180
|
+
values (torch.Tensor): Tensor containing bags of indicies into the embedding matrix.
|
|
181
|
+
offsets (torch.Tensor): Starting index position of each sequence
|
|
182
|
+
weights (Optional[torch.Tensor]): weights to use to calculate weighted pooling
|
|
183
|
+
Returns:
|
|
184
|
+
Tensor output of `(B , table_1_embedding_dim + table_2_embedding_dim + ...)`
|
|
185
|
+
"""
|
|
186
|
+
|
|
187
|
+
return self._emb_module(
|
|
188
|
+
indices=values,
|
|
189
|
+
offsets=offsets,
|
|
190
|
+
per_sample_weights=weights,
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
def _init_parameters(self) -> None:
|
|
194
|
+
assert len(self._num_embeddings) == len(
|
|
195
|
+
self._emb_module.split_embedding_weights()
|
|
196
|
+
)
|
|
197
|
+
for (rows, emb_dim, weight_init_min, weight_init_max, param) in zip(
|
|
198
|
+
self._rows,
|
|
199
|
+
self._cols,
|
|
200
|
+
self._weight_init_mins,
|
|
201
|
+
self._weight_init_maxs,
|
|
202
|
+
self._emb_module.split_embedding_weights(),
|
|
203
|
+
):
|
|
204
|
+
assert param.shape == (rows, emb_dim)
|
|
205
|
+
param.data.uniform_(
|
|
206
|
+
weight_init_min,
|
|
207
|
+
weight_init_max,
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
def split_embedding_weights(self) -> List[torch.Tensor]:
|
|
211
|
+
return self._emb_module.split_embedding_weights()
|
|
212
|
+
|
|
213
|
+
@property
|
|
214
|
+
def fused_optimizer(self) -> FusedOptimizer:
|
|
215
|
+
return self._optim
|
|
216
|
+
|
|
217
|
+
def parameters(
|
|
218
|
+
self, prefix: str = "", recurse: bool = True
|
|
219
|
+
) -> Iterator[nn.Parameter]:
|
|
220
|
+
yield cast(nn.Parameter, self._emb_module.weights)
|
|
221
|
+
|
|
222
|
+
def named_parameters(
|
|
223
|
+
self, prefix: str = "", recurse: bool = True
|
|
224
|
+
) -> Iterator[Tuple[str, nn.Parameter]]:
|
|
225
|
+
for table, weight in zip(
|
|
226
|
+
self._embedding_tables, self.split_embedding_weights()
|
|
227
|
+
):
|
|
228
|
+
name = table.name
|
|
229
|
+
key = f"{prefix}.{name}" if (prefix and name) else (prefix + name)
|
|
230
|
+
yield key, cast(nn.Parameter, weight)
|
|
231
|
+
|
|
232
|
+
def named_buffers(
|
|
233
|
+
self, prefix: str = "", recurse: bool = True
|
|
234
|
+
) -> Iterator[Tuple[str, torch.Tensor]]:
|
|
235
|
+
for table, param in zip(self._embedding_tables, self.split_embedding_weights()):
|
|
236
|
+
name = f"{table.name}.weight"
|
|
237
|
+
key = f"{prefix}.{name}" if (prefix and name) else (prefix + name)
|
|
238
|
+
yield key, param
|
|
239
|
+
|
|
240
|
+
def buffers(self, prefix: str = "", recurse: bool = True) -> Iterator[torch.Tensor]:
|
|
241
|
+
yield from self.split_embedding_weights()
|
|
242
|
+
|
|
243
|
+
def flush(self) -> None:
|
|
244
|
+
self._emb_module.flush()
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def convert_optimizer_type_and_kwargs(
|
|
248
|
+
optimizer_type: Type[torch.optim.Optimizer],
|
|
249
|
+
optimizer_kwargs: Dict[str, Any],
|
|
250
|
+
) -> Optional[Tuple[EmbOptimType, Dict[str, Any]]]:
|
|
251
|
+
optimizer_kwargs = copy.deepcopy(optimizer_kwargs)
|
|
252
|
+
if "lr" in optimizer_kwargs:
|
|
253
|
+
optimizer_kwargs["learning_rate"] = optimizer_kwargs["lr"]
|
|
254
|
+
optimizer_kwargs.pop("lr")
|
|
255
|
+
|
|
256
|
+
if optimizer_type == torch.optim.SGD:
|
|
257
|
+
return (
|
|
258
|
+
EmbOptimType.EXACT_SGD,
|
|
259
|
+
optimizer_kwargs,
|
|
260
|
+
)
|
|
261
|
+
elif optimizer_type == torch.optim.Adagrad:
|
|
262
|
+
return (EmbOptimType.EXACT_ADAGRAD, optimizer_kwargs)
|
|
263
|
+
elif optimizer_type == trec_optim.RowWiseAdagrad:
|
|
264
|
+
return (EmbOptimType.EXACT_ROWWISE_ADAGRAD, optimizer_kwargs)
|
|
265
|
+
elif optimizer_type == torch.optim.Adam:
|
|
266
|
+
return (EmbOptimType.ADAM, optimizer_kwargs)
|
|
267
|
+
|
|
268
|
+
return None
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class FusedEmbeddingBagCollection(
|
|
272
|
+
EmbeddingBagCollectionInterface, FusedOptimizerModule
|
|
273
|
+
):
|
|
274
|
+
"""
|
|
275
|
+
FusedEmbeddingBagCollection represents a collection of pooled embeddings (`EmbeddingBags`).
|
|
276
|
+
It utilizes a technique called Optimizer fusion (register the optimizer with model). The semantics
|
|
277
|
+
of this is that during the backwards pass, the registered optimizer will be called.
|
|
278
|
+
|
|
279
|
+
It processes sparse data in the form of `KeyedJaggedTensor` with values of the form
|
|
280
|
+
[F X B X L] where:
|
|
281
|
+
|
|
282
|
+
* F: features (keys)
|
|
283
|
+
* B: batch size
|
|
284
|
+
* L: length of sparse features (jagged)
|
|
285
|
+
|
|
286
|
+
and outputs a `KeyedTensor` with values of the form [B x F x D] where:
|
|
287
|
+
|
|
288
|
+
* F: features (keys)
|
|
289
|
+
* D: each feature's (key's) embedding dimension
|
|
290
|
+
* B: batch size
|
|
291
|
+
|
|
292
|
+
Args:
|
|
293
|
+
tables (List[EmbeddingBagConfig]): list of embedding tables.
|
|
294
|
+
is_weighted (bool): whether input `KeyedJaggedTensor` is weighted.
|
|
295
|
+
optimizer (Type[torch.optim.Optimizer]): fusion optimizer type
|
|
296
|
+
optimizer_kwargs: Dict[str, Any]: fusion optimizer kwargs
|
|
297
|
+
device (Optional[torch.device]): compute device.
|
|
298
|
+
|
|
299
|
+
Example::
|
|
300
|
+
|
|
301
|
+
table_0 = EmbeddingBagConfig(
|
|
302
|
+
name="t1", embedding_dim=3, num_embeddings=10, feature_names=["f1"]
|
|
303
|
+
)
|
|
304
|
+
table_1 = EmbeddingBagConfig(
|
|
305
|
+
name="t2", embedding_dim=4, num_embeddings=10, feature_names=["f2"]
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
ebc = FusedEmeddingBagCollection(tables=[table_0, table_1], optimizer=torch.optim.SGD, optimizer_kwargs={"lr": .01})
|
|
309
|
+
|
|
310
|
+
# 0 1 2 <-- batch
|
|
311
|
+
# "f1" [0,1] None [2]
|
|
312
|
+
# "f2" [3] [4] [5,6,7]
|
|
313
|
+
# ^
|
|
314
|
+
# feature
|
|
315
|
+
|
|
316
|
+
features = KeyedJaggedTensor(
|
|
317
|
+
keys=["f1", "f2"],
|
|
318
|
+
values=torch.tensor([0, 1, 2, 3, 4, 5, 6, 7]),
|
|
319
|
+
offsets=torch.tensor([0, 2, 2, 3, 4, 5, 8]),
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
pooled_embeddings = ebc(features)
|
|
323
|
+
print(pooled_embeddings.values())
|
|
324
|
+
tensor([[-0.6149, 0.0000, -0.3176],
|
|
325
|
+
[-0.8876, 0.0000, -1.5606],
|
|
326
|
+
[ 1.6805, 0.0000, 0.6810],
|
|
327
|
+
[-1.4206, -1.0409, 0.2249],
|
|
328
|
+
[ 0.1823, -0.4697, 1.3823],
|
|
329
|
+
[-0.2767, -0.9965, -0.1797],
|
|
330
|
+
[ 0.8864, 0.1315, -2.0724]], grad_fn=<TransposeBackward0>)
|
|
331
|
+
print(pooled_embeddings.keys())
|
|
332
|
+
['f1', 'f2']
|
|
333
|
+
print(pooled_embeddings.offset_per_key())
|
|
334
|
+
tensor([0, 3, 7])
|
|
335
|
+
"""
|
|
336
|
+
|
|
337
|
+
def __init__(
|
|
338
|
+
self,
|
|
339
|
+
tables: List[EmbeddingBagConfig],
|
|
340
|
+
optimizer_type: Type[torch.optim.Optimizer],
|
|
341
|
+
optimizer_kwargs: Dict[str, Any],
|
|
342
|
+
is_weighted: bool = False,
|
|
343
|
+
device: Optional[torch.device] = None,
|
|
344
|
+
location: Optional[EmbeddingLocation] = None,
|
|
345
|
+
) -> None:
|
|
346
|
+
super().__init__()
|
|
347
|
+
|
|
348
|
+
self._optimizer_type = optimizer_type
|
|
349
|
+
self._optimizer_kwargs = optimizer_kwargs
|
|
350
|
+
|
|
351
|
+
emb_optim_and_kwargs = convert_optimizer_type_and_kwargs(
|
|
352
|
+
optimizer_type, optimizer_kwargs
|
|
353
|
+
)
|
|
354
|
+
if emb_optim_and_kwargs is None:
|
|
355
|
+
raise ValueError(
|
|
356
|
+
f"Cannot fuse optimizer_type={optimizer_type} with kwargs {optimizer_kwargs}"
|
|
357
|
+
)
|
|
358
|
+
(emb_optim_type, emb_opt_kwargs) = emb_optim_and_kwargs
|
|
359
|
+
|
|
360
|
+
if location in [
|
|
361
|
+
EmbeddingLocation.DEVICE,
|
|
362
|
+
EmbeddingLocation.MANAGED,
|
|
363
|
+
EmbeddingLocation.MANAGED_CACHING,
|
|
364
|
+
]:
|
|
365
|
+
assert device is not None and device.type in [
|
|
366
|
+
"cuda",
|
|
367
|
+
"meta",
|
|
368
|
+
], f"Using location={location} requires device=cuda or meta"
|
|
369
|
+
|
|
370
|
+
if device is None:
|
|
371
|
+
device = torch.device("cpu")
|
|
372
|
+
|
|
373
|
+
if location is None:
|
|
374
|
+
if device.type in ["cpu", "meta"]:
|
|
375
|
+
location = EmbeddingLocation.HOST
|
|
376
|
+
elif device.type == "cuda":
|
|
377
|
+
location = EmbeddingLocation.DEVICE
|
|
378
|
+
else:
|
|
379
|
+
raise ValueError("EmbeddingLocation could not be set")
|
|
380
|
+
|
|
381
|
+
self._is_weighted = is_weighted
|
|
382
|
+
self._embedding_bag_configs = tables
|
|
383
|
+
self._emb_modules: nn.ModuleList = nn.ModuleList()
|
|
384
|
+
|
|
385
|
+
self._key_to_tables: Dict[
|
|
386
|
+
Tuple[PoolingType, DataType], List[EmbeddingBagConfig]
|
|
387
|
+
] = defaultdict(list)
|
|
388
|
+
|
|
389
|
+
self._embedding_names: List[str] = []
|
|
390
|
+
|
|
391
|
+
self._length_per_key: List[int] = []
|
|
392
|
+
|
|
393
|
+
for table in tables:
|
|
394
|
+
self._length_per_key.extend(
|
|
395
|
+
[table.embedding_dim] * len(table.feature_names)
|
|
396
|
+
)
|
|
397
|
+
|
|
398
|
+
key = (table.pooling, table.data_type)
|
|
399
|
+
self._key_to_tables[key].append(table)
|
|
400
|
+
|
|
401
|
+
optims = []
|
|
402
|
+
for key, tables in self._key_to_tables.items():
|
|
403
|
+
(pooling, data_type) = key
|
|
404
|
+
emb_module = _BatchedFusedEmbeddingBag(
|
|
405
|
+
tables,
|
|
406
|
+
data_type=data_type,
|
|
407
|
+
pooling=pooling,
|
|
408
|
+
optimizer_type=emb_optim_type,
|
|
409
|
+
optimizer_kwargs=emb_opt_kwargs,
|
|
410
|
+
device=device,
|
|
411
|
+
embedding_location=location,
|
|
412
|
+
)
|
|
413
|
+
self._emb_modules.append(emb_module)
|
|
414
|
+
params: Dict[str, torch.Tensor] = {}
|
|
415
|
+
for param_key, weight in emb_module.fused_optimizer.params.items():
|
|
416
|
+
# pyre-fixme[6]: For 2nd param expected `Tensor` but got
|
|
417
|
+
# `Union[Tensor, ShardedTensor]`.
|
|
418
|
+
params[f"embedding_bags.{param_key}"] = weight
|
|
419
|
+
optims.append(("", emb_module.fused_optimizer))
|
|
420
|
+
|
|
421
|
+
self._optim: CombinedOptimizer = CombinedOptimizer(optims)
|
|
422
|
+
self._embedding_names = list(
|
|
423
|
+
itertools.chain(*get_embedding_names_by_table(tables))
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
def forward(self, features: KeyedJaggedTensor) -> KeyedTensor:
|
|
427
|
+
"""
|
|
428
|
+
Args:
|
|
429
|
+
features (KeyedJaggedTensor): KJT of form [F X B X L].
|
|
430
|
+
|
|
431
|
+
Returns:
|
|
432
|
+
KeyedTensor
|
|
433
|
+
"""
|
|
434
|
+
assert features is not None
|
|
435
|
+
feature_dict = features.to_dict()
|
|
436
|
+
embeddings = []
|
|
437
|
+
|
|
438
|
+
for emb_op, (_key, tables) in zip(
|
|
439
|
+
self._emb_modules, self._key_to_tables.items()
|
|
440
|
+
):
|
|
441
|
+
indicies = []
|
|
442
|
+
lengths = []
|
|
443
|
+
offsets = []
|
|
444
|
+
weights = []
|
|
445
|
+
|
|
446
|
+
for table in tables:
|
|
447
|
+
for feature in table.feature_names:
|
|
448
|
+
f = feature_dict[feature]
|
|
449
|
+
indicies.append(f.values())
|
|
450
|
+
lengths.append(f.lengths())
|
|
451
|
+
if self._is_weighted:
|
|
452
|
+
weights.append(f.weights())
|
|
453
|
+
|
|
454
|
+
indicies = torch.cat(indicies)
|
|
455
|
+
lengths = torch.cat(lengths)
|
|
456
|
+
|
|
457
|
+
offsets = torch.ops.fbgemm.asynchronous_complete_cumsum(lengths)
|
|
458
|
+
if self._is_weighted:
|
|
459
|
+
weights = torch.cat(weights)
|
|
460
|
+
|
|
461
|
+
embeddings.append(
|
|
462
|
+
emb_op(
|
|
463
|
+
indicies.int(),
|
|
464
|
+
offsets.int(),
|
|
465
|
+
weights if self._is_weighted else None,
|
|
466
|
+
)
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
embeddings = torch.cat(embeddings, dim=1)
|
|
470
|
+
return KeyedTensor(
|
|
471
|
+
keys=self._embedding_names,
|
|
472
|
+
values=embeddings,
|
|
473
|
+
length_per_key=self._length_per_key,
|
|
474
|
+
)
|
|
475
|
+
|
|
476
|
+
# pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently.
|
|
477
|
+
def state_dict(
|
|
478
|
+
self,
|
|
479
|
+
destination: Optional[Dict[str, Any]] = None,
|
|
480
|
+
prefix: str = "",
|
|
481
|
+
keep_vars: bool = False,
|
|
482
|
+
) -> Dict[str, Any]:
|
|
483
|
+
if destination is None:
|
|
484
|
+
destination = OrderedDict()
|
|
485
|
+
# pyre-ignore [16]
|
|
486
|
+
destination._metadata = OrderedDict()
|
|
487
|
+
for emb_op, (_key, tables) in zip(
|
|
488
|
+
self._emb_modules, self._key_to_tables.items()
|
|
489
|
+
):
|
|
490
|
+
for table, weight in zip(tables, emb_op.split_embedding_weights()):
|
|
491
|
+
destination[prefix + f"embedding_bags.{table.name}.weight"] = weight
|
|
492
|
+
return destination
|
|
493
|
+
|
|
494
|
+
# pyre-fixme[14]: `load_state_dict` overrides method defined in `Module` inconsistently.
|
|
495
|
+
def load_state_dict(
|
|
496
|
+
self,
|
|
497
|
+
state_dict: "OrderedDict[str, torch.Tensor]",
|
|
498
|
+
strict: bool = True,
|
|
499
|
+
) -> _IncompatibleKeys:
|
|
500
|
+
|
|
501
|
+
missing_keys = []
|
|
502
|
+
unexpected_keys = []
|
|
503
|
+
|
|
504
|
+
current_state_dict = self.state_dict()
|
|
505
|
+
for key in current_state_dict.keys():
|
|
506
|
+
if key not in state_dict:
|
|
507
|
+
missing_keys.append(key)
|
|
508
|
+
for key in state_dict.keys():
|
|
509
|
+
if key not in current_state_dict.keys():
|
|
510
|
+
unexpected_keys.append(key)
|
|
511
|
+
|
|
512
|
+
if missing_keys or unexpected_keys:
|
|
513
|
+
return _IncompatibleKeys(
|
|
514
|
+
missing_keys=missing_keys, unexpected_keys=unexpected_keys
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
for (_key, tables) in self._key_to_tables.items():
|
|
518
|
+
for table in tables:
|
|
519
|
+
current_state_dict[
|
|
520
|
+
f"embedding_bags.{table.name}.weight"
|
|
521
|
+
].detach().copy_(state_dict[f"embedding_bags.{table.name}.weight"])
|
|
522
|
+
|
|
523
|
+
return _IncompatibleKeys(
|
|
524
|
+
missing_keys=missing_keys, unexpected_keys=unexpected_keys
|
|
525
|
+
)
|
|
526
|
+
|
|
527
|
+
def _get_name(self) -> str:
|
|
528
|
+
return "FusedEmeddingBagCollection"
|
|
529
|
+
|
|
530
|
+
@property
|
|
531
|
+
def embedding_bag_configs(self) -> List[EmbeddingBagConfig]:
|
|
532
|
+
return self._embedding_bag_configs
|
|
533
|
+
|
|
534
|
+
@property
|
|
535
|
+
def is_weighted(self) -> bool:
|
|
536
|
+
return self._is_weighted
|
|
537
|
+
|
|
538
|
+
@property
|
|
539
|
+
def optimizer_type(self) -> Type[torch.optim.Optimizer]:
|
|
540
|
+
return self._optimizer_type
|
|
541
|
+
|
|
542
|
+
@property
|
|
543
|
+
def optimizer_kwargs(self) -> Dict[str, Any]:
|
|
544
|
+
return self._optimizer_kwargs
|
|
545
|
+
|
|
546
|
+
def named_parameters(
|
|
547
|
+
self, prefix: str = "", recurse: bool = True
|
|
548
|
+
) -> Iterator[Tuple[str, nn.Parameter]]:
|
|
549
|
+
for emb_module in self._emb_modules:
|
|
550
|
+
yield from emb_module.named_parameters(prefix, recurse)
|
|
551
|
+
|
|
552
|
+
def named_buffers(
|
|
553
|
+
self, prefix: str = "", recurse: bool = True
|
|
554
|
+
) -> Iterator[Tuple[str, torch.Tensor]]:
|
|
555
|
+
for emb_module in self._emb_modules:
|
|
556
|
+
yield from emb_module.named_buffers(prefix, recurse)
|
|
557
|
+
|
|
558
|
+
@property
|
|
559
|
+
def fused_optimizer(self) -> KeyedOptimizer:
|
|
560
|
+
return self._optim
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
class FusedEmbeddingCollection(EmbeddingCollection, FusedOptimizerModule):
|
|
564
|
+
pass
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def fuse_embedding_optimizer(
|
|
568
|
+
model: nn.Module,
|
|
569
|
+
optimizer_type: Type[torch.optim.Optimizer],
|
|
570
|
+
optimizer_kwargs: Dict[str, Any],
|
|
571
|
+
device: torch.device,
|
|
572
|
+
location: Optional[EmbeddingLocation] = None,
|
|
573
|
+
) -> nn.Module:
|
|
574
|
+
"""
|
|
575
|
+
Recursively replaces EmbeddingBagCollection and EmbeddingCollection with
|
|
576
|
+
FusedEmbeddingBagCollection and FusedEmbeddingCollection in a model subtree.
|
|
577
|
+
The fused modules will be initialized using the passed in optimizer parameters, and model location.
|
|
578
|
+
|
|
579
|
+
Args:
|
|
580
|
+
model: (nn.Module):
|
|
581
|
+
optimizer_type: (Type[torch.optim.Optimizer]):
|
|
582
|
+
optimizer_kwargs: (Dict[Str, Any]):
|
|
583
|
+
device (Optional[torch.device]):
|
|
584
|
+
location: (Optional[EmbeddingLocation]): GPU location placement
|
|
585
|
+
Returns
|
|
586
|
+
nn.Module: input nn.Module with Fused Embedding Modules
|
|
587
|
+
|
|
588
|
+
Example::
|
|
589
|
+
ebc = EmbeddingBagCollection()
|
|
590
|
+
my_model = ExampleModel(ebc)
|
|
591
|
+
my_model = fused_embedding_optimizer(my_model, optimizer_type=torch.optim.SGD, optimizer_kwargs={"lr": .01})
|
|
592
|
+
kjt = KeyedJaggedTensor()
|
|
593
|
+
output = my_model(kjt)
|
|
594
|
+
"""
|
|
595
|
+
# Replace all EBCs and ECs in a with a corresponding FusedEmbeddingModule.
|
|
596
|
+
|
|
597
|
+
# check if top-level module is EBC/EC
|
|
598
|
+
if isinstance(model, EmbeddingBagCollection):
|
|
599
|
+
return FusedEmbeddingBagCollection(
|
|
600
|
+
model.embedding_bag_configs,
|
|
601
|
+
optimizer_type=optimizer_type,
|
|
602
|
+
optimizer_kwargs=optimizer_kwargs,
|
|
603
|
+
device=device,
|
|
604
|
+
location=location,
|
|
605
|
+
)
|
|
606
|
+
|
|
607
|
+
def replace(_model: nn.Module) -> None:
|
|
608
|
+
for child_name, child in _model.named_children():
|
|
609
|
+
if isinstance(child, EmbeddingBagCollection):
|
|
610
|
+
setattr(
|
|
611
|
+
_model,
|
|
612
|
+
child_name,
|
|
613
|
+
FusedEmbeddingBagCollection(
|
|
614
|
+
tables=child.embedding_bag_configs,
|
|
615
|
+
optimizer_type=optimizer_type,
|
|
616
|
+
optimizer_kwargs=optimizer_kwargs,
|
|
617
|
+
device=device,
|
|
618
|
+
location=location,
|
|
619
|
+
),
|
|
620
|
+
)
|
|
621
|
+
else:
|
|
622
|
+
replace(child)
|
|
623
|
+
|
|
624
|
+
replace(model)
|
|
625
|
+
return model
|