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,992 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
3
|
+
# All rights reserved.
|
|
4
|
+
#
|
|
5
|
+
# This source code is licensed under the BSD-style license found in the
|
|
6
|
+
# LICENSE file in the root directory of this source tree.
|
|
7
|
+
|
|
8
|
+
from collections import OrderedDict
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any, cast, Dict, Iterator, List, Optional, Set, Tuple, Type, TypeVar
|
|
11
|
+
|
|
12
|
+
import torch
|
|
13
|
+
import torch.distributed as dist
|
|
14
|
+
from torch import nn
|
|
15
|
+
from torch.nn.parallel import DistributedDataParallel
|
|
16
|
+
from torchrec.distributed.comm import intra_and_cross_node_pg
|
|
17
|
+
from torchrec.distributed.dist_data import (
|
|
18
|
+
PooledEmbeddingsAllToAll,
|
|
19
|
+
PooledEmbeddingsAwaitable,
|
|
20
|
+
)
|
|
21
|
+
from torchrec.distributed.embedding import EmbeddingCollectionSharder
|
|
22
|
+
from torchrec.distributed.embedding_sharding import (
|
|
23
|
+
SparseFeaturesAllToAll,
|
|
24
|
+
SparseFeaturesListAwaitable,
|
|
25
|
+
)
|
|
26
|
+
from torchrec.distributed.embedding_types import (
|
|
27
|
+
BaseEmbeddingSharder,
|
|
28
|
+
SparseFeatures,
|
|
29
|
+
SparseFeaturesList,
|
|
30
|
+
)
|
|
31
|
+
from torchrec.distributed.embeddingbag import EmbeddingBagCollectionSharder
|
|
32
|
+
from torchrec.distributed.types import (
|
|
33
|
+
Awaitable,
|
|
34
|
+
LazyAwaitable,
|
|
35
|
+
ParameterSharding,
|
|
36
|
+
ShardedModule,
|
|
37
|
+
ShardedModuleContext,
|
|
38
|
+
ShardingEnv,
|
|
39
|
+
ShardingType,
|
|
40
|
+
)
|
|
41
|
+
from torchrec.distributed.utils import append_prefix
|
|
42
|
+
from torchrec.modules.embedding_modules import (
|
|
43
|
+
EmbeddingBagCollection,
|
|
44
|
+
EmbeddingCollection,
|
|
45
|
+
)
|
|
46
|
+
from torchrec.modules.embedding_tower import (
|
|
47
|
+
EmbeddingTower,
|
|
48
|
+
EmbeddingTowerCollection,
|
|
49
|
+
tower_input_params,
|
|
50
|
+
)
|
|
51
|
+
from torchrec.optim.fused import FusedOptimizerModule
|
|
52
|
+
from torchrec.optim.keyed import CombinedOptimizer, KeyedOptimizer
|
|
53
|
+
from torchrec.sparse.jagged_tensor import KeyedJaggedTensor
|
|
54
|
+
|
|
55
|
+
M = TypeVar("M", bound=nn.Module)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _replace_sharding_with_intra_node(
|
|
59
|
+
table_name_to_parameter_sharding: Dict[str, ParameterSharding], local_size: int
|
|
60
|
+
) -> None:
|
|
61
|
+
for _, value in table_name_to_parameter_sharding.items():
|
|
62
|
+
if value.sharding_type == ShardingType.TABLE_ROW_WISE.value:
|
|
63
|
+
value.sharding_type = ShardingType.ROW_WISE.value
|
|
64
|
+
elif value.sharding_type == ShardingType.TABLE_COLUMN_WISE.value:
|
|
65
|
+
value.sharding_type = ShardingType.COLUMN_WISE.value
|
|
66
|
+
else:
|
|
67
|
+
raise ValueError(f"Sharding type not supported {value.sharding_type}")
|
|
68
|
+
if value.ranks:
|
|
69
|
+
value.ranks = [rank % local_size for rank in value.ranks]
|
|
70
|
+
if value.sharding_spec:
|
|
71
|
+
# pyre-ignore [6, 16]
|
|
72
|
+
for (shard, rank) in zip(value.sharding_spec.shards, value.ranks):
|
|
73
|
+
shard.placement._rank = rank
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class TowerLazyAwaitable(LazyAwaitable[torch.Tensor]):
|
|
77
|
+
def __init__(
|
|
78
|
+
self,
|
|
79
|
+
awaitable: PooledEmbeddingsAwaitable,
|
|
80
|
+
) -> None:
|
|
81
|
+
super().__init__()
|
|
82
|
+
self._awaitable = awaitable
|
|
83
|
+
|
|
84
|
+
def _wait_impl(self) -> torch.Tensor:
|
|
85
|
+
return self._awaitable.wait()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass
|
|
89
|
+
class EmbeddingTowerCollectionContext(ShardedModuleContext):
|
|
90
|
+
embedding_contexts: List[ShardedModuleContext]
|
|
91
|
+
|
|
92
|
+
def record_stream(self, stream: torch.cuda.streams.Stream) -> None:
|
|
93
|
+
for ctx in self.embedding_contexts:
|
|
94
|
+
ctx.record_stream(stream)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class ShardedEmbeddingTower(
|
|
98
|
+
ShardedModule[
|
|
99
|
+
SparseFeaturesList,
|
|
100
|
+
torch.Tensor,
|
|
101
|
+
torch.Tensor,
|
|
102
|
+
],
|
|
103
|
+
FusedOptimizerModule,
|
|
104
|
+
):
|
|
105
|
+
def __init__(
|
|
106
|
+
self,
|
|
107
|
+
module: EmbeddingTower,
|
|
108
|
+
table_name_to_parameter_sharding: Dict[str, ParameterSharding],
|
|
109
|
+
embedding_sharder: BaseEmbeddingSharder[nn.Module],
|
|
110
|
+
kjt_features: List[str],
|
|
111
|
+
wkjt_features: List[str],
|
|
112
|
+
env: ShardingEnv,
|
|
113
|
+
fused_params: Optional[Dict[str, Any]] = None,
|
|
114
|
+
device: Optional[torch.device] = None,
|
|
115
|
+
) -> None:
|
|
116
|
+
super().__init__()
|
|
117
|
+
intra_pg, cross_pg = intra_and_cross_node_pg(device)
|
|
118
|
+
self._intra_pg: Optional[dist.ProcessGroup] = intra_pg
|
|
119
|
+
self._cross_pg: Optional[dist.ProcessGroup] = cross_pg
|
|
120
|
+
self._device = device
|
|
121
|
+
self._output_dist: Optional[PooledEmbeddingsAllToAll] = None
|
|
122
|
+
self._cross_pg_global_batch_size: int = 0
|
|
123
|
+
self._cross_pg_world_size: int = dist.get_world_size(self._cross_pg)
|
|
124
|
+
|
|
125
|
+
self._has_uninitialized_output_dist = True
|
|
126
|
+
|
|
127
|
+
# make sure all sharding on single physical node
|
|
128
|
+
devices_per_host = dist.get_world_size(intra_pg)
|
|
129
|
+
tower_devices = set()
|
|
130
|
+
for sharding in table_name_to_parameter_sharding.values():
|
|
131
|
+
# pyre-ignore [6]
|
|
132
|
+
tower_devices.update(sharding.ranks)
|
|
133
|
+
host = {tower_device // devices_per_host for tower_device in tower_devices}
|
|
134
|
+
assert len(host) == 1, f"{tower_devices}, {table_name_to_parameter_sharding}"
|
|
135
|
+
self._tower_node: int = next(iter(host))
|
|
136
|
+
self._active_device: bool = {dist.get_rank() // devices_per_host} == host
|
|
137
|
+
|
|
138
|
+
# input_dist
|
|
139
|
+
self._kjt_feature_names: List[str] = kjt_features
|
|
140
|
+
self._wkjt_feature_names: List[str] = wkjt_features
|
|
141
|
+
self._has_uninitialized_input_dist: bool = True
|
|
142
|
+
self._cross_dist: nn.Module = nn.Module()
|
|
143
|
+
self._kjt_features_order: List[int] = []
|
|
144
|
+
self._wkjt_features_order: List[int] = []
|
|
145
|
+
self._has_kjt_features_permute: bool = False
|
|
146
|
+
self._has_wkjt_features_permute: bool = False
|
|
147
|
+
|
|
148
|
+
self.embedding: Optional[nn.Module] = None
|
|
149
|
+
self.interaction: Optional[nn.Module] = None
|
|
150
|
+
if self._active_device:
|
|
151
|
+
_replace_sharding_with_intra_node(
|
|
152
|
+
table_name_to_parameter_sharding, dist.get_world_size(self._intra_pg)
|
|
153
|
+
)
|
|
154
|
+
intra_env: ShardingEnv = ShardingEnv(
|
|
155
|
+
world_size=dist.get_world_size(self._intra_pg),
|
|
156
|
+
rank=dist.get_rank(self._intra_pg),
|
|
157
|
+
pg=self._intra_pg,
|
|
158
|
+
)
|
|
159
|
+
# shard embedding module
|
|
160
|
+
self.embedding = embedding_sharder.shard(
|
|
161
|
+
module.embedding,
|
|
162
|
+
table_name_to_parameter_sharding,
|
|
163
|
+
intra_env,
|
|
164
|
+
device,
|
|
165
|
+
)
|
|
166
|
+
# Hierarchical DDP
|
|
167
|
+
# pyre-fixme[28]: Unexpected keyword argument `gradient_as_bucket_view`.
|
|
168
|
+
self.interaction = DistributedDataParallel(
|
|
169
|
+
module=module.interaction.to(self._device),
|
|
170
|
+
device_ids=[self._device],
|
|
171
|
+
process_group=self._intra_pg,
|
|
172
|
+
gradient_as_bucket_view=True,
|
|
173
|
+
broadcast_buffers=False,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
# Setup output dists for quantized comms
|
|
177
|
+
# pyre-fixme[8]: Attribute has type `ModuleList`; used as `Union[Module,
|
|
178
|
+
# Tensor]`.
|
|
179
|
+
self._output_dists: nn.ModuleList = (
|
|
180
|
+
self.embedding._output_dists if self.embedding else nn.ModuleList()
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
def _create_input_dist(
|
|
184
|
+
self,
|
|
185
|
+
kjt_feature_names: List[str],
|
|
186
|
+
wkjt_feature_names: List[str],
|
|
187
|
+
) -> None:
|
|
188
|
+
if self._kjt_feature_names != kjt_feature_names:
|
|
189
|
+
self._has_kjt_features_permute = True
|
|
190
|
+
for f in self._kjt_feature_names:
|
|
191
|
+
self._kjt_features_order.append(kjt_feature_names.index(f))
|
|
192
|
+
self.register_buffer(
|
|
193
|
+
"_kjt_features_order_tensor",
|
|
194
|
+
torch.tensor(
|
|
195
|
+
self._kjt_features_order, device=self._device, dtype=torch.int32
|
|
196
|
+
),
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
if self._wkjt_feature_names != wkjt_feature_names:
|
|
200
|
+
self._has_wkjt_features_permute = True
|
|
201
|
+
for f in self._wkjt_feature_names:
|
|
202
|
+
self._wkjt_features_order.append(wkjt_feature_names.index(f))
|
|
203
|
+
self.register_buffer(
|
|
204
|
+
"_wkjt_features_order_tensor",
|
|
205
|
+
torch.tensor(
|
|
206
|
+
self._wkjt_features_order, device=self._device, dtype=torch.int32
|
|
207
|
+
),
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
node_count = dist.get_world_size(self._cross_pg)
|
|
211
|
+
kjt_features_per_node = [
|
|
212
|
+
len(self._kjt_feature_names) if node == self._tower_node else 0
|
|
213
|
+
for node in range(node_count)
|
|
214
|
+
]
|
|
215
|
+
wkjt_features_per_node = [
|
|
216
|
+
len(self._wkjt_feature_names) if node == self._tower_node else 0
|
|
217
|
+
for node in range(node_count)
|
|
218
|
+
]
|
|
219
|
+
self._cross_dist = SparseFeaturesAllToAll(
|
|
220
|
+
# pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
|
|
221
|
+
# `Optional[ProcessGroup]`.
|
|
222
|
+
self._cross_pg,
|
|
223
|
+
kjt_features_per_node,
|
|
224
|
+
wkjt_features_per_node,
|
|
225
|
+
self._device,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
# pyre-ignore [14]
|
|
229
|
+
def input_dist(
|
|
230
|
+
self,
|
|
231
|
+
ctx: ShardedModuleContext,
|
|
232
|
+
features: KeyedJaggedTensor,
|
|
233
|
+
optional_features: Optional[KeyedJaggedTensor] = None,
|
|
234
|
+
) -> Awaitable[SparseFeaturesList]:
|
|
235
|
+
|
|
236
|
+
# optional_features are populated only if both kjt and weighted kjt present in tower
|
|
237
|
+
if self._wkjt_feature_names and self._kjt_feature_names:
|
|
238
|
+
kjt_features = features
|
|
239
|
+
wkjt_features = optional_features
|
|
240
|
+
elif self._wkjt_feature_names:
|
|
241
|
+
kjt_features = None
|
|
242
|
+
wkjt_features = features
|
|
243
|
+
else:
|
|
244
|
+
kjt_features = features
|
|
245
|
+
wkjt_features = None
|
|
246
|
+
|
|
247
|
+
if self._has_uninitialized_input_dist:
|
|
248
|
+
self._cross_pg_global_batch_size = (
|
|
249
|
+
features.stride() * self._cross_pg_world_size
|
|
250
|
+
)
|
|
251
|
+
self._create_input_dist(
|
|
252
|
+
kjt_features.keys() if kjt_features else [],
|
|
253
|
+
wkjt_features.keys() if wkjt_features else [],
|
|
254
|
+
)
|
|
255
|
+
self._has_uninitialized_input_dist = False
|
|
256
|
+
|
|
257
|
+
with torch.no_grad():
|
|
258
|
+
if self._has_kjt_features_permute:
|
|
259
|
+
# pyre-ignore [16]
|
|
260
|
+
kjt_features = kjt_features.permute(
|
|
261
|
+
self._kjt_features_order,
|
|
262
|
+
self._kjt_features_order_tensor,
|
|
263
|
+
)
|
|
264
|
+
if self._has_wkjt_features_permute:
|
|
265
|
+
wkjt_features = wkjt_features.permute(
|
|
266
|
+
self._wkjt_features_order,
|
|
267
|
+
self._wkjt_features_order_tensor,
|
|
268
|
+
)
|
|
269
|
+
tensor_awaitable = self._cross_dist(
|
|
270
|
+
SparseFeatures(
|
|
271
|
+
id_list_features=kjt_features,
|
|
272
|
+
id_score_list_features=wkjt_features,
|
|
273
|
+
)
|
|
274
|
+
)
|
|
275
|
+
return SparseFeaturesListAwaitable([tensor_awaitable.wait()])
|
|
276
|
+
|
|
277
|
+
def compute(
|
|
278
|
+
self, ctx: ShardedModuleContext, dist_input: SparseFeaturesList
|
|
279
|
+
) -> torch.Tensor:
|
|
280
|
+
kjt_features = dist_input[0].id_list_features
|
|
281
|
+
wkjt_features = dist_input[0].id_score_list_features
|
|
282
|
+
|
|
283
|
+
if self._active_device:
|
|
284
|
+
if kjt_features and wkjt_features:
|
|
285
|
+
# pyre-ignore [29]
|
|
286
|
+
embeddings = self.embedding(kjt_features, wkjt_features)
|
|
287
|
+
elif wkjt_features:
|
|
288
|
+
# pyre-ignore [29]
|
|
289
|
+
embeddings = self.embedding(wkjt_features)
|
|
290
|
+
else:
|
|
291
|
+
# pyre-ignore [29]
|
|
292
|
+
embeddings = self.embedding(kjt_features)
|
|
293
|
+
# pyre-ignore [29]
|
|
294
|
+
output = self.interaction(embeddings)
|
|
295
|
+
else:
|
|
296
|
+
output = torch.empty(
|
|
297
|
+
[self._cross_pg_global_batch_size, 0],
|
|
298
|
+
device=self._device,
|
|
299
|
+
requires_grad=True,
|
|
300
|
+
)
|
|
301
|
+
return output
|
|
302
|
+
|
|
303
|
+
def _create_output_dist(
|
|
304
|
+
self, ctx: ShardedModuleContext, output: torch.Tensor
|
|
305
|
+
) -> None:
|
|
306
|
+
# Determine the output_dist splits and the all_to_all output size
|
|
307
|
+
assert len(output.shape) == 2
|
|
308
|
+
local_dim_sum = torch.tensor(
|
|
309
|
+
[
|
|
310
|
+
output.shape[1],
|
|
311
|
+
],
|
|
312
|
+
dtype=torch.int64,
|
|
313
|
+
device=self._device,
|
|
314
|
+
)
|
|
315
|
+
dim_sum_per_rank = [
|
|
316
|
+
torch.zeros(
|
|
317
|
+
1,
|
|
318
|
+
dtype=torch.int64,
|
|
319
|
+
device=self._device,
|
|
320
|
+
)
|
|
321
|
+
for i in range(dist.get_world_size(self._cross_pg))
|
|
322
|
+
]
|
|
323
|
+
dist.all_gather(
|
|
324
|
+
dim_sum_per_rank,
|
|
325
|
+
local_dim_sum,
|
|
326
|
+
group=self._cross_pg,
|
|
327
|
+
)
|
|
328
|
+
dim_sum_per_rank = [x.item() for x in dim_sum_per_rank]
|
|
329
|
+
self._output_dist = PooledEmbeddingsAllToAll(
|
|
330
|
+
# pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
|
|
331
|
+
# `Optional[ProcessGroup]`.
|
|
332
|
+
pg=self._cross_pg,
|
|
333
|
+
# pyre-fixme[6]: For 2nd param expected `List[int]` but got
|
|
334
|
+
# `List[Union[bool, float, int]]`.
|
|
335
|
+
dim_sum_per_rank=dim_sum_per_rank,
|
|
336
|
+
device=self._device,
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
def output_dist(
|
|
340
|
+
self, ctx: ShardedModuleContext, output: torch.Tensor
|
|
341
|
+
) -> LazyAwaitable[torch.Tensor]:
|
|
342
|
+
if self._has_uninitialized_output_dist:
|
|
343
|
+
self._create_output_dist(ctx, output)
|
|
344
|
+
self._has_uninitialized_output_dist = False
|
|
345
|
+
# pyre-ignore [29]
|
|
346
|
+
return TowerLazyAwaitable(self._output_dist(output))
|
|
347
|
+
|
|
348
|
+
# pyre-ignore [14]
|
|
349
|
+
def state_dict(
|
|
350
|
+
self,
|
|
351
|
+
destination: Optional[Dict[str, Any]] = None,
|
|
352
|
+
prefix: str = "",
|
|
353
|
+
keep_vars: bool = False,
|
|
354
|
+
) -> Dict[str, Any]:
|
|
355
|
+
if destination is None:
|
|
356
|
+
destination = OrderedDict()
|
|
357
|
+
# pyre-ignore [16]
|
|
358
|
+
destination._metadata = OrderedDict()
|
|
359
|
+
if self._active_device:
|
|
360
|
+
# pyre-ignore [16]
|
|
361
|
+
self.embedding.state_dict(destination, prefix + "embedding.", keep_vars)
|
|
362
|
+
# pyre-ignore [16]
|
|
363
|
+
self.interaction.module.state_dict(
|
|
364
|
+
destination, prefix + "interaction.", keep_vars
|
|
365
|
+
)
|
|
366
|
+
return destination
|
|
367
|
+
|
|
368
|
+
@property
|
|
369
|
+
def fused_optimizer(self) -> KeyedOptimizer:
|
|
370
|
+
if self.embedding:
|
|
371
|
+
# pyre-ignore [7]
|
|
372
|
+
return self.embedding.fused_optimizer
|
|
373
|
+
else:
|
|
374
|
+
return CombinedOptimizer([])
|
|
375
|
+
|
|
376
|
+
def named_parameters(
|
|
377
|
+
self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
|
|
378
|
+
) -> Iterator[Tuple[str, nn.Parameter]]:
|
|
379
|
+
if self._active_device:
|
|
380
|
+
# pyre-ignore[16]
|
|
381
|
+
yield from self.embedding.named_parameters(
|
|
382
|
+
append_prefix(prefix, "embedding"), recurse
|
|
383
|
+
)
|
|
384
|
+
# pyre-ignore[16]
|
|
385
|
+
yield from self.interaction.module.named_parameters(
|
|
386
|
+
append_prefix(prefix, "interaction"), recurse
|
|
387
|
+
)
|
|
388
|
+
else:
|
|
389
|
+
yield from ()
|
|
390
|
+
|
|
391
|
+
def named_buffers(
|
|
392
|
+
self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
|
|
393
|
+
) -> Iterator[Tuple[str, torch.Tensor]]:
|
|
394
|
+
if self._active_device:
|
|
395
|
+
# pyre-ignore[16]
|
|
396
|
+
yield from self.embedding.named_buffers(
|
|
397
|
+
append_prefix(prefix, "embedding"), recurse
|
|
398
|
+
)
|
|
399
|
+
# pyre-ignore[16]
|
|
400
|
+
yield from self.interaction.module.named_buffers(
|
|
401
|
+
append_prefix(prefix, "interaction"), recurse
|
|
402
|
+
)
|
|
403
|
+
yield from ()
|
|
404
|
+
|
|
405
|
+
def sparse_grad_parameter_names(
|
|
406
|
+
self,
|
|
407
|
+
destination: Optional[List[str]] = None,
|
|
408
|
+
prefix: str = "",
|
|
409
|
+
) -> List[str]:
|
|
410
|
+
destination = [] if destination is None else destination
|
|
411
|
+
if self._active_device:
|
|
412
|
+
# pyre-ignore[16]
|
|
413
|
+
self.embedding.sparse_grad_parameter_names(
|
|
414
|
+
destination, append_prefix(prefix, "embedding")
|
|
415
|
+
)
|
|
416
|
+
return destination
|
|
417
|
+
|
|
418
|
+
def sharded_parameter_names(self, prefix: str = "") -> Iterator[str]:
|
|
419
|
+
if self._active_device:
|
|
420
|
+
# pyre-ignore[16]
|
|
421
|
+
yield from self.embedding.sharded_parameter_names(
|
|
422
|
+
append_prefix(prefix, "embedding")
|
|
423
|
+
)
|
|
424
|
+
# pyre-ignore[16]
|
|
425
|
+
for name, _ in self.interaction.module.named_parameters(
|
|
426
|
+
append_prefix(prefix, "interaction")
|
|
427
|
+
):
|
|
428
|
+
yield name
|
|
429
|
+
else:
|
|
430
|
+
yield from ()
|
|
431
|
+
|
|
432
|
+
def named_modules(
|
|
433
|
+
self,
|
|
434
|
+
memo: Optional[Set[nn.Module]] = None,
|
|
435
|
+
prefix: str = "",
|
|
436
|
+
remove_duplicate: bool = True,
|
|
437
|
+
) -> Iterator[Tuple[str, nn.Module]]:
|
|
438
|
+
yield from [(prefix, self)]
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
class ShardedEmbeddingTowerCollection(
|
|
442
|
+
ShardedModule[
|
|
443
|
+
SparseFeaturesList,
|
|
444
|
+
torch.Tensor,
|
|
445
|
+
torch.Tensor,
|
|
446
|
+
],
|
|
447
|
+
FusedOptimizerModule,
|
|
448
|
+
):
|
|
449
|
+
def __init__(
|
|
450
|
+
self,
|
|
451
|
+
module: EmbeddingTowerCollection,
|
|
452
|
+
table_name_to_parameter_sharding: Dict[str, ParameterSharding],
|
|
453
|
+
tower_sharder: BaseEmbeddingSharder[EmbeddingTower],
|
|
454
|
+
env: ShardingEnv,
|
|
455
|
+
fused_params: Optional[Dict[str, Any]] = None,
|
|
456
|
+
device: Optional[torch.device] = None,
|
|
457
|
+
) -> None:
|
|
458
|
+
super().__init__()
|
|
459
|
+
|
|
460
|
+
intra_pg, cross_pg = intra_and_cross_node_pg(device)
|
|
461
|
+
self._intra_pg: Optional[dist.ProcessGroup] = intra_pg
|
|
462
|
+
self._cross_pg: Optional[dist.ProcessGroup] = cross_pg
|
|
463
|
+
self._cross_pg_world_size: int = dist.get_world_size(self._cross_pg)
|
|
464
|
+
self._intra_pg_world_size: int = dist.get_world_size(self._intra_pg)
|
|
465
|
+
self._device = device
|
|
466
|
+
self._tower_id: int = dist.get_rank() // self._intra_pg_world_size
|
|
467
|
+
self._output_dist: Optional[PooledEmbeddingsAllToAll] = None
|
|
468
|
+
self._cross_pg_global_batch_size: int = 0
|
|
469
|
+
self._is_weighted: bool = False
|
|
470
|
+
self._has_uninitialized_input_dist: bool = True
|
|
471
|
+
self._has_uninitialized_output_dist: bool = True
|
|
472
|
+
self._kjt_features_order: List[int] = []
|
|
473
|
+
self._wkjt_features_order: List[int] = []
|
|
474
|
+
self._kjt_feature_names: List[str] = []
|
|
475
|
+
self._wkjt_feature_names: List[str] = []
|
|
476
|
+
self._kjt_num_features_per_pt: List[int] = []
|
|
477
|
+
self._wkjt_num_features_per_pt: List[int] = []
|
|
478
|
+
self._has_kjt_features_permute: bool = False
|
|
479
|
+
self._has_wkjt_features_permute: bool = False
|
|
480
|
+
self.embeddings: nn.ModuleDict = nn.ModuleDict()
|
|
481
|
+
self.interactions: nn.ModuleDict = nn.ModuleDict()
|
|
482
|
+
self.input_dist_params: List[Tuple[bool, bool]] = []
|
|
483
|
+
self._cross_dist: nn.Module = nn.Module()
|
|
484
|
+
|
|
485
|
+
# groups parameter sharding into physical towers
|
|
486
|
+
tables_per_pt: List[Set[str]] = [
|
|
487
|
+
set() for _ in range(self._cross_pg_world_size)
|
|
488
|
+
]
|
|
489
|
+
[
|
|
490
|
+
tables_per_pt[i].add(k)
|
|
491
|
+
for i in range(self._cross_pg_world_size)
|
|
492
|
+
for k, v in table_name_to_parameter_sharding.items()
|
|
493
|
+
# pyre-ignore [16]
|
|
494
|
+
if v.ranks[0] // self._intra_pg_world_size == i
|
|
495
|
+
]
|
|
496
|
+
|
|
497
|
+
# create mapping of logical towers to physical towers
|
|
498
|
+
tables_per_lt: List[Set[str]] = []
|
|
499
|
+
for tower in module.towers:
|
|
500
|
+
lt_tables = set(tower_sharder.shardable_parameters(tower).keys())
|
|
501
|
+
tables_per_lt.append(lt_tables)
|
|
502
|
+
# check the tables in a logical tower are on same physical tower
|
|
503
|
+
found_physical_tower = False
|
|
504
|
+
for pt_tables in tables_per_pt:
|
|
505
|
+
if lt_tables.issubset(pt_tables):
|
|
506
|
+
found_physical_tower = True
|
|
507
|
+
break
|
|
508
|
+
assert (
|
|
509
|
+
found_physical_tower
|
|
510
|
+
), f"tables in a logical tower must be in the same physical tower, logical tower tables: {lt_tables}, tables_per_pt: {tables_per_pt}"
|
|
511
|
+
|
|
512
|
+
logical_to_physical_order: List[List[int]] = [
|
|
513
|
+
[] for _ in range(self._cross_pg_world_size)
|
|
514
|
+
]
|
|
515
|
+
feature_names_by_pt: List[Tuple[List[str], List[str]]] = [
|
|
516
|
+
([], []) for _ in range(self._cross_pg_world_size)
|
|
517
|
+
]
|
|
518
|
+
|
|
519
|
+
for i, pt_tables in enumerate(tables_per_pt):
|
|
520
|
+
found = False
|
|
521
|
+
for j, lt_tables in enumerate(tables_per_lt):
|
|
522
|
+
if lt_tables.issubset(pt_tables):
|
|
523
|
+
logical_to_physical_order[i].append(j)
|
|
524
|
+
found = True
|
|
525
|
+
if not found and pt_tables:
|
|
526
|
+
raise RuntimeError(
|
|
527
|
+
f"Could not find any towers with features: {pt_tables}"
|
|
528
|
+
)
|
|
529
|
+
|
|
530
|
+
for pt_index, lt_on_pt in enumerate(logical_to_physical_order):
|
|
531
|
+
for lt_index in lt_on_pt:
|
|
532
|
+
# pyre-ignore [16]
|
|
533
|
+
kjt_features, wkjt_features = tower_sharder.embedding_feature_names(
|
|
534
|
+
module.towers[lt_index]
|
|
535
|
+
)
|
|
536
|
+
feature_names_by_pt[pt_index][0].extend(kjt_features)
|
|
537
|
+
feature_names_by_pt[pt_index][1].extend(wkjt_features)
|
|
538
|
+
|
|
539
|
+
for kjt_names, wkjt_names in feature_names_by_pt:
|
|
540
|
+
self._kjt_feature_names.extend(kjt_names)
|
|
541
|
+
self._wkjt_feature_names.extend(wkjt_names)
|
|
542
|
+
self._kjt_num_features_per_pt.append(len(kjt_names))
|
|
543
|
+
self._wkjt_num_features_per_pt.append(len(wkjt_names))
|
|
544
|
+
|
|
545
|
+
local_towers: List[Tuple[str, EmbeddingTower]] = [
|
|
546
|
+
(str(i), tower)
|
|
547
|
+
for i, tower in enumerate(module.towers)
|
|
548
|
+
if i in logical_to_physical_order[self._tower_id]
|
|
549
|
+
]
|
|
550
|
+
|
|
551
|
+
if local_towers:
|
|
552
|
+
_replace_sharding_with_intra_node(
|
|
553
|
+
table_name_to_parameter_sharding, dist.get_world_size(self._intra_pg)
|
|
554
|
+
)
|
|
555
|
+
intra_env: ShardingEnv = ShardingEnv(
|
|
556
|
+
world_size=dist.get_world_size(self._intra_pg),
|
|
557
|
+
rank=dist.get_rank(self._intra_pg),
|
|
558
|
+
pg=self._intra_pg,
|
|
559
|
+
)
|
|
560
|
+
for i, tower in local_towers:
|
|
561
|
+
# pyre-ignore [16]
|
|
562
|
+
self.embeddings[i] = tower_sharder.embedding_sharder(tower).shard(
|
|
563
|
+
tower.embedding,
|
|
564
|
+
table_name_to_parameter_sharding,
|
|
565
|
+
intra_env,
|
|
566
|
+
device,
|
|
567
|
+
)
|
|
568
|
+
self.input_dist_params.append(tower_input_params(tower.embedding))
|
|
569
|
+
# Hierarchical DDP
|
|
570
|
+
# pyre-fixme[28]: Unexpected keyword argument `gradient_as_bucket_view`.
|
|
571
|
+
self.interactions[i] = DistributedDataParallel(
|
|
572
|
+
module=tower.interaction.to(self._device),
|
|
573
|
+
device_ids=[self._device],
|
|
574
|
+
process_group=self._intra_pg,
|
|
575
|
+
gradient_as_bucket_view=True,
|
|
576
|
+
broadcast_buffers=False,
|
|
577
|
+
static_graph=True,
|
|
578
|
+
)
|
|
579
|
+
|
|
580
|
+
# Setup output dists for quantized comms
|
|
581
|
+
output_dists = nn.ModuleList()
|
|
582
|
+
for embedding in self.embeddings.values():
|
|
583
|
+
output_dists.extend(embedding._output_dists)
|
|
584
|
+
self._output_dists: nn.ModuleList = output_dists
|
|
585
|
+
|
|
586
|
+
def _create_input_dist(
|
|
587
|
+
self,
|
|
588
|
+
kjt_feature_names: List[str],
|
|
589
|
+
wkjt_feature_names: List[str],
|
|
590
|
+
) -> None:
|
|
591
|
+
|
|
592
|
+
if self._kjt_feature_names != kjt_feature_names:
|
|
593
|
+
self._has_kjt_features_permute = True
|
|
594
|
+
for f in self._kjt_feature_names:
|
|
595
|
+
self._kjt_features_order.append(kjt_feature_names.index(f))
|
|
596
|
+
self.register_buffer(
|
|
597
|
+
"_kjt_features_order_tensor",
|
|
598
|
+
torch.tensor(
|
|
599
|
+
self._kjt_features_order, device=self._device, dtype=torch.int32
|
|
600
|
+
),
|
|
601
|
+
)
|
|
602
|
+
|
|
603
|
+
if self._wkjt_feature_names != wkjt_feature_names:
|
|
604
|
+
self._has_wkjt_features_permute = True
|
|
605
|
+
for f in self._wkjt_feature_names:
|
|
606
|
+
self._wkjt_features_order.append(wkjt_feature_names.index(f))
|
|
607
|
+
self.register_buffer(
|
|
608
|
+
"_wkjt_features_order_tensor",
|
|
609
|
+
torch.tensor(
|
|
610
|
+
self._wkjt_features_order, device=self._device, dtype=torch.int32
|
|
611
|
+
),
|
|
612
|
+
)
|
|
613
|
+
self._cross_dist = SparseFeaturesAllToAll(
|
|
614
|
+
# pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
|
|
615
|
+
# `Optional[ProcessGroup]`.
|
|
616
|
+
self._cross_pg,
|
|
617
|
+
self._kjt_num_features_per_pt,
|
|
618
|
+
self._wkjt_num_features_per_pt,
|
|
619
|
+
self._device,
|
|
620
|
+
)
|
|
621
|
+
|
|
622
|
+
# pyre-ignore [14]
|
|
623
|
+
def input_dist(
|
|
624
|
+
self,
|
|
625
|
+
ctx: EmbeddingTowerCollectionContext,
|
|
626
|
+
kjt_features: Optional[KeyedJaggedTensor] = None,
|
|
627
|
+
wkjt_features: Optional[KeyedJaggedTensor] = None,
|
|
628
|
+
) -> Awaitable[SparseFeaturesList]:
|
|
629
|
+
if self._has_uninitialized_input_dist:
|
|
630
|
+
# pyre-ignore [16]
|
|
631
|
+
stride = kjt_features.stride() if kjt_features else wkjt_features.stride()
|
|
632
|
+
self._cross_pg_global_batch_size = stride * self._cross_pg_world_size
|
|
633
|
+
self._create_input_dist(
|
|
634
|
+
kjt_features.keys() if kjt_features else [],
|
|
635
|
+
wkjt_features.keys() if wkjt_features else [],
|
|
636
|
+
)
|
|
637
|
+
self._has_uninitialized_input_dist = False
|
|
638
|
+
with torch.no_grad():
|
|
639
|
+
if self._has_kjt_features_permute:
|
|
640
|
+
kjt_features = kjt_features.permute( # pyre-ignore [16]
|
|
641
|
+
self._kjt_features_order,
|
|
642
|
+
cast(torch.Tensor, self._kjt_features_order_tensor),
|
|
643
|
+
)
|
|
644
|
+
if self._has_wkjt_features_permute:
|
|
645
|
+
wkjt_features = wkjt_features.permute(
|
|
646
|
+
self._wkjt_features_order,
|
|
647
|
+
cast(torch.Tensor, self._wkjt_features_order_tensor),
|
|
648
|
+
)
|
|
649
|
+
sparse_features_awaitable = self._cross_dist(
|
|
650
|
+
SparseFeatures(
|
|
651
|
+
id_list_features=kjt_features,
|
|
652
|
+
id_score_list_features=wkjt_features,
|
|
653
|
+
)
|
|
654
|
+
)
|
|
655
|
+
|
|
656
|
+
sparse_features = sparse_features_awaitable.wait().wait()
|
|
657
|
+
|
|
658
|
+
input_dists = []
|
|
659
|
+
for embedding, input_dist_params in zip(
|
|
660
|
+
self.embeddings.values(), self.input_dist_params
|
|
661
|
+
):
|
|
662
|
+
|
|
663
|
+
embedding_ctx = embedding.create_context()
|
|
664
|
+
ctx.embedding_contexts.append(embedding_ctx)
|
|
665
|
+
kjt_param, wkjt_param = input_dist_params
|
|
666
|
+
if kjt_param and wkjt_param:
|
|
667
|
+
input_dists.append(
|
|
668
|
+
embedding.input_dist(
|
|
669
|
+
embedding_ctx,
|
|
670
|
+
sparse_features.id_list_features,
|
|
671
|
+
sparse_features.id_score_list_features,
|
|
672
|
+
)
|
|
673
|
+
)
|
|
674
|
+
elif kjt_param:
|
|
675
|
+
input_dists.append(
|
|
676
|
+
embedding.input_dist(
|
|
677
|
+
embedding_ctx, sparse_features.id_list_features
|
|
678
|
+
)
|
|
679
|
+
)
|
|
680
|
+
else:
|
|
681
|
+
input_dists.append(
|
|
682
|
+
embedding.input_dist(
|
|
683
|
+
embedding_ctx, sparse_features.id_score_list_features
|
|
684
|
+
)
|
|
685
|
+
)
|
|
686
|
+
return SparseFeaturesListAwaitable(input_dists)
|
|
687
|
+
|
|
688
|
+
# pyre-ignore [14]
|
|
689
|
+
def compute(
|
|
690
|
+
self, ctx: EmbeddingTowerCollectionContext, dist_input: SparseFeaturesList
|
|
691
|
+
) -> torch.Tensor:
|
|
692
|
+
|
|
693
|
+
if self.embeddings:
|
|
694
|
+
output = torch.cat(
|
|
695
|
+
[
|
|
696
|
+
interaction(
|
|
697
|
+
embedding.compute_and_output_dist(
|
|
698
|
+
embedding_ctx, embedding_input
|
|
699
|
+
)
|
|
700
|
+
)
|
|
701
|
+
for embedding_ctx, embedding, interaction, embedding_input in zip(
|
|
702
|
+
ctx.embedding_contexts,
|
|
703
|
+
self.embeddings.values(),
|
|
704
|
+
self.interactions.values(),
|
|
705
|
+
dist_input,
|
|
706
|
+
)
|
|
707
|
+
],
|
|
708
|
+
dim=1,
|
|
709
|
+
)
|
|
710
|
+
|
|
711
|
+
else:
|
|
712
|
+
output = torch.empty(
|
|
713
|
+
[self._cross_pg_global_batch_size, 0],
|
|
714
|
+
device=self._device,
|
|
715
|
+
requires_grad=True,
|
|
716
|
+
)
|
|
717
|
+
|
|
718
|
+
return output
|
|
719
|
+
|
|
720
|
+
def _create_output_dist(self, output: torch.Tensor) -> None:
|
|
721
|
+
# Determine the output_dist splits and the all_to_all output size
|
|
722
|
+
assert len(output.shape) == 2
|
|
723
|
+
local_dim_sum = torch.tensor(
|
|
724
|
+
[
|
|
725
|
+
output.shape[1],
|
|
726
|
+
],
|
|
727
|
+
dtype=torch.int64,
|
|
728
|
+
device=self._device,
|
|
729
|
+
)
|
|
730
|
+
dim_sum_per_rank = [
|
|
731
|
+
torch.zeros(
|
|
732
|
+
1,
|
|
733
|
+
dtype=torch.int64,
|
|
734
|
+
device=self._device,
|
|
735
|
+
)
|
|
736
|
+
for i in range(dist.get_world_size(self._cross_pg))
|
|
737
|
+
]
|
|
738
|
+
dist.all_gather(
|
|
739
|
+
dim_sum_per_rank,
|
|
740
|
+
local_dim_sum,
|
|
741
|
+
group=self._cross_pg,
|
|
742
|
+
)
|
|
743
|
+
dim_sum_per_rank = [x.item() for x in dim_sum_per_rank]
|
|
744
|
+
self._output_dist = PooledEmbeddingsAllToAll(
|
|
745
|
+
# pyre-fixme[6]: For 1st param expected `ProcessGroup` but got
|
|
746
|
+
# `Optional[ProcessGroup]`.
|
|
747
|
+
pg=self._cross_pg,
|
|
748
|
+
# pyre-fixme[6]: For 2nd param expected `List[int]` but got
|
|
749
|
+
# `List[Union[bool, float, int]]`.
|
|
750
|
+
dim_sum_per_rank=dim_sum_per_rank,
|
|
751
|
+
device=self._device,
|
|
752
|
+
)
|
|
753
|
+
|
|
754
|
+
# pyre-ignore [14]
|
|
755
|
+
def output_dist(
|
|
756
|
+
self, ctx: EmbeddingTowerCollectionContext, output: torch.Tensor
|
|
757
|
+
) -> LazyAwaitable[torch.Tensor]:
|
|
758
|
+
if self._has_uninitialized_output_dist:
|
|
759
|
+
self._create_output_dist(output)
|
|
760
|
+
self._has_uninitialized_output_dist = False
|
|
761
|
+
# pyre-ignore [29]
|
|
762
|
+
return TowerLazyAwaitable(self._output_dist(output))
|
|
763
|
+
|
|
764
|
+
def create_context(self) -> EmbeddingTowerCollectionContext:
|
|
765
|
+
return EmbeddingTowerCollectionContext(embedding_contexts=[])
|
|
766
|
+
|
|
767
|
+
# pyre-ignore [14]
|
|
768
|
+
def state_dict(
|
|
769
|
+
self,
|
|
770
|
+
destination: Optional[Dict[str, Any]] = None,
|
|
771
|
+
prefix: str = "",
|
|
772
|
+
keep_vars: bool = False,
|
|
773
|
+
) -> Dict[str, Any]:
|
|
774
|
+
if destination is None:
|
|
775
|
+
destination = OrderedDict()
|
|
776
|
+
# pyre-ignore [16]
|
|
777
|
+
destination._metadata = OrderedDict()
|
|
778
|
+
for i, embedding in self.embeddings.items():
|
|
779
|
+
embedding.state_dict(
|
|
780
|
+
destination, prefix + f"towers.{i}.embedding.", keep_vars
|
|
781
|
+
)
|
|
782
|
+
for i, interaction in self.interactions.items():
|
|
783
|
+
interaction.module.state_dict(
|
|
784
|
+
destination, prefix + f"towers.{i}.interaction.", keep_vars
|
|
785
|
+
)
|
|
786
|
+
return destination
|
|
787
|
+
|
|
788
|
+
@property
|
|
789
|
+
def fused_optimizer(self) -> KeyedOptimizer:
|
|
790
|
+
return CombinedOptimizer(
|
|
791
|
+
[
|
|
792
|
+
(f"towers.{tower_index}.embedding", embedding.fused_optimizer)
|
|
793
|
+
for tower_index, embedding in self.embeddings.items()
|
|
794
|
+
],
|
|
795
|
+
)
|
|
796
|
+
|
|
797
|
+
def named_parameters(
|
|
798
|
+
self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
|
|
799
|
+
) -> Iterator[Tuple[str, nn.Parameter]]:
|
|
800
|
+
for i, embedding in self.embeddings.items():
|
|
801
|
+
yield from (
|
|
802
|
+
embedding.named_parameters(
|
|
803
|
+
append_prefix(prefix, f"towers.{i}.embedding"), recurse
|
|
804
|
+
)
|
|
805
|
+
)
|
|
806
|
+
for i, interaction in self.interactions.items():
|
|
807
|
+
yield from (
|
|
808
|
+
interaction.module.named_parameters(
|
|
809
|
+
append_prefix(prefix, f"towers.{i}.interaction"), recurse
|
|
810
|
+
)
|
|
811
|
+
)
|
|
812
|
+
|
|
813
|
+
def named_buffers(
|
|
814
|
+
self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
|
|
815
|
+
) -> Iterator[Tuple[str, torch.Tensor]]:
|
|
816
|
+
for i, embedding in self.embeddings.items():
|
|
817
|
+
yield from (
|
|
818
|
+
embedding.named_buffers(
|
|
819
|
+
append_prefix(prefix, f"towers.{i}.embedding"), recurse
|
|
820
|
+
)
|
|
821
|
+
)
|
|
822
|
+
for i, interaction in self.interactions.items():
|
|
823
|
+
yield from (
|
|
824
|
+
interaction.module.named_buffers(
|
|
825
|
+
append_prefix(prefix, f"towers.{i}.interaction"), recurse
|
|
826
|
+
)
|
|
827
|
+
)
|
|
828
|
+
|
|
829
|
+
def sparse_grad_parameter_names(
|
|
830
|
+
self,
|
|
831
|
+
destination: Optional[List[str]] = None,
|
|
832
|
+
prefix: str = "",
|
|
833
|
+
) -> List[str]:
|
|
834
|
+
destination = [] if destination is None else destination
|
|
835
|
+
for i, embedding in self.embeddings.items():
|
|
836
|
+
embedding.sparse_grad_parameter_names(
|
|
837
|
+
destination, append_prefix(prefix, f"towers.{i}.embedding")
|
|
838
|
+
)
|
|
839
|
+
return destination
|
|
840
|
+
|
|
841
|
+
def sharded_parameter_names(self, prefix: str = "") -> Iterator[str]:
|
|
842
|
+
for i, embedding in self.embeddings.items():
|
|
843
|
+
yield from (
|
|
844
|
+
embedding.sharded_parameter_names(
|
|
845
|
+
append_prefix(prefix, f"towers.{i}.embedding")
|
|
846
|
+
)
|
|
847
|
+
)
|
|
848
|
+
for i, interaction in self.interactions.items():
|
|
849
|
+
yield from (
|
|
850
|
+
key
|
|
851
|
+
for key, _ in interaction.module.named_parameters(
|
|
852
|
+
append_prefix(prefix, f"towers.{i}.interaction")
|
|
853
|
+
)
|
|
854
|
+
)
|
|
855
|
+
|
|
856
|
+
def named_modules(
|
|
857
|
+
self,
|
|
858
|
+
memo: Optional[Set[nn.Module]] = None,
|
|
859
|
+
prefix: str = "",
|
|
860
|
+
remove_duplicate: bool = True,
|
|
861
|
+
) -> Iterator[Tuple[str, nn.Module]]:
|
|
862
|
+
yield from [(prefix, self)]
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
class EmbeddingTowerSharder(BaseEmbeddingSharder[EmbeddingTower]):
|
|
866
|
+
def shard(
|
|
867
|
+
self,
|
|
868
|
+
module: EmbeddingTower,
|
|
869
|
+
params: Dict[str, ParameterSharding],
|
|
870
|
+
env: ShardingEnv,
|
|
871
|
+
device: Optional[torch.device] = None,
|
|
872
|
+
) -> ShardedEmbeddingTower:
|
|
873
|
+
kjt_features, wkjt_features = self.embedding_feature_names(module)
|
|
874
|
+
|
|
875
|
+
return ShardedEmbeddingTower(
|
|
876
|
+
module=module,
|
|
877
|
+
table_name_to_parameter_sharding=params,
|
|
878
|
+
embedding_sharder=self.embedding_sharder(module),
|
|
879
|
+
kjt_features=kjt_features,
|
|
880
|
+
wkjt_features=wkjt_features,
|
|
881
|
+
env=env,
|
|
882
|
+
fused_params=self.fused_params,
|
|
883
|
+
device=device,
|
|
884
|
+
)
|
|
885
|
+
|
|
886
|
+
def sharding_types(self, compute_device_type: str) -> List[str]:
|
|
887
|
+
"""
|
|
888
|
+
List of supported sharding types. See ShardingType for well-known examples.
|
|
889
|
+
"""
|
|
890
|
+
return [
|
|
891
|
+
ShardingType.TABLE_ROW_WISE.value,
|
|
892
|
+
ShardingType.TABLE_COLUMN_WISE.value,
|
|
893
|
+
]
|
|
894
|
+
|
|
895
|
+
def shardable_parameters(self, module: EmbeddingTower) -> Dict[str, nn.Parameter]:
|
|
896
|
+
"""
|
|
897
|
+
List of parameters, which can be sharded.
|
|
898
|
+
"""
|
|
899
|
+
return self.embedding_sharder(module).shardable_parameters(module.embedding)
|
|
900
|
+
|
|
901
|
+
@property
|
|
902
|
+
def module_type(self) -> Type[EmbeddingTower]:
|
|
903
|
+
return EmbeddingTower
|
|
904
|
+
|
|
905
|
+
def embedding_sharder(
|
|
906
|
+
self, module: EmbeddingTower
|
|
907
|
+
) -> BaseEmbeddingSharder[nn.Module]:
|
|
908
|
+
embedding: nn.Module = module.embedding
|
|
909
|
+
if isinstance(embedding, EmbeddingBagCollection):
|
|
910
|
+
# pyre-ignore [7]
|
|
911
|
+
return EmbeddingBagCollectionSharder(self.fused_params)
|
|
912
|
+
elif isinstance(embedding, EmbeddingCollection):
|
|
913
|
+
# pyre-ignore [7]
|
|
914
|
+
return EmbeddingCollectionSharder(self.fused_params)
|
|
915
|
+
else:
|
|
916
|
+
raise RuntimeError(f"Unsupported embedding type: {type(module)}")
|
|
917
|
+
|
|
918
|
+
def embedding_feature_names(
|
|
919
|
+
self, module: EmbeddingTower
|
|
920
|
+
) -> Tuple[List[str], List[str]]:
|
|
921
|
+
embedding: nn.Module = module.embedding
|
|
922
|
+
if not (
|
|
923
|
+
isinstance(embedding, EmbeddingBagCollection)
|
|
924
|
+
or isinstance(embedding, EmbeddingCollection)
|
|
925
|
+
):
|
|
926
|
+
raise RuntimeError(f"unsupported embedding type: {type(module)}")
|
|
927
|
+
|
|
928
|
+
kjt_features: List[str] = []
|
|
929
|
+
wkjt_features: List[str] = []
|
|
930
|
+
configs = []
|
|
931
|
+
|
|
932
|
+
weighted = False
|
|
933
|
+
if isinstance(embedding, EmbeddingBagCollection):
|
|
934
|
+
configs = embedding.embedding_bag_configs
|
|
935
|
+
weighted = embedding.is_weighted
|
|
936
|
+
elif isinstance(embedding, EmbeddingCollection):
|
|
937
|
+
configs = embedding.embedding_configs
|
|
938
|
+
|
|
939
|
+
for config in configs:
|
|
940
|
+
if getattr(config, "weighted", weighted):
|
|
941
|
+
wkjt_features.extend(config.feature_names)
|
|
942
|
+
else:
|
|
943
|
+
kjt_features.extend(config.feature_names)
|
|
944
|
+
return kjt_features, wkjt_features
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
class EmbeddingTowerCollectionSharder(BaseEmbeddingSharder[EmbeddingTowerCollection]):
|
|
948
|
+
def __init__(self, fused_params: Optional[Dict[str, Any]] = None) -> None:
|
|
949
|
+
super().__init__()
|
|
950
|
+
self._tower_sharder = EmbeddingTowerSharder(self.fused_params)
|
|
951
|
+
|
|
952
|
+
def shard(
|
|
953
|
+
self,
|
|
954
|
+
module: EmbeddingTowerCollection,
|
|
955
|
+
params: Dict[str, ParameterSharding],
|
|
956
|
+
env: ShardingEnv,
|
|
957
|
+
device: Optional[torch.device] = None,
|
|
958
|
+
) -> ShardedEmbeddingTowerCollection:
|
|
959
|
+
|
|
960
|
+
return ShardedEmbeddingTowerCollection(
|
|
961
|
+
module=module,
|
|
962
|
+
table_name_to_parameter_sharding=params,
|
|
963
|
+
tower_sharder=self._tower_sharder,
|
|
964
|
+
env=env,
|
|
965
|
+
fused_params=self.fused_params,
|
|
966
|
+
device=device,
|
|
967
|
+
)
|
|
968
|
+
|
|
969
|
+
def sharding_types(self, compute_device_type: str) -> List[str]:
|
|
970
|
+
"""
|
|
971
|
+
List of supported sharding types. See ShardingType for well-known examples.
|
|
972
|
+
"""
|
|
973
|
+
return [
|
|
974
|
+
ShardingType.TABLE_ROW_WISE.value,
|
|
975
|
+
ShardingType.TABLE_COLUMN_WISE.value,
|
|
976
|
+
]
|
|
977
|
+
|
|
978
|
+
def shardable_parameters(
|
|
979
|
+
self, module: EmbeddingTowerCollection
|
|
980
|
+
) -> Dict[str, nn.Parameter]:
|
|
981
|
+
"""
|
|
982
|
+
List of parameters, which can be sharded.
|
|
983
|
+
"""
|
|
984
|
+
|
|
985
|
+
named_parameters: Dict[str, nn.Parameter] = {}
|
|
986
|
+
for tower in module.towers:
|
|
987
|
+
named_parameters.update(self._tower_sharder.shardable_parameters(tower))
|
|
988
|
+
return named_parameters
|
|
989
|
+
|
|
990
|
+
@property
|
|
991
|
+
def module_type(self) -> Type[EmbeddingTowerCollection]:
|
|
992
|
+
return EmbeddingTowerCollection
|