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,307 @@
|
|
|
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 collections import OrderedDict
|
|
10
|
+
from typing import Any, cast, Dict, List, Optional, Type
|
|
11
|
+
|
|
12
|
+
import torch
|
|
13
|
+
from torch import nn
|
|
14
|
+
from torch.nn.modules.module import _IncompatibleKeys
|
|
15
|
+
from torchrec.distributed.embedding import (
|
|
16
|
+
create_sharding_infos_by_sharding,
|
|
17
|
+
EmbeddingCollectionAwaitable,
|
|
18
|
+
EmbeddingCollectionContext,
|
|
19
|
+
EmbeddingShardingInfo,
|
|
20
|
+
)
|
|
21
|
+
from torchrec.distributed.embedding_sharding import (
|
|
22
|
+
EmbeddingSharding,
|
|
23
|
+
ListOfSparseFeaturesListAwaitable,
|
|
24
|
+
)
|
|
25
|
+
from torchrec.distributed.embedding_types import (
|
|
26
|
+
BaseQuantEmbeddingSharder,
|
|
27
|
+
ListOfSparseFeaturesList,
|
|
28
|
+
ShardingType,
|
|
29
|
+
SparseFeatures,
|
|
30
|
+
SparseFeaturesList,
|
|
31
|
+
)
|
|
32
|
+
from torchrec.distributed.sharding.sequence_sharding import SequenceShardingContext
|
|
33
|
+
from torchrec.distributed.sharding.tw_sequence_sharding import (
|
|
34
|
+
InferTwSequenceEmbeddingSharding,
|
|
35
|
+
)
|
|
36
|
+
from torchrec.distributed.types import (
|
|
37
|
+
Awaitable,
|
|
38
|
+
LazyAwaitable,
|
|
39
|
+
ParameterSharding,
|
|
40
|
+
ShardedModule,
|
|
41
|
+
ShardedModuleContext,
|
|
42
|
+
ShardingEnv,
|
|
43
|
+
)
|
|
44
|
+
from torchrec.distributed.utils import filter_state_dict
|
|
45
|
+
from torchrec.modules.embedding_configs import (
|
|
46
|
+
data_type_to_sparse_type,
|
|
47
|
+
dtype_to_data_type,
|
|
48
|
+
)
|
|
49
|
+
from torchrec.quant.embedding_modules import (
|
|
50
|
+
EmbeddingCollection as QuantEmbeddingCollection,
|
|
51
|
+
)
|
|
52
|
+
from torchrec.sparse.jagged_tensor import JaggedTensor, KeyedJaggedTensor
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops")
|
|
56
|
+
torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops_cpu")
|
|
57
|
+
except OSError:
|
|
58
|
+
pass
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def create_infer_embedding_sharding(
|
|
62
|
+
sharding_type: str,
|
|
63
|
+
sharding_infos: List[EmbeddingShardingInfo],
|
|
64
|
+
env: ShardingEnv,
|
|
65
|
+
device: Optional[torch.device] = None,
|
|
66
|
+
) -> EmbeddingSharding[SparseFeaturesList, List[torch.Tensor]]:
|
|
67
|
+
if sharding_type == ShardingType.TABLE_WISE.value:
|
|
68
|
+
return InferTwSequenceEmbeddingSharding(sharding_infos, env, device)
|
|
69
|
+
else:
|
|
70
|
+
raise ValueError(f"Sharding type not supported {sharding_type}")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class ShardedQuantEmbeddingCollection(
|
|
74
|
+
ShardedModule[
|
|
75
|
+
ListOfSparseFeaturesList, List[List[torch.Tensor]], Dict[str, JaggedTensor]
|
|
76
|
+
],
|
|
77
|
+
):
|
|
78
|
+
"""
|
|
79
|
+
Sharded implementation of `QuantEmbeddingCollection`.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
module: QuantEmbeddingCollection,
|
|
85
|
+
table_name_to_parameter_sharding: Dict[str, ParameterSharding],
|
|
86
|
+
env: ShardingEnv,
|
|
87
|
+
fused_params: Optional[Dict[str, Any]] = None,
|
|
88
|
+
) -> None:
|
|
89
|
+
super().__init__()
|
|
90
|
+
sharding_type_to_sharding_infos = create_sharding_infos_by_sharding(
|
|
91
|
+
module, table_name_to_parameter_sharding
|
|
92
|
+
)
|
|
93
|
+
self._sharding_type_to_sharding: Dict[
|
|
94
|
+
str, EmbeddingSharding[SparseFeaturesList, List[torch.Tensor]]
|
|
95
|
+
] = {
|
|
96
|
+
sharding_type: create_infer_embedding_sharding(
|
|
97
|
+
sharding_type, embedding_confings, env
|
|
98
|
+
)
|
|
99
|
+
for sharding_type, embedding_confings in sharding_type_to_sharding_infos.items()
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
self._input_dists: nn.ModuleList = nn.ModuleList()
|
|
103
|
+
self._lookups: nn.ModuleList = nn.ModuleList()
|
|
104
|
+
self._create_lookups(fused_params)
|
|
105
|
+
self._output_dists: nn.ModuleList = nn.ModuleList()
|
|
106
|
+
|
|
107
|
+
self._feature_splits: List[int] = []
|
|
108
|
+
self._features_order: List[int] = []
|
|
109
|
+
|
|
110
|
+
self._has_uninitialized_input_dist: bool = True
|
|
111
|
+
self._has_uninitialized_output_dist: bool = True
|
|
112
|
+
|
|
113
|
+
self._embedding_dim: int = module.embedding_dim
|
|
114
|
+
self._need_indices: bool = module.need_indices
|
|
115
|
+
|
|
116
|
+
def _create_input_dist(
|
|
117
|
+
self,
|
|
118
|
+
input_feature_names: List[str],
|
|
119
|
+
device: torch.device,
|
|
120
|
+
) -> None:
|
|
121
|
+
feature_names: List[str] = []
|
|
122
|
+
self._feature_splits: List[int] = []
|
|
123
|
+
for sharding in self._sharding_type_to_sharding.values():
|
|
124
|
+
self._input_dists.append(sharding.create_input_dist())
|
|
125
|
+
feature_names.extend(sharding.id_list_feature_names())
|
|
126
|
+
self._feature_splits.append(len(sharding.id_list_feature_names()))
|
|
127
|
+
self._features_order: List[int] = []
|
|
128
|
+
for f in feature_names:
|
|
129
|
+
self._features_order.append(input_feature_names.index(f))
|
|
130
|
+
self._features_order = (
|
|
131
|
+
[]
|
|
132
|
+
if self._features_order == list(range(len(self._features_order)))
|
|
133
|
+
else self._features_order
|
|
134
|
+
)
|
|
135
|
+
self.register_buffer(
|
|
136
|
+
"_features_order_tensor",
|
|
137
|
+
torch.tensor(self._features_order, device=device, dtype=torch.int32),
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
def _create_lookups(self, fused_params: Optional[Dict[str, Any]]) -> None:
|
|
141
|
+
for sharding in self._sharding_type_to_sharding.values():
|
|
142
|
+
self._lookups.append(sharding.create_lookup(fused_params=fused_params))
|
|
143
|
+
|
|
144
|
+
def _create_output_dist(
|
|
145
|
+
self,
|
|
146
|
+
device: Optional[torch.device] = None,
|
|
147
|
+
) -> None:
|
|
148
|
+
for sharding in self._sharding_type_to_sharding.values():
|
|
149
|
+
self._output_dists.append(sharding.create_output_dist(device))
|
|
150
|
+
|
|
151
|
+
# pyre-ignore [3, 14]
|
|
152
|
+
def input_dist(
|
|
153
|
+
self,
|
|
154
|
+
ctx: EmbeddingCollectionContext,
|
|
155
|
+
features: KeyedJaggedTensor,
|
|
156
|
+
) -> Awaitable[Any]:
|
|
157
|
+
if self._has_uninitialized_input_dist:
|
|
158
|
+
self._create_input_dist(
|
|
159
|
+
input_feature_names=features.keys() if features is not None else [],
|
|
160
|
+
device=features.device(),
|
|
161
|
+
)
|
|
162
|
+
self._has_uninitialized_input_dist = False
|
|
163
|
+
if self._has_uninitialized_output_dist:
|
|
164
|
+
self._create_output_dist(features.device())
|
|
165
|
+
self._has_uninitialized_output_dist = False
|
|
166
|
+
with torch.no_grad():
|
|
167
|
+
features_by_sharding = []
|
|
168
|
+
if self._features_order:
|
|
169
|
+
features = features.permute(
|
|
170
|
+
self._features_order,
|
|
171
|
+
# pyre-ignore [6]
|
|
172
|
+
self._features_order_tensor,
|
|
173
|
+
)
|
|
174
|
+
features_by_sharding = features.split(
|
|
175
|
+
self._feature_splits,
|
|
176
|
+
)
|
|
177
|
+
# save input splits and output splits in sharding context which
|
|
178
|
+
# will be reused in sequence embedding all2all
|
|
179
|
+
awaitables = []
|
|
180
|
+
for module, features in zip(self._input_dists, features_by_sharding):
|
|
181
|
+
tensor_awaitable = module(
|
|
182
|
+
SparseFeatures(
|
|
183
|
+
id_list_features=features,
|
|
184
|
+
id_score_list_features=None,
|
|
185
|
+
)
|
|
186
|
+
).wait() # a dummy wait since now length indices comm is splited
|
|
187
|
+
ctx.sharding_contexts.append(
|
|
188
|
+
SequenceShardingContext(
|
|
189
|
+
features_before_input_dist=features,
|
|
190
|
+
input_splits=[],
|
|
191
|
+
output_splits=[],
|
|
192
|
+
unbucketize_permute_tensor=None,
|
|
193
|
+
)
|
|
194
|
+
)
|
|
195
|
+
awaitables.append(tensor_awaitable)
|
|
196
|
+
return ListOfSparseFeaturesListAwaitable(awaitables)
|
|
197
|
+
|
|
198
|
+
def compute(
|
|
199
|
+
self, ctx: ShardedModuleContext, dist_input: ListOfSparseFeaturesList
|
|
200
|
+
) -> List[List[torch.Tensor]]:
|
|
201
|
+
ret: List[List[torch.Tensor]] = []
|
|
202
|
+
for lookup, features in zip(
|
|
203
|
+
self._lookups,
|
|
204
|
+
dist_input,
|
|
205
|
+
):
|
|
206
|
+
ret.append([o.view(-1, self._embedding_dim) for o in lookup(features)])
|
|
207
|
+
return ret
|
|
208
|
+
|
|
209
|
+
def output_dist(
|
|
210
|
+
self, ctx: ShardedModuleContext, output: List[List[torch.Tensor]]
|
|
211
|
+
) -> LazyAwaitable[Dict[str, JaggedTensor]]:
|
|
212
|
+
awaitables_per_sharding: List[Awaitable[torch.Tensor]] = []
|
|
213
|
+
features_before_all2all_per_sharding: List[KeyedJaggedTensor] = []
|
|
214
|
+
for odist, embeddings, sharding_ctx in zip(
|
|
215
|
+
self._output_dists,
|
|
216
|
+
output,
|
|
217
|
+
cast(EmbeddingCollectionContext, ctx).sharding_contexts,
|
|
218
|
+
):
|
|
219
|
+
awaitables_per_sharding.append(odist(embeddings, sharding_ctx))
|
|
220
|
+
features_before_all2all_per_sharding.append(
|
|
221
|
+
sharding_ctx.features_before_input_dist
|
|
222
|
+
)
|
|
223
|
+
return EmbeddingCollectionAwaitable(
|
|
224
|
+
awaitables_per_sharding=awaitables_per_sharding,
|
|
225
|
+
features_per_sharding=features_before_all2all_per_sharding,
|
|
226
|
+
need_indices=self._need_indices,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
def compute_and_output_dist(
|
|
230
|
+
self, ctx: ShardedModuleContext, input: ListOfSparseFeaturesList
|
|
231
|
+
) -> LazyAwaitable[Dict[str, JaggedTensor]]:
|
|
232
|
+
return self.output_dist(ctx, self.compute(ctx, input))
|
|
233
|
+
|
|
234
|
+
# pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently.
|
|
235
|
+
def state_dict(
|
|
236
|
+
self,
|
|
237
|
+
destination: Optional[Dict[str, Any]] = None,
|
|
238
|
+
prefix: str = "",
|
|
239
|
+
keep_vars: bool = False,
|
|
240
|
+
) -> Dict[str, Any]:
|
|
241
|
+
if destination is None:
|
|
242
|
+
destination = OrderedDict()
|
|
243
|
+
# pyre-ignore [16]
|
|
244
|
+
destination._metadata = OrderedDict()
|
|
245
|
+
for lookup in self._lookups:
|
|
246
|
+
lookup.state_dict(destination, prefix + "embeddings.", keep_vars)
|
|
247
|
+
return destination
|
|
248
|
+
|
|
249
|
+
# pyre-fixme[14]: `load_state_dict` overrides method defined in `Module`
|
|
250
|
+
# inconsistently.
|
|
251
|
+
def load_state_dict(
|
|
252
|
+
self,
|
|
253
|
+
state_dict: "OrderedDict[str, torch.Tensor]",
|
|
254
|
+
strict: bool = True,
|
|
255
|
+
) -> _IncompatibleKeys:
|
|
256
|
+
missing_keys = []
|
|
257
|
+
unexpected_keys = []
|
|
258
|
+
for lookup in self._lookups:
|
|
259
|
+
missing, unexpected = lookup.load_state_dict(
|
|
260
|
+
filter_state_dict(state_dict, "embeddings"),
|
|
261
|
+
strict,
|
|
262
|
+
)
|
|
263
|
+
missing_keys.extend(missing)
|
|
264
|
+
unexpected_keys.extend(unexpected)
|
|
265
|
+
return _IncompatibleKeys(
|
|
266
|
+
missing_keys=missing_keys, unexpected_keys=unexpected_keys
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
def copy(self, device: torch.device) -> nn.Module:
|
|
270
|
+
return self
|
|
271
|
+
|
|
272
|
+
def create_context(self) -> ShardedModuleContext:
|
|
273
|
+
return EmbeddingCollectionContext(sharding_contexts=[])
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class QuantEmbeddingCollectionSharder(
|
|
277
|
+
BaseQuantEmbeddingSharder[QuantEmbeddingCollection]
|
|
278
|
+
):
|
|
279
|
+
"""
|
|
280
|
+
This implementation uses non-fused EmbeddingCollection
|
|
281
|
+
"""
|
|
282
|
+
|
|
283
|
+
def shard(
|
|
284
|
+
self,
|
|
285
|
+
module: QuantEmbeddingCollection,
|
|
286
|
+
params: Dict[str, ParameterSharding],
|
|
287
|
+
env: ShardingEnv,
|
|
288
|
+
device: Optional[torch.device] = None,
|
|
289
|
+
) -> ShardedQuantEmbeddingCollection:
|
|
290
|
+
fused_params = self.fused_params if self.fused_params else {}
|
|
291
|
+
fused_params["output_dtype"] = data_type_to_sparse_type(
|
|
292
|
+
dtype_to_data_type(module.output_dtype)
|
|
293
|
+
)
|
|
294
|
+
return ShardedQuantEmbeddingCollection(module, params, env, fused_params)
|
|
295
|
+
|
|
296
|
+
def shardable_parameters(
|
|
297
|
+
self, module: QuantEmbeddingCollection
|
|
298
|
+
) -> Dict[str, nn.Parameter]:
|
|
299
|
+
return {
|
|
300
|
+
name.split(".")[-2]: param
|
|
301
|
+
for name, param in module.state_dict().items()
|
|
302
|
+
if name.endswith(".weight")
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
@property
|
|
306
|
+
def module_type(self) -> Type[QuantEmbeddingCollection]:
|
|
307
|
+
return QuantEmbeddingCollection
|
|
@@ -0,0 +1,295 @@
|
|
|
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 copy
|
|
9
|
+
import logging
|
|
10
|
+
from typing import Any, Dict, Iterator, List, Optional, Tuple
|
|
11
|
+
|
|
12
|
+
import torch
|
|
13
|
+
import torch.distributed as dist
|
|
14
|
+
from fbgemm_gpu.split_embedding_configs import SparseType
|
|
15
|
+
from fbgemm_gpu.split_table_batched_embeddings_ops import (
|
|
16
|
+
EmbeddingLocation,
|
|
17
|
+
IntNBitTableBatchedEmbeddingBagsCodegen,
|
|
18
|
+
PoolingMode,
|
|
19
|
+
rounded_row_size_in_bytes,
|
|
20
|
+
)
|
|
21
|
+
from torchrec.distributed.batched_embedding_kernel import (
|
|
22
|
+
BaseBatchedEmbedding,
|
|
23
|
+
BaseBatchedEmbeddingBag,
|
|
24
|
+
)
|
|
25
|
+
from torchrec.distributed.embedding_kernel import BaseEmbedding
|
|
26
|
+
from torchrec.distributed.embedding_types import (
|
|
27
|
+
compute_kernel_to_embedding_location,
|
|
28
|
+
GroupedEmbeddingConfig,
|
|
29
|
+
)
|
|
30
|
+
from torchrec.distributed.utils import append_prefix
|
|
31
|
+
from torchrec.modules.embedding_configs import (
|
|
32
|
+
DATA_TYPE_NUM_BITS,
|
|
33
|
+
data_type_to_sparse_type,
|
|
34
|
+
DataType,
|
|
35
|
+
dtype_to_data_type,
|
|
36
|
+
)
|
|
37
|
+
from torchrec.sparse.jagged_tensor import KeyedJaggedTensor
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
logger: logging.Logger = logging.getLogger(__name__)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _copy_config(
|
|
44
|
+
original: GroupedEmbeddingConfig,
|
|
45
|
+
data_type: DataType,
|
|
46
|
+
sparse_type: SparseType,
|
|
47
|
+
device: torch.device,
|
|
48
|
+
) -> GroupedEmbeddingConfig:
|
|
49
|
+
# Adjust config to quantized version.
|
|
50
|
+
# This obviously doesn't work for column-wise sharding.
|
|
51
|
+
config = copy.deepcopy(original)
|
|
52
|
+
config.data_type = data_type
|
|
53
|
+
for table in config.embedding_tables:
|
|
54
|
+
row_alignment = 16 if device.type == "cuda" else 1
|
|
55
|
+
table.local_cols = rounded_row_size_in_bytes(
|
|
56
|
+
table.local_cols, sparse_type, row_alignment
|
|
57
|
+
)
|
|
58
|
+
if table.local_metadata is not None:
|
|
59
|
+
table.local_metadata.shard_sizes = [
|
|
60
|
+
table.local_rows,
|
|
61
|
+
table.local_cols,
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
global_metadata = table.global_metadata
|
|
65
|
+
if global_metadata is not None:
|
|
66
|
+
for shard_meta in global_metadata.shards_metadata:
|
|
67
|
+
if shard_meta != table.local_metadata:
|
|
68
|
+
shard_meta.shard_sizes = [
|
|
69
|
+
shard_meta.shard_sizes[0],
|
|
70
|
+
rounded_row_size_in_bytes(
|
|
71
|
+
shard_meta.shard_sizes[1], sparse_type, row_alignment
|
|
72
|
+
),
|
|
73
|
+
]
|
|
74
|
+
global_metadata.size = torch.Size(
|
|
75
|
+
[
|
|
76
|
+
global_metadata.size[0],
|
|
77
|
+
sum(
|
|
78
|
+
shard_meta.shard_sizes[1]
|
|
79
|
+
for shard_meta in global_metadata.shards_metadata
|
|
80
|
+
),
|
|
81
|
+
]
|
|
82
|
+
)
|
|
83
|
+
return config
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _quantize_weight(
|
|
87
|
+
state_dict: Dict[str, torch.Tensor], data_type: DataType
|
|
88
|
+
) -> List[Tuple[torch.Tensor, Optional[torch.Tensor]]]:
|
|
89
|
+
quant_weight_list = []
|
|
90
|
+
for weight in state_dict.values():
|
|
91
|
+
if weight.dtype == torch.float or weight.dtype == torch.float16:
|
|
92
|
+
quantized_weights = (
|
|
93
|
+
torch.ops.fbgemm.FloatOrHalfToFusedNBitRowwiseQuantizedSBHalf(
|
|
94
|
+
weight, DATA_TYPE_NUM_BITS[data_type]
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
else:
|
|
98
|
+
raise Exception("Unsupported dtype: {weight.dtype}")
|
|
99
|
+
|
|
100
|
+
# weight and 4 byte scale shift (2xfp16)
|
|
101
|
+
quant_weight = quantized_weights[:, :-4]
|
|
102
|
+
scale_shift = quantized_weights[:, -4:]
|
|
103
|
+
|
|
104
|
+
quant_weight_list.append((quant_weight, scale_shift))
|
|
105
|
+
return quant_weight_list
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class QuantBatchedEmbeddingBag(BaseBatchedEmbeddingBag):
|
|
109
|
+
def __init__(
|
|
110
|
+
self,
|
|
111
|
+
config: GroupedEmbeddingConfig,
|
|
112
|
+
pg: Optional[dist.ProcessGroup] = None,
|
|
113
|
+
device: Optional[torch.device] = None,
|
|
114
|
+
fused_params: Optional[Dict[str, Any]] = None,
|
|
115
|
+
) -> None:
|
|
116
|
+
super().__init__(config, pg, device)
|
|
117
|
+
|
|
118
|
+
managed: List[EmbeddingLocation] = []
|
|
119
|
+
for table in config.embedding_tables:
|
|
120
|
+
if device is not None and device.type == "cuda":
|
|
121
|
+
managed.append(
|
|
122
|
+
compute_kernel_to_embedding_location(table.compute_kernel)
|
|
123
|
+
)
|
|
124
|
+
else:
|
|
125
|
+
managed.append(EmbeddingLocation.HOST)
|
|
126
|
+
self._emb_module: IntNBitTableBatchedEmbeddingBagsCodegen = (
|
|
127
|
+
IntNBitTableBatchedEmbeddingBagsCodegen(
|
|
128
|
+
embedding_specs=[
|
|
129
|
+
(
|
|
130
|
+
"",
|
|
131
|
+
local_rows,
|
|
132
|
+
table.embedding_dim,
|
|
133
|
+
data_type_to_sparse_type(config.data_type),
|
|
134
|
+
location,
|
|
135
|
+
)
|
|
136
|
+
for local_rows, table, location in zip(
|
|
137
|
+
self._local_rows, config.embedding_tables, managed
|
|
138
|
+
)
|
|
139
|
+
],
|
|
140
|
+
device=device,
|
|
141
|
+
pooling_mode=self._pooling,
|
|
142
|
+
feature_table_map=self._feature_table_map,
|
|
143
|
+
row_alignment=16,
|
|
144
|
+
**(fused_params or {}),
|
|
145
|
+
)
|
|
146
|
+
)
|
|
147
|
+
if device is not None and device.type != "meta":
|
|
148
|
+
self._emb_module.initialize_weights()
|
|
149
|
+
|
|
150
|
+
def init_parameters(self) -> None:
|
|
151
|
+
pass
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def emb_module(
|
|
155
|
+
self,
|
|
156
|
+
) -> IntNBitTableBatchedEmbeddingBagsCodegen:
|
|
157
|
+
return self._emb_module
|
|
158
|
+
|
|
159
|
+
def forward(self, features: KeyedJaggedTensor) -> torch.Tensor:
|
|
160
|
+
return self.emb_module(
|
|
161
|
+
indices=features.values().int(),
|
|
162
|
+
offsets=features.offsets().int(),
|
|
163
|
+
per_sample_weights=features.weights_or_none(),
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
def named_buffers(
|
|
167
|
+
self, prefix: str = "", recurse: bool = True
|
|
168
|
+
) -> Iterator[Tuple[str, torch.Tensor]]:
|
|
169
|
+
for config, weight in zip(
|
|
170
|
+
self._config.embedding_tables,
|
|
171
|
+
self.emb_module.split_embedding_weights(),
|
|
172
|
+
):
|
|
173
|
+
yield append_prefix(prefix, f"{config.name}.weight"), weight[0]
|
|
174
|
+
|
|
175
|
+
def split_embedding_weights(self) -> List[torch.Tensor]:
|
|
176
|
+
return [
|
|
177
|
+
weight
|
|
178
|
+
for weight, _ in self.emb_module.split_embedding_weights(
|
|
179
|
+
split_scale_shifts=False
|
|
180
|
+
)
|
|
181
|
+
]
|
|
182
|
+
|
|
183
|
+
@classmethod
|
|
184
|
+
def from_float(cls, module: BaseEmbedding) -> "QuantBatchedEmbeddingBag":
|
|
185
|
+
assert hasattr(
|
|
186
|
+
module, "qconfig"
|
|
187
|
+
), "BaseEmbedding input float module must have qconfig defined"
|
|
188
|
+
|
|
189
|
+
# pyre-ignore [16]
|
|
190
|
+
data_type = dtype_to_data_type(module.qconfig.weight().dtype)
|
|
191
|
+
sparse_type = data_type_to_sparse_type(data_type)
|
|
192
|
+
|
|
193
|
+
state_dict = dict(module.named_buffers())
|
|
194
|
+
device = next(iter(state_dict.values())).device
|
|
195
|
+
|
|
196
|
+
config = _copy_config(module.config, data_type, sparse_type, device)
|
|
197
|
+
ret = QuantBatchedEmbeddingBag(config=config, device=device)
|
|
198
|
+
|
|
199
|
+
quant_weight_list = _quantize_weight(state_dict, data_type)
|
|
200
|
+
ret.emb_module.assign_embedding_weights(quant_weight_list)
|
|
201
|
+
|
|
202
|
+
return ret
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class QuantBatchedEmbedding(BaseBatchedEmbedding):
|
|
206
|
+
def __init__(
|
|
207
|
+
self,
|
|
208
|
+
config: GroupedEmbeddingConfig,
|
|
209
|
+
pg: Optional[dist.ProcessGroup] = None,
|
|
210
|
+
device: Optional[torch.device] = None,
|
|
211
|
+
fused_params: Optional[Dict[str, Any]] = None,
|
|
212
|
+
) -> None:
|
|
213
|
+
super().__init__(config, pg, device)
|
|
214
|
+
|
|
215
|
+
managed: List[EmbeddingLocation] = []
|
|
216
|
+
for table in config.embedding_tables:
|
|
217
|
+
if device is not None and device.type == "cuda":
|
|
218
|
+
managed.append(
|
|
219
|
+
compute_kernel_to_embedding_location(table.compute_kernel)
|
|
220
|
+
)
|
|
221
|
+
else:
|
|
222
|
+
managed.append(EmbeddingLocation.HOST)
|
|
223
|
+
self._emb_module: IntNBitTableBatchedEmbeddingBagsCodegen = (
|
|
224
|
+
IntNBitTableBatchedEmbeddingBagsCodegen(
|
|
225
|
+
embedding_specs=[
|
|
226
|
+
(
|
|
227
|
+
"",
|
|
228
|
+
local_rows,
|
|
229
|
+
table.embedding_dim,
|
|
230
|
+
data_type_to_sparse_type(config.data_type),
|
|
231
|
+
location,
|
|
232
|
+
)
|
|
233
|
+
for local_rows, table, location in zip(
|
|
234
|
+
self._local_rows, config.embedding_tables, managed
|
|
235
|
+
)
|
|
236
|
+
],
|
|
237
|
+
device=device,
|
|
238
|
+
pooling_mode=PoolingMode.NONE,
|
|
239
|
+
feature_table_map=self._feature_table_map,
|
|
240
|
+
row_alignment=16,
|
|
241
|
+
**(fused_params or {}),
|
|
242
|
+
)
|
|
243
|
+
)
|
|
244
|
+
if device is not None and device.type != "meta":
|
|
245
|
+
self._emb_module.initialize_weights()
|
|
246
|
+
|
|
247
|
+
@property
|
|
248
|
+
def emb_module(
|
|
249
|
+
self,
|
|
250
|
+
) -> IntNBitTableBatchedEmbeddingBagsCodegen:
|
|
251
|
+
return self._emb_module
|
|
252
|
+
|
|
253
|
+
def split_embedding_weights(self) -> List[torch.Tensor]:
|
|
254
|
+
return [
|
|
255
|
+
weight
|
|
256
|
+
for weight, _ in self.emb_module.split_embedding_weights(
|
|
257
|
+
split_scale_shifts=False
|
|
258
|
+
)
|
|
259
|
+
]
|
|
260
|
+
|
|
261
|
+
def forward(self, features: KeyedJaggedTensor) -> torch.Tensor:
|
|
262
|
+
return self.emb_module(
|
|
263
|
+
indices=features.values().int(),
|
|
264
|
+
offsets=features.offsets().int(),
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
def named_buffers(
|
|
268
|
+
self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
|
|
269
|
+
) -> Iterator[Tuple[str, torch.Tensor]]:
|
|
270
|
+
for config, weight in zip(
|
|
271
|
+
self._config.embedding_tables,
|
|
272
|
+
self.emb_module.split_embedding_weights(),
|
|
273
|
+
):
|
|
274
|
+
yield append_prefix(prefix, f"{config.name}.weight"), weight[0]
|
|
275
|
+
|
|
276
|
+
@classmethod
|
|
277
|
+
def from_float(cls, module: BaseEmbedding) -> "QuantBatchedEmbedding":
|
|
278
|
+
assert hasattr(
|
|
279
|
+
module, "qconfig"
|
|
280
|
+
), "BaseEmbedding input float module must have qconfig defined"
|
|
281
|
+
|
|
282
|
+
# pyre-ignore [16]
|
|
283
|
+
data_type = dtype_to_data_type(module.qconfig.weight().dtype)
|
|
284
|
+
sparse_type = data_type_to_sparse_type(data_type)
|
|
285
|
+
|
|
286
|
+
state_dict = dict(module.named_buffers())
|
|
287
|
+
device = next(iter(state_dict.values())).device
|
|
288
|
+
|
|
289
|
+
config = _copy_config(module.config, data_type, sparse_type, device)
|
|
290
|
+
ret = QuantBatchedEmbedding(config=config, device=device)
|
|
291
|
+
|
|
292
|
+
quant_weight_list = _quantize_weight(state_dict, data_type)
|
|
293
|
+
ret.emb_module.assign_embedding_weights(quant_weight_list)
|
|
294
|
+
|
|
295
|
+
return ret
|