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,638 @@
|
|
|
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
|
+
import copy
|
|
10
|
+
from collections import defaultdict, deque, OrderedDict
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import (
|
|
13
|
+
Any,
|
|
14
|
+
cast,
|
|
15
|
+
Dict,
|
|
16
|
+
Iterator,
|
|
17
|
+
List,
|
|
18
|
+
MutableMapping,
|
|
19
|
+
Optional,
|
|
20
|
+
Set,
|
|
21
|
+
Tuple,
|
|
22
|
+
Type,
|
|
23
|
+
Union,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
import torch
|
|
27
|
+
from torch import nn
|
|
28
|
+
from torch.nn.modules.module import _IncompatibleKeys
|
|
29
|
+
from torchrec.distributed.embedding_sharding import (
|
|
30
|
+
EmbeddingSharding,
|
|
31
|
+
EmbeddingShardingInfo,
|
|
32
|
+
SparseFeaturesIndicesAwaitable,
|
|
33
|
+
SparseFeaturesListAwaitable,
|
|
34
|
+
)
|
|
35
|
+
from torchrec.distributed.embedding_types import (
|
|
36
|
+
BaseEmbeddingSharder,
|
|
37
|
+
EmbeddingComputeKernel,
|
|
38
|
+
ShardingType,
|
|
39
|
+
SparseFeatures,
|
|
40
|
+
SparseFeaturesList,
|
|
41
|
+
)
|
|
42
|
+
from torchrec.distributed.sharding.cw_sequence_sharding import (
|
|
43
|
+
CwSequenceEmbeddingSharding,
|
|
44
|
+
)
|
|
45
|
+
from torchrec.distributed.sharding.dp_sequence_sharding import (
|
|
46
|
+
DpSequenceEmbeddingSharding,
|
|
47
|
+
)
|
|
48
|
+
from torchrec.distributed.sharding.rw_sequence_sharding import (
|
|
49
|
+
RwSequenceEmbeddingSharding,
|
|
50
|
+
)
|
|
51
|
+
from torchrec.distributed.sharding.rw_sharding import RwSparseFeaturesDist
|
|
52
|
+
from torchrec.distributed.sharding.sequence_sharding import SequenceShardingContext
|
|
53
|
+
from torchrec.distributed.sharding.tw_sequence_sharding import (
|
|
54
|
+
TwSequenceEmbeddingSharding,
|
|
55
|
+
)
|
|
56
|
+
from torchrec.distributed.types import (
|
|
57
|
+
Awaitable,
|
|
58
|
+
LazyAwaitable,
|
|
59
|
+
ParameterSharding,
|
|
60
|
+
ShardedModule,
|
|
61
|
+
ShardedModuleContext,
|
|
62
|
+
ShardedTensor,
|
|
63
|
+
ShardingEnv,
|
|
64
|
+
ShardMetadata,
|
|
65
|
+
)
|
|
66
|
+
from torchrec.distributed.utils import append_prefix, filter_state_dict
|
|
67
|
+
from torchrec.modules.embedding_configs import (
|
|
68
|
+
EmbeddingConfig,
|
|
69
|
+
EmbeddingTableConfig,
|
|
70
|
+
PoolingType,
|
|
71
|
+
)
|
|
72
|
+
from torchrec.modules.embedding_modules import (
|
|
73
|
+
EmbeddingCollection,
|
|
74
|
+
EmbeddingCollectionInterface,
|
|
75
|
+
)
|
|
76
|
+
from torchrec.optim.fused import FusedOptimizerModule
|
|
77
|
+
from torchrec.optim.keyed import CombinedOptimizer, KeyedOptimizer
|
|
78
|
+
from torchrec.sparse.jagged_tensor import JaggedTensor, KeyedJaggedTensor
|
|
79
|
+
|
|
80
|
+
try:
|
|
81
|
+
torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops")
|
|
82
|
+
torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops_cpu")
|
|
83
|
+
except OSError:
|
|
84
|
+
pass
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def create_embedding_sharding(
|
|
88
|
+
sharding_type: str,
|
|
89
|
+
sharding_infos: List[EmbeddingShardingInfo],
|
|
90
|
+
env: ShardingEnv,
|
|
91
|
+
device: Optional[torch.device] = None,
|
|
92
|
+
) -> EmbeddingSharding[SparseFeatures, torch.Tensor]:
|
|
93
|
+
if sharding_type == ShardingType.TABLE_WISE.value:
|
|
94
|
+
return TwSequenceEmbeddingSharding(sharding_infos, env, device)
|
|
95
|
+
elif sharding_type == ShardingType.ROW_WISE.value:
|
|
96
|
+
return RwSequenceEmbeddingSharding(sharding_infos, env, device)
|
|
97
|
+
elif sharding_type == ShardingType.DATA_PARALLEL.value:
|
|
98
|
+
return DpSequenceEmbeddingSharding(sharding_infos, env, device)
|
|
99
|
+
elif sharding_type == ShardingType.COLUMN_WISE.value:
|
|
100
|
+
return CwSequenceEmbeddingSharding(sharding_infos, env, device)
|
|
101
|
+
else:
|
|
102
|
+
raise ValueError(f"Sharding not supported {sharding_type}")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def create_sharding_infos_by_sharding(
|
|
106
|
+
module: EmbeddingCollectionInterface,
|
|
107
|
+
table_name_to_parameter_sharding: Dict[str, ParameterSharding],
|
|
108
|
+
) -> Dict[str, List[EmbeddingShardingInfo]]:
|
|
109
|
+
sharding_type_to_sharding_infos: Dict[str, List[EmbeddingShardingInfo]] = {}
|
|
110
|
+
state_dict = module.state_dict()
|
|
111
|
+
for (
|
|
112
|
+
config,
|
|
113
|
+
embedding_names,
|
|
114
|
+
) in zip(module.embedding_configs, module.embedding_names_by_table):
|
|
115
|
+
table_name = config.name
|
|
116
|
+
assert table_name in table_name_to_parameter_sharding
|
|
117
|
+
|
|
118
|
+
parameter_sharding = table_name_to_parameter_sharding[table_name]
|
|
119
|
+
if parameter_sharding.compute_kernel not in [
|
|
120
|
+
kernel.value for kernel in EmbeddingComputeKernel
|
|
121
|
+
]:
|
|
122
|
+
raise ValueError(
|
|
123
|
+
f"Compute kernel not supported {parameter_sharding.compute_kernel}"
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
param_name = "embeddings." + config.name + ".weight"
|
|
127
|
+
assert param_name in state_dict
|
|
128
|
+
param = state_dict[param_name]
|
|
129
|
+
|
|
130
|
+
if parameter_sharding.sharding_type not in sharding_type_to_sharding_infos:
|
|
131
|
+
sharding_type_to_sharding_infos[parameter_sharding.sharding_type] = []
|
|
132
|
+
sharding_type_to_sharding_infos[parameter_sharding.sharding_type].append(
|
|
133
|
+
(
|
|
134
|
+
EmbeddingShardingInfo(
|
|
135
|
+
embedding_config=EmbeddingTableConfig(
|
|
136
|
+
num_embeddings=config.num_embeddings,
|
|
137
|
+
embedding_dim=config.embedding_dim,
|
|
138
|
+
name=config.name,
|
|
139
|
+
data_type=config.data_type,
|
|
140
|
+
feature_names=copy.deepcopy(config.feature_names),
|
|
141
|
+
pooling=PoolingType.NONE,
|
|
142
|
+
is_weighted=False,
|
|
143
|
+
has_feature_processor=False,
|
|
144
|
+
embedding_names=embedding_names,
|
|
145
|
+
weight_init_max=config.weight_init_max,
|
|
146
|
+
weight_init_min=config.weight_init_min,
|
|
147
|
+
),
|
|
148
|
+
param_sharding=parameter_sharding,
|
|
149
|
+
param=param,
|
|
150
|
+
)
|
|
151
|
+
)
|
|
152
|
+
)
|
|
153
|
+
return sharding_type_to_sharding_infos
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _construct_jagged_tensors(
|
|
157
|
+
embeddings: torch.Tensor,
|
|
158
|
+
features: KeyedJaggedTensor,
|
|
159
|
+
need_indices: bool = False,
|
|
160
|
+
features_to_permute_indices: Optional[Dict[str, List[int]]] = None,
|
|
161
|
+
) -> Dict[str, JaggedTensor]:
|
|
162
|
+
ret: Dict[str, JaggedTensor] = {}
|
|
163
|
+
stride = features.stride()
|
|
164
|
+
length_per_key = features.length_per_key()
|
|
165
|
+
values = features.values()
|
|
166
|
+
|
|
167
|
+
lengths = features.lengths().view(-1, stride)
|
|
168
|
+
lengths_tuple = torch.unbind(lengths.view(-1, stride), dim=0)
|
|
169
|
+
embeddings_list = torch.split(embeddings, length_per_key, dim=0)
|
|
170
|
+
values_list = torch.split(values, length_per_key) if need_indices else None
|
|
171
|
+
|
|
172
|
+
key_indices = defaultdict(list)
|
|
173
|
+
for i, key in enumerate(features.keys()):
|
|
174
|
+
key_indices[key].append(i)
|
|
175
|
+
for key, indices in key_indices.items():
|
|
176
|
+
# combines outputs in correct order for CW sharding
|
|
177
|
+
indices = (
|
|
178
|
+
_permute_indices(indices, features_to_permute_indices[key])
|
|
179
|
+
if features_to_permute_indices and key in features_to_permute_indices
|
|
180
|
+
else indices
|
|
181
|
+
)
|
|
182
|
+
ret[key] = JaggedTensor(
|
|
183
|
+
lengths=lengths_tuple[indices[0]],
|
|
184
|
+
values=embeddings_list[indices[0]]
|
|
185
|
+
if len(indices) == 1
|
|
186
|
+
else torch.cat([embeddings_list[i] for i in indices], dim=1),
|
|
187
|
+
weights=values_list[indices[0]] if values_list else None,
|
|
188
|
+
)
|
|
189
|
+
return ret
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _permute_indices(indices: List[int], permute: List[int]) -> List[int]:
|
|
193
|
+
permuted_indices = [0] * len(indices)
|
|
194
|
+
for i, permuted_index in enumerate(permute):
|
|
195
|
+
permuted_indices[i] = indices[permuted_index]
|
|
196
|
+
return permuted_indices
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@dataclass
|
|
200
|
+
class EmbeddingCollectionContext(ShardedModuleContext):
|
|
201
|
+
sharding_contexts: List[SequenceShardingContext]
|
|
202
|
+
|
|
203
|
+
def record_stream(self, stream: torch.cuda.streams.Stream) -> None:
|
|
204
|
+
for ctx in self.sharding_contexts:
|
|
205
|
+
ctx.record_stream(stream)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class EmbeddingCollectionAwaitable(LazyAwaitable[Dict[str, JaggedTensor]]):
|
|
209
|
+
def __init__(
|
|
210
|
+
self,
|
|
211
|
+
awaitables_per_sharding: List[Awaitable[torch.Tensor]],
|
|
212
|
+
features_per_sharding: List[KeyedJaggedTensor],
|
|
213
|
+
need_indices: bool = False,
|
|
214
|
+
features_to_permute_indices: Optional[Dict[str, List[int]]] = None,
|
|
215
|
+
) -> None:
|
|
216
|
+
super().__init__()
|
|
217
|
+
self._awaitables_per_sharding = awaitables_per_sharding
|
|
218
|
+
self._features_per_sharding = features_per_sharding
|
|
219
|
+
self._need_indices = need_indices
|
|
220
|
+
self._features_to_permute_indices = features_to_permute_indices
|
|
221
|
+
|
|
222
|
+
def _wait_impl(self) -> Dict[str, JaggedTensor]:
|
|
223
|
+
jt_dict: Dict[str, JaggedTensor] = {}
|
|
224
|
+
for w, f in zip(
|
|
225
|
+
self._awaitables_per_sharding,
|
|
226
|
+
self._features_per_sharding,
|
|
227
|
+
):
|
|
228
|
+
jt_dict.update(
|
|
229
|
+
_construct_jagged_tensors(
|
|
230
|
+
embeddings=w.wait(),
|
|
231
|
+
features=f,
|
|
232
|
+
need_indices=self._need_indices,
|
|
233
|
+
features_to_permute_indices=self._features_to_permute_indices,
|
|
234
|
+
)
|
|
235
|
+
)
|
|
236
|
+
return jt_dict
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class ShardedEmbeddingCollection(
|
|
240
|
+
ShardedModule[
|
|
241
|
+
SparseFeaturesList,
|
|
242
|
+
List[torch.Tensor],
|
|
243
|
+
Dict[str, JaggedTensor],
|
|
244
|
+
],
|
|
245
|
+
FusedOptimizerModule,
|
|
246
|
+
):
|
|
247
|
+
"""
|
|
248
|
+
Sharded implementation of `EmbeddingCollection`.
|
|
249
|
+
This is part of the public API to allow for manual data dist pipelining.
|
|
250
|
+
"""
|
|
251
|
+
|
|
252
|
+
def __init__(
|
|
253
|
+
self,
|
|
254
|
+
module: EmbeddingCollection,
|
|
255
|
+
table_name_to_parameter_sharding: Dict[str, ParameterSharding],
|
|
256
|
+
env: ShardingEnv,
|
|
257
|
+
fused_params: Optional[Dict[str, Any]] = None,
|
|
258
|
+
device: Optional[torch.device] = None,
|
|
259
|
+
) -> None:
|
|
260
|
+
super().__init__()
|
|
261
|
+
sharding_type_to_sharding_infos = create_sharding_infos_by_sharding(
|
|
262
|
+
module, table_name_to_parameter_sharding
|
|
263
|
+
)
|
|
264
|
+
self._sharding_type_to_sharding: Dict[
|
|
265
|
+
str, EmbeddingSharding[SparseFeatures, torch.Tensor]
|
|
266
|
+
] = {
|
|
267
|
+
sharding_type: create_embedding_sharding(
|
|
268
|
+
sharding_type, embedding_confings, env, device
|
|
269
|
+
)
|
|
270
|
+
for sharding_type, embedding_confings in sharding_type_to_sharding_infos.items()
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
self._device = device
|
|
274
|
+
self._input_dists: nn.ModuleList = nn.ModuleList()
|
|
275
|
+
self._lookups: nn.ModuleList = nn.ModuleList()
|
|
276
|
+
self._create_lookups(fused_params)
|
|
277
|
+
self._output_dists: nn.ModuleList = nn.ModuleList()
|
|
278
|
+
self._create_output_dist()
|
|
279
|
+
|
|
280
|
+
self._feature_splits: List[int] = []
|
|
281
|
+
self._features_order: List[int] = []
|
|
282
|
+
|
|
283
|
+
self._has_uninitialized_input_dist: bool = True
|
|
284
|
+
|
|
285
|
+
# Get all fused optimizers and combine them.
|
|
286
|
+
optims = []
|
|
287
|
+
for lookup in self._lookups:
|
|
288
|
+
for _, m in lookup.named_modules():
|
|
289
|
+
if isinstance(m, FusedOptimizerModule):
|
|
290
|
+
# modify param keys to match EmbeddingCollection
|
|
291
|
+
params: MutableMapping[str, Union[torch.Tensor, ShardedTensor]] = {}
|
|
292
|
+
for param_key, weight in m.fused_optimizer.params.items():
|
|
293
|
+
params["embeddings." + param_key] = weight
|
|
294
|
+
m.fused_optimizer.params = params
|
|
295
|
+
optims.append(("", m.fused_optimizer))
|
|
296
|
+
self._optim: CombinedOptimizer = CombinedOptimizer(optims)
|
|
297
|
+
self._embedding_dim: int = module.embedding_dim
|
|
298
|
+
self._local_embedding_dim: int = self._embedding_dim
|
|
299
|
+
self._features_to_permute_indices: Dict[str, List[int]] = {}
|
|
300
|
+
if ShardingType.COLUMN_WISE.value in self._sharding_type_to_sharding:
|
|
301
|
+
sharding = self._sharding_type_to_sharding[ShardingType.COLUMN_WISE.value]
|
|
302
|
+
# CW partition must be same for all CW sharded parameters
|
|
303
|
+
self._local_embedding_dim = cast(
|
|
304
|
+
ShardMetadata, sharding.embedding_shard_metadata()[0]
|
|
305
|
+
).shard_sizes[1]
|
|
306
|
+
self._generate_permute_indices_per_feature(
|
|
307
|
+
module.embedding_configs, table_name_to_parameter_sharding
|
|
308
|
+
)
|
|
309
|
+
self._need_indices: bool = module.need_indices
|
|
310
|
+
|
|
311
|
+
def _generate_permute_indices_per_feature(
|
|
312
|
+
self,
|
|
313
|
+
embedding_configs: List[EmbeddingConfig],
|
|
314
|
+
table_name_to_parameter_sharding: Dict[str, ParameterSharding],
|
|
315
|
+
) -> None:
|
|
316
|
+
"""
|
|
317
|
+
Generates permute indices per feature for column-wise sharding.
|
|
318
|
+
|
|
319
|
+
Since outputs are stored in order of rank, column-wise shards of a table on the
|
|
320
|
+
same rank will be seen as adjacent, which may not be correct.
|
|
321
|
+
|
|
322
|
+
The permute indices store the correct ordering of outputs relative to the
|
|
323
|
+
provided ordering.
|
|
324
|
+
|
|
325
|
+
Example::
|
|
326
|
+
rank_0 = [f_0(shard_0), f_0(shard_2)]
|
|
327
|
+
rank_1 = [f_0(shard_1)]
|
|
328
|
+
output = [f_0(shard_0), f_0(shard_2), f_0(shard_1)]
|
|
329
|
+
|
|
330
|
+
shard_ranks = [0, 1, 0]
|
|
331
|
+
output_ranks = [0, 0, 1]
|
|
332
|
+
|
|
333
|
+
# To get the correct order from output_ranks -> shard_ranks
|
|
334
|
+
permute_indices = [0, 2, 1]
|
|
335
|
+
"""
|
|
336
|
+
for table in embedding_configs:
|
|
337
|
+
sharding = table_name_to_parameter_sharding[table.name]
|
|
338
|
+
if sharding.sharding_type != ShardingType.COLUMN_WISE.value:
|
|
339
|
+
continue
|
|
340
|
+
ranks = cast(List[int], sharding.ranks)
|
|
341
|
+
rank_to_indices = defaultdict(deque)
|
|
342
|
+
for i, rank in enumerate(sorted(ranks)):
|
|
343
|
+
rank_to_indices[rank].append(i)
|
|
344
|
+
permute_indices = [rank_to_indices[rank].popleft() for rank in ranks]
|
|
345
|
+
for feature_name in table.feature_names:
|
|
346
|
+
self._features_to_permute_indices[feature_name] = permute_indices
|
|
347
|
+
|
|
348
|
+
def _create_input_dist(
|
|
349
|
+
self,
|
|
350
|
+
input_feature_names: List[str],
|
|
351
|
+
) -> None:
|
|
352
|
+
feature_names: List[str] = []
|
|
353
|
+
self._feature_splits: List[int] = []
|
|
354
|
+
for sharding in self._sharding_type_to_sharding.values():
|
|
355
|
+
self._input_dists.append(sharding.create_input_dist())
|
|
356
|
+
feature_names.extend(sharding.id_list_feature_names())
|
|
357
|
+
self._feature_splits.append(len(sharding.id_list_feature_names()))
|
|
358
|
+
self._features_order: List[int] = []
|
|
359
|
+
for f in feature_names:
|
|
360
|
+
self._features_order.append(input_feature_names.index(f))
|
|
361
|
+
self._features_order = (
|
|
362
|
+
[]
|
|
363
|
+
if self._features_order == list(range(len(self._features_order)))
|
|
364
|
+
else self._features_order
|
|
365
|
+
)
|
|
366
|
+
self.register_buffer(
|
|
367
|
+
"_features_order_tensor",
|
|
368
|
+
torch.tensor(self._features_order, device=self._device, dtype=torch.int32),
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
def _create_lookups(self, fused_params: Optional[Dict[str, Any]]) -> None:
|
|
372
|
+
for sharding in self._sharding_type_to_sharding.values():
|
|
373
|
+
self._lookups.append(sharding.create_lookup(fused_params=fused_params))
|
|
374
|
+
|
|
375
|
+
def _create_output_dist(
|
|
376
|
+
self,
|
|
377
|
+
) -> None:
|
|
378
|
+
for sharding in self._sharding_type_to_sharding.values():
|
|
379
|
+
self._output_dists.append(sharding.create_output_dist())
|
|
380
|
+
|
|
381
|
+
# pyre-ignore [14]
|
|
382
|
+
def input_dist(
|
|
383
|
+
self,
|
|
384
|
+
ctx: EmbeddingCollectionContext,
|
|
385
|
+
features: KeyedJaggedTensor,
|
|
386
|
+
) -> Awaitable[SparseFeaturesList]:
|
|
387
|
+
if self._has_uninitialized_input_dist:
|
|
388
|
+
self._create_input_dist(input_feature_names=features.keys())
|
|
389
|
+
self._has_uninitialized_input_dist = False
|
|
390
|
+
with torch.no_grad():
|
|
391
|
+
if self._features_order:
|
|
392
|
+
features = features.permute(
|
|
393
|
+
self._features_order,
|
|
394
|
+
# pyre-ignore [6]
|
|
395
|
+
self._features_order_tensor,
|
|
396
|
+
)
|
|
397
|
+
features_by_shards = features.split(
|
|
398
|
+
self._feature_splits,
|
|
399
|
+
)
|
|
400
|
+
# save input splits and output splits in sharding context which
|
|
401
|
+
# will be reused in sequence embedding all2all
|
|
402
|
+
awaitables = []
|
|
403
|
+
for module, features in zip(self._input_dists, features_by_shards):
|
|
404
|
+
tensor_awaitable = module(
|
|
405
|
+
SparseFeatures(
|
|
406
|
+
id_list_features=features,
|
|
407
|
+
id_score_list_features=None,
|
|
408
|
+
)
|
|
409
|
+
)
|
|
410
|
+
tensor_awaitable = tensor_awaitable.wait() # finish lengths all2all
|
|
411
|
+
input_splits = []
|
|
412
|
+
output_splits = []
|
|
413
|
+
if isinstance(tensor_awaitable, SparseFeaturesIndicesAwaitable):
|
|
414
|
+
input_splits = (
|
|
415
|
+
# pyre-fixme[16]: `Optional` has no attribute
|
|
416
|
+
# `_in_lengths_per_worker`.
|
|
417
|
+
tensor_awaitable._id_list_features_awaitable._in_lengths_per_worker
|
|
418
|
+
)
|
|
419
|
+
output_splits = (
|
|
420
|
+
# pyre-fixme[16]: `Optional` has no attribute
|
|
421
|
+
# `_out_lengths_per_worker`.
|
|
422
|
+
tensor_awaitable._id_list_features_awaitable._out_lengths_per_worker
|
|
423
|
+
)
|
|
424
|
+
ctx.sharding_contexts.append(
|
|
425
|
+
SequenceShardingContext(
|
|
426
|
+
features_before_input_dist=features,
|
|
427
|
+
input_splits=input_splits,
|
|
428
|
+
output_splits=output_splits,
|
|
429
|
+
unbucketize_permute_tensor=module.unbucketize_permute_tensor
|
|
430
|
+
if isinstance(module, RwSparseFeaturesDist)
|
|
431
|
+
else None,
|
|
432
|
+
)
|
|
433
|
+
)
|
|
434
|
+
awaitables.append(tensor_awaitable)
|
|
435
|
+
return SparseFeaturesListAwaitable(awaitables)
|
|
436
|
+
|
|
437
|
+
def compute(
|
|
438
|
+
self, ctx: ShardedModuleContext, dist_input: SparseFeaturesList
|
|
439
|
+
) -> List[torch.Tensor]:
|
|
440
|
+
ret: List[torch.Tensor] = []
|
|
441
|
+
for lookup, features, sharding_ctx, sharding_type in zip(
|
|
442
|
+
self._lookups,
|
|
443
|
+
dist_input,
|
|
444
|
+
cast(EmbeddingCollectionContext, ctx).sharding_contexts,
|
|
445
|
+
self._sharding_type_to_sharding,
|
|
446
|
+
):
|
|
447
|
+
sharding_ctx.lengths_after_input_dist = (
|
|
448
|
+
features.id_list_features.lengths().view(
|
|
449
|
+
-1, features.id_list_features.stride()
|
|
450
|
+
)
|
|
451
|
+
)
|
|
452
|
+
embedding_dim = self._embedding_dim_for_sharding_type(sharding_type)
|
|
453
|
+
ret.append(lookup(features).view(-1, embedding_dim))
|
|
454
|
+
return ret
|
|
455
|
+
|
|
456
|
+
def output_dist(
|
|
457
|
+
self, ctx: ShardedModuleContext, output: List[torch.Tensor]
|
|
458
|
+
) -> LazyAwaitable[Dict[str, JaggedTensor]]:
|
|
459
|
+
awaitables_per_sharding: List[Awaitable[torch.Tensor]] = []
|
|
460
|
+
features_before_all2all_per_sharding: List[KeyedJaggedTensor] = []
|
|
461
|
+
for odist, embeddings, sharding_ctx in zip(
|
|
462
|
+
self._output_dists,
|
|
463
|
+
output,
|
|
464
|
+
cast(EmbeddingCollectionContext, ctx).sharding_contexts,
|
|
465
|
+
):
|
|
466
|
+
awaitables_per_sharding.append(odist(embeddings, sharding_ctx))
|
|
467
|
+
features_before_all2all_per_sharding.append(
|
|
468
|
+
sharding_ctx.features_before_input_dist
|
|
469
|
+
)
|
|
470
|
+
return EmbeddingCollectionAwaitable(
|
|
471
|
+
awaitables_per_sharding=awaitables_per_sharding,
|
|
472
|
+
features_per_sharding=features_before_all2all_per_sharding,
|
|
473
|
+
need_indices=self._need_indices,
|
|
474
|
+
features_to_permute_indices=self._features_to_permute_indices,
|
|
475
|
+
)
|
|
476
|
+
|
|
477
|
+
def compute_and_output_dist(
|
|
478
|
+
self, ctx: ShardedModuleContext, input: SparseFeaturesList
|
|
479
|
+
) -> LazyAwaitable[Dict[str, JaggedTensor]]:
|
|
480
|
+
awaitables_per_sharding: List[Awaitable[torch.Tensor]] = []
|
|
481
|
+
features_before_all2all_per_sharding: List[KeyedJaggedTensor] = []
|
|
482
|
+
for lookup, odist, features, sharding_ctx, sharding_type in zip(
|
|
483
|
+
self._lookups,
|
|
484
|
+
self._output_dists,
|
|
485
|
+
input,
|
|
486
|
+
cast(EmbeddingCollectionContext, ctx).sharding_contexts,
|
|
487
|
+
self._sharding_type_to_sharding,
|
|
488
|
+
):
|
|
489
|
+
sharding_ctx.lengths_after_input_dist = (
|
|
490
|
+
features.id_list_features.lengths().view(
|
|
491
|
+
-1, features.id_list_features.stride()
|
|
492
|
+
)
|
|
493
|
+
)
|
|
494
|
+
embedding_dim = self._embedding_dim_for_sharding_type(sharding_type)
|
|
495
|
+
awaitables_per_sharding.append(
|
|
496
|
+
odist(lookup(features).view(-1, embedding_dim), sharding_ctx)
|
|
497
|
+
)
|
|
498
|
+
features_before_all2all_per_sharding.append(
|
|
499
|
+
sharding_ctx.features_before_input_dist
|
|
500
|
+
)
|
|
501
|
+
return EmbeddingCollectionAwaitable(
|
|
502
|
+
awaitables_per_sharding=awaitables_per_sharding,
|
|
503
|
+
features_per_sharding=features_before_all2all_per_sharding,
|
|
504
|
+
need_indices=self._need_indices,
|
|
505
|
+
features_to_permute_indices=self._features_to_permute_indices,
|
|
506
|
+
)
|
|
507
|
+
|
|
508
|
+
def _embedding_dim_for_sharding_type(self, sharding_type: str) -> int:
|
|
509
|
+
return (
|
|
510
|
+
self._local_embedding_dim
|
|
511
|
+
if sharding_type == ShardingType.COLUMN_WISE.value
|
|
512
|
+
else self._embedding_dim
|
|
513
|
+
)
|
|
514
|
+
|
|
515
|
+
# pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently.
|
|
516
|
+
def state_dict(
|
|
517
|
+
self,
|
|
518
|
+
destination: Optional[Dict[str, Any]] = None,
|
|
519
|
+
prefix: str = "",
|
|
520
|
+
keep_vars: bool = False,
|
|
521
|
+
) -> Dict[str, Any]:
|
|
522
|
+
if destination is None:
|
|
523
|
+
destination = OrderedDict()
|
|
524
|
+
# pyre-ignore [16]
|
|
525
|
+
destination._metadata = OrderedDict()
|
|
526
|
+
for lookup in self._lookups:
|
|
527
|
+
lookup.state_dict(destination, prefix + "embeddings.", keep_vars)
|
|
528
|
+
return destination
|
|
529
|
+
|
|
530
|
+
def named_modules(
|
|
531
|
+
self,
|
|
532
|
+
memo: Optional[Set[nn.Module]] = None,
|
|
533
|
+
prefix: str = "",
|
|
534
|
+
remove_duplicate: bool = True,
|
|
535
|
+
) -> Iterator[Tuple[str, nn.Module]]:
|
|
536
|
+
yield from [(prefix, self)]
|
|
537
|
+
|
|
538
|
+
def named_parameters(
|
|
539
|
+
self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
|
|
540
|
+
) -> Iterator[Tuple[str, nn.Parameter]]:
|
|
541
|
+
for lookup in self._lookups:
|
|
542
|
+
yield from lookup.named_parameters(
|
|
543
|
+
append_prefix(prefix, "embeddings"), recurse
|
|
544
|
+
)
|
|
545
|
+
|
|
546
|
+
def named_buffers(
|
|
547
|
+
self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
|
|
548
|
+
) -> Iterator[Tuple[str, torch.Tensor]]:
|
|
549
|
+
for lookup in self._lookups:
|
|
550
|
+
yield from lookup.named_buffers(
|
|
551
|
+
append_prefix(prefix, "embeddings"), recurse
|
|
552
|
+
)
|
|
553
|
+
|
|
554
|
+
# pyre-fixme[14]: `load_state_dict` overrides method defined in `Module`
|
|
555
|
+
# inconsistently.
|
|
556
|
+
def load_state_dict(
|
|
557
|
+
self,
|
|
558
|
+
state_dict: "OrderedDict[str, torch.Tensor]",
|
|
559
|
+
strict: bool = True,
|
|
560
|
+
) -> _IncompatibleKeys:
|
|
561
|
+
missing_keys = []
|
|
562
|
+
unexpected_keys = []
|
|
563
|
+
for lookup in self._lookups:
|
|
564
|
+
missing, unexpected = lookup.load_state_dict(
|
|
565
|
+
filter_state_dict(state_dict, "embeddings"),
|
|
566
|
+
strict,
|
|
567
|
+
)
|
|
568
|
+
missing_keys.extend(missing)
|
|
569
|
+
unexpected_keys.extend(unexpected)
|
|
570
|
+
return _IncompatibleKeys(
|
|
571
|
+
missing_keys=missing_keys, unexpected_keys=unexpected_keys
|
|
572
|
+
)
|
|
573
|
+
|
|
574
|
+
def sparse_grad_parameter_names(
|
|
575
|
+
self,
|
|
576
|
+
destination: Optional[List[str]] = None,
|
|
577
|
+
prefix: str = "",
|
|
578
|
+
) -> List[str]:
|
|
579
|
+
destination = [] if destination is None else destination
|
|
580
|
+
for lookup in self._lookups:
|
|
581
|
+
lookup.sparse_grad_parameter_names(
|
|
582
|
+
destination, append_prefix(prefix, "embeddings")
|
|
583
|
+
)
|
|
584
|
+
return destination
|
|
585
|
+
|
|
586
|
+
def sharded_parameter_names(self, prefix: str = "") -> Iterator[str]:
|
|
587
|
+
for lookup, sharding_type in zip(
|
|
588
|
+
self._lookups, self._sharding_type_to_sharding.keys()
|
|
589
|
+
):
|
|
590
|
+
if sharding_type == ShardingType.DATA_PARALLEL.value:
|
|
591
|
+
continue
|
|
592
|
+
for name, _ in lookup.named_parameters(append_prefix(prefix, "embeddings")):
|
|
593
|
+
yield name
|
|
594
|
+
|
|
595
|
+
@property
|
|
596
|
+
def fused_optimizer(self) -> KeyedOptimizer:
|
|
597
|
+
return self._optim
|
|
598
|
+
|
|
599
|
+
def create_context(self) -> ShardedModuleContext:
|
|
600
|
+
return EmbeddingCollectionContext(sharding_contexts=[])
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
class EmbeddingCollectionSharder(BaseEmbeddingSharder[EmbeddingCollection]):
|
|
604
|
+
"""
|
|
605
|
+
This implementation uses non-fused EmbeddingCollection
|
|
606
|
+
"""
|
|
607
|
+
|
|
608
|
+
def shard(
|
|
609
|
+
self,
|
|
610
|
+
module: EmbeddingCollection,
|
|
611
|
+
params: Dict[str, ParameterSharding],
|
|
612
|
+
env: ShardingEnv,
|
|
613
|
+
device: Optional[torch.device] = None,
|
|
614
|
+
) -> ShardedEmbeddingCollection:
|
|
615
|
+
return ShardedEmbeddingCollection(
|
|
616
|
+
module, params, env, self.fused_params, device
|
|
617
|
+
)
|
|
618
|
+
|
|
619
|
+
def shardable_parameters(
|
|
620
|
+
self, module: EmbeddingCollection
|
|
621
|
+
) -> Dict[str, nn.Parameter]:
|
|
622
|
+
return {
|
|
623
|
+
name.split(".")[0]: param
|
|
624
|
+
for name, param in module.embeddings.named_parameters()
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
def sharding_types(self, compute_device_type: str) -> List[str]:
|
|
628
|
+
types = [
|
|
629
|
+
ShardingType.DATA_PARALLEL.value,
|
|
630
|
+
ShardingType.TABLE_WISE.value,
|
|
631
|
+
ShardingType.COLUMN_WISE.value,
|
|
632
|
+
ShardingType.ROW_WISE.value,
|
|
633
|
+
]
|
|
634
|
+
return types
|
|
635
|
+
|
|
636
|
+
@property
|
|
637
|
+
def module_type(self) -> Type[EmbeddingCollection]:
|
|
638
|
+
return EmbeddingCollection
|