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,353 @@
|
|
|
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 math
|
|
9
|
+
from typing import Dict, List, Optional, Tuple, Union
|
|
10
|
+
|
|
11
|
+
import torch
|
|
12
|
+
from torch import nn
|
|
13
|
+
from torchrec.distributed.embedding_types import EmbeddingComputeKernel
|
|
14
|
+
from torchrec.distributed.planner.constants import MIN_CW_DIM, POOLING_FACTOR
|
|
15
|
+
from torchrec.distributed.planner.shard_estimators import (
|
|
16
|
+
EmbeddingPerfEstimator,
|
|
17
|
+
EmbeddingStorageEstimator,
|
|
18
|
+
)
|
|
19
|
+
from torchrec.distributed.planner.types import (
|
|
20
|
+
Enumerator,
|
|
21
|
+
ParameterConstraints,
|
|
22
|
+
PartitionByType,
|
|
23
|
+
Shard,
|
|
24
|
+
ShardEstimator,
|
|
25
|
+
ShardingOption,
|
|
26
|
+
Topology,
|
|
27
|
+
)
|
|
28
|
+
from torchrec.distributed.planner.utils import sharder_name
|
|
29
|
+
from torchrec.distributed.types import ModuleSharder, ShardingType
|
|
30
|
+
from torchrec.modules.embedding_tower import EmbeddingTower, EmbeddingTowerCollection
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class EmbeddingEnumerator(Enumerator):
|
|
34
|
+
"""
|
|
35
|
+
Generates embedding sharding options for given `nn.Module`, considering user provided
|
|
36
|
+
constraints.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
topology (Topology): device topology.
|
|
40
|
+
constraints (Optional[Dict[str, ParameterConstraints]]): dict of parameter names
|
|
41
|
+
to provided ParameterConstraints.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
topology: Topology,
|
|
47
|
+
constraints: Optional[Dict[str, ParameterConstraints]] = None,
|
|
48
|
+
estimator: Optional[Union[ShardEstimator, List[ShardEstimator]]] = None,
|
|
49
|
+
) -> None:
|
|
50
|
+
self._compute_device: str = topology.compute_device
|
|
51
|
+
self._world_size: int = topology.world_size
|
|
52
|
+
self._local_world_size: int = topology.local_world_size
|
|
53
|
+
self._constraints = constraints
|
|
54
|
+
self._batch_size: int = topology.batch_size
|
|
55
|
+
|
|
56
|
+
if estimator:
|
|
57
|
+
self._estimators: List[ShardEstimator] = (
|
|
58
|
+
[estimator] if not isinstance(estimator, list) else estimator
|
|
59
|
+
)
|
|
60
|
+
else:
|
|
61
|
+
self._estimators: List[ShardEstimator] = [
|
|
62
|
+
EmbeddingPerfEstimator(topology=topology, constraints=constraints),
|
|
63
|
+
EmbeddingStorageEstimator(topology=topology, constraints=constraints),
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
def enumerate(
|
|
67
|
+
self,
|
|
68
|
+
module: nn.Module,
|
|
69
|
+
sharders: List[ModuleSharder[nn.Module]],
|
|
70
|
+
) -> List[ShardingOption]:
|
|
71
|
+
"""
|
|
72
|
+
Generates relevant sharding options given module and sharders.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
module (nn.Module): module to be sharded.
|
|
76
|
+
sharders (List[ModuleSharder[nn.Module]]): provided sharders for module.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
List[ShardingOption]: valid sharding options with values populated.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
sharder_map: Dict[str, ModuleSharder[nn.Module]] = {
|
|
83
|
+
sharder_name(sharder.module_type): sharder for sharder in sharders
|
|
84
|
+
}
|
|
85
|
+
sharding_options: List[ShardingOption] = []
|
|
86
|
+
|
|
87
|
+
named_modules_queue = [("", module)]
|
|
88
|
+
while named_modules_queue:
|
|
89
|
+
child_path, child_module = named_modules_queue.pop()
|
|
90
|
+
sharder_key = sharder_name(type(child_module))
|
|
91
|
+
sharder = sharder_map.get(sharder_key, None)
|
|
92
|
+
if not sharder:
|
|
93
|
+
for n, m in child_module.named_children():
|
|
94
|
+
if child_path != "":
|
|
95
|
+
named_modules_queue.append((child_path + "." + n, m))
|
|
96
|
+
else:
|
|
97
|
+
named_modules_queue.append((n, m))
|
|
98
|
+
continue
|
|
99
|
+
|
|
100
|
+
for name, param in sharder.shardable_parameters(child_module).items():
|
|
101
|
+
for sharding_type in self._filter_sharding_types(
|
|
102
|
+
name, sharder.sharding_types(self._compute_device)
|
|
103
|
+
):
|
|
104
|
+
for compute_kernel in self._filter_compute_kernels(
|
|
105
|
+
name,
|
|
106
|
+
sharder.compute_kernels(sharding_type, self._compute_device),
|
|
107
|
+
):
|
|
108
|
+
|
|
109
|
+
input_lengths = (
|
|
110
|
+
self._constraints[name].pooling_factors
|
|
111
|
+
if self._constraints and self._constraints.get(name)
|
|
112
|
+
else [POOLING_FACTOR]
|
|
113
|
+
)
|
|
114
|
+
col_wise_shard_dim = (
|
|
115
|
+
self._constraints[name].min_partition
|
|
116
|
+
if self._constraints and self._constraints.get(name)
|
|
117
|
+
else None
|
|
118
|
+
)
|
|
119
|
+
(
|
|
120
|
+
shard_sizes,
|
|
121
|
+
shard_offsets,
|
|
122
|
+
) = calculate_shard_sizes_and_offsets(
|
|
123
|
+
tensor=param,
|
|
124
|
+
world_size=self._world_size,
|
|
125
|
+
local_world_size=self._local_world_size,
|
|
126
|
+
sharding_type=sharding_type,
|
|
127
|
+
col_wise_shard_dim=col_wise_shard_dim,
|
|
128
|
+
)
|
|
129
|
+
dependency = None
|
|
130
|
+
if isinstance(child_module, EmbeddingTower):
|
|
131
|
+
dependency = child_path
|
|
132
|
+
elif isinstance(child_module, EmbeddingTowerCollection):
|
|
133
|
+
tower_index = _get_tower_index(name, child_module)
|
|
134
|
+
dependency = child_path + ".tower_" + str(tower_index)
|
|
135
|
+
sharding_options.append(
|
|
136
|
+
ShardingOption(
|
|
137
|
+
name=name,
|
|
138
|
+
tensor=param,
|
|
139
|
+
module=(child_path, child_module),
|
|
140
|
+
upstream_modules=[],
|
|
141
|
+
downstream_modules=[],
|
|
142
|
+
input_lengths=input_lengths,
|
|
143
|
+
batch_size=self._batch_size,
|
|
144
|
+
compute_kernel=compute_kernel,
|
|
145
|
+
sharding_type=sharding_type,
|
|
146
|
+
partition_by=get_partition_by_type(sharding_type),
|
|
147
|
+
shards=[
|
|
148
|
+
Shard(size=size, offset=offset)
|
|
149
|
+
for size, offset in zip(shard_sizes, shard_offsets)
|
|
150
|
+
],
|
|
151
|
+
dependency=dependency,
|
|
152
|
+
)
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
for estimator in self._estimators:
|
|
156
|
+
estimator.estimate(sharding_options, sharder_map)
|
|
157
|
+
|
|
158
|
+
return sharding_options
|
|
159
|
+
|
|
160
|
+
def _filter_sharding_types(self, name: str, sharding_types: List[str]) -> List[str]:
|
|
161
|
+
if not self._constraints or not self._constraints.get(name):
|
|
162
|
+
return sharding_types
|
|
163
|
+
constraints: ParameterConstraints = self._constraints[name]
|
|
164
|
+
if not constraints.sharding_types:
|
|
165
|
+
return sharding_types
|
|
166
|
+
constrained_sharding_types: List[str] = constraints.sharding_types
|
|
167
|
+
|
|
168
|
+
sharding_types = list(set(constrained_sharding_types) & set(sharding_types))
|
|
169
|
+
|
|
170
|
+
if not sharding_types:
|
|
171
|
+
raise RuntimeError(
|
|
172
|
+
f"No available sharding types after applying user provided constraints for {name}"
|
|
173
|
+
)
|
|
174
|
+
return sharding_types
|
|
175
|
+
|
|
176
|
+
def _filter_compute_kernels(
|
|
177
|
+
self,
|
|
178
|
+
name: str,
|
|
179
|
+
compute_kernels: List[str],
|
|
180
|
+
) -> List[str]:
|
|
181
|
+
|
|
182
|
+
if not self._constraints or not self._constraints.get(name):
|
|
183
|
+
filtered_compute_kernels = compute_kernels
|
|
184
|
+
else:
|
|
185
|
+
constraints: ParameterConstraints = self._constraints[name]
|
|
186
|
+
if not constraints.compute_kernels:
|
|
187
|
+
filtered_compute_kernels = compute_kernels
|
|
188
|
+
else:
|
|
189
|
+
constrained_compute_kernels: List[str] = constraints.compute_kernels
|
|
190
|
+
filtered_compute_kernels = list(
|
|
191
|
+
set(constrained_compute_kernels) & set(compute_kernels)
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
if EmbeddingComputeKernel.DENSE.value in filtered_compute_kernels:
|
|
195
|
+
if (
|
|
196
|
+
EmbeddingComputeKernel.FUSED.value in filtered_compute_kernels
|
|
197
|
+
): # always false for data_parallel
|
|
198
|
+
filtered_compute_kernels.remove(EmbeddingComputeKernel.DENSE.value)
|
|
199
|
+
|
|
200
|
+
if not filtered_compute_kernels:
|
|
201
|
+
raise RuntimeError(
|
|
202
|
+
f"No available compute kernels after applying user provided constraints for {name}"
|
|
203
|
+
)
|
|
204
|
+
return filtered_compute_kernels
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def get_partition_by_type(sharding_type: str) -> str:
|
|
208
|
+
"""
|
|
209
|
+
Gets corresponding partition by type for provided sharding type.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
sharding_type (str): sharding type string.
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
str: the corresponding `PartitionByType` value.
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
device_sharding_types = {
|
|
219
|
+
ShardingType.TABLE_WISE.value,
|
|
220
|
+
ShardingType.COLUMN_WISE.value,
|
|
221
|
+
}
|
|
222
|
+
host_sharding_types = {
|
|
223
|
+
ShardingType.TABLE_ROW_WISE.value,
|
|
224
|
+
ShardingType.TABLE_COLUMN_WISE.value,
|
|
225
|
+
}
|
|
226
|
+
uniform_sharding_types = {
|
|
227
|
+
ShardingType.ROW_WISE.value,
|
|
228
|
+
ShardingType.DATA_PARALLEL.value,
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if sharding_type in device_sharding_types:
|
|
232
|
+
return PartitionByType.DEVICE.value
|
|
233
|
+
elif sharding_type in host_sharding_types:
|
|
234
|
+
return PartitionByType.HOST.value
|
|
235
|
+
elif sharding_type in uniform_sharding_types:
|
|
236
|
+
return PartitionByType.UNIFORM.value
|
|
237
|
+
|
|
238
|
+
raise ValueError(
|
|
239
|
+
f"Unrecognized or unsupported sharding type provided: {sharding_type}"
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def calculate_shard_sizes_and_offsets(
|
|
244
|
+
tensor: torch.Tensor,
|
|
245
|
+
world_size: int,
|
|
246
|
+
local_world_size: int,
|
|
247
|
+
sharding_type: str,
|
|
248
|
+
col_wise_shard_dim: Optional[int] = None,
|
|
249
|
+
) -> Tuple[List[List[int]], List[List[int]]]:
|
|
250
|
+
"""
|
|
251
|
+
Calculates sizes and offsets for tensor sharded according to provided sharding type.
|
|
252
|
+
|
|
253
|
+
Args:
|
|
254
|
+
tensor (torch.Tensor): tensor to be sharded.
|
|
255
|
+
world_size (int): total number of devices in topology.
|
|
256
|
+
local_world_size (int): total number of devices in host group topology.
|
|
257
|
+
sharding_type (str): provided ShardingType value.
|
|
258
|
+
col_wise_shard_dim (Optional[int]): dimension for column wise sharding split.
|
|
259
|
+
|
|
260
|
+
Returns:
|
|
261
|
+
Tuple[List[List[int]], List[List[int]]]: shard sizes, represented as a list of the dimensions of the sharded tensor on each device, and shard offsets, represented as a list of coordinates of placement on each device.
|
|
262
|
+
|
|
263
|
+
Raises:
|
|
264
|
+
ValueError: If `sharding_type` is not a valid ShardingType.
|
|
265
|
+
"""
|
|
266
|
+
|
|
267
|
+
(rows, columns) = tensor.shape
|
|
268
|
+
|
|
269
|
+
if sharding_type == ShardingType.DATA_PARALLEL.value:
|
|
270
|
+
return [[rows, columns]] * world_size, [[0, 0]] * world_size
|
|
271
|
+
elif sharding_type == ShardingType.TABLE_WISE.value:
|
|
272
|
+
return [[rows, columns]], [[0, 0]]
|
|
273
|
+
elif sharding_type == ShardingType.ROW_WISE.value:
|
|
274
|
+
return _calculate_rw_shard_sizes_and_offsets(rows, world_size, columns)
|
|
275
|
+
elif sharding_type == ShardingType.TABLE_ROW_WISE.value:
|
|
276
|
+
return _calculate_rw_shard_sizes_and_offsets(rows, local_world_size, columns)
|
|
277
|
+
elif (
|
|
278
|
+
sharding_type == ShardingType.COLUMN_WISE.value
|
|
279
|
+
or sharding_type == ShardingType.TABLE_COLUMN_WISE.value
|
|
280
|
+
):
|
|
281
|
+
return _calculate_cw_shard_sizes_and_offsets(columns, rows, col_wise_shard_dim)
|
|
282
|
+
|
|
283
|
+
raise ValueError(
|
|
284
|
+
f"Unrecognized or unsupported sharding type provided: {sharding_type}"
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _calculate_rw_shard_sizes_and_offsets(
|
|
289
|
+
hash_size: int, num_devices: int, columns: int
|
|
290
|
+
) -> Tuple[List[List[int]], List[List[int]]]:
|
|
291
|
+
"""
|
|
292
|
+
Sets prefix of shard_sizes to be ceil(hash_size/num_devices).
|
|
293
|
+
|
|
294
|
+
For example if hash_size = 10, num_devices = 3, we will allocate the rows as 3,3,3,1
|
|
295
|
+
(rather than 3,3,2,2).
|
|
296
|
+
This is due to implementation in RW sharding that sets block_size_lists to be ceil.
|
|
297
|
+
The balanced way is harder to support on GPU.
|
|
298
|
+
For more details see https://fb.quip.com/xbgbAchCTOL0
|
|
299
|
+
|
|
300
|
+
Also consider the example of hash_size = 5, num_devices = 4. The expected rows per
|
|
301
|
+
rank is [2,2,1,0].
|
|
302
|
+
"""
|
|
303
|
+
|
|
304
|
+
block_size: int = math.ceil(hash_size / num_devices)
|
|
305
|
+
last_rank: int = hash_size // block_size
|
|
306
|
+
last_block_size: int = hash_size - block_size * last_rank
|
|
307
|
+
shard_sizes: List[List[int]] = []
|
|
308
|
+
|
|
309
|
+
for rank in range(num_devices):
|
|
310
|
+
if rank < last_rank:
|
|
311
|
+
local_row: int = block_size
|
|
312
|
+
elif rank == last_rank:
|
|
313
|
+
local_row: int = last_block_size
|
|
314
|
+
else:
|
|
315
|
+
local_row: int = 0
|
|
316
|
+
shard_sizes.append([local_row, columns])
|
|
317
|
+
shard_offsets = [[0, 0]]
|
|
318
|
+
|
|
319
|
+
for i in range(num_devices - 1):
|
|
320
|
+
shard_offsets.append([shard_sizes[i][0] + shard_offsets[i][0], 0])
|
|
321
|
+
|
|
322
|
+
return shard_sizes, shard_offsets
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _calculate_cw_shard_sizes_and_offsets(
|
|
326
|
+
hash_size: int,
|
|
327
|
+
rows: int,
|
|
328
|
+
col_wise_shard_dim: Optional[int] = None,
|
|
329
|
+
) -> Tuple[List[List[int]], List[List[int]]]:
|
|
330
|
+
block_size: int = min(
|
|
331
|
+
col_wise_shard_dim if col_wise_shard_dim else MIN_CW_DIM, hash_size
|
|
332
|
+
)
|
|
333
|
+
num_col_wise_shards, residual = divmod(hash_size, block_size)
|
|
334
|
+
|
|
335
|
+
shard_sizes: List[List[int]] = [[rows, block_size]] * (num_col_wise_shards - 1)
|
|
336
|
+
shard_sizes.append([rows, block_size + residual])
|
|
337
|
+
|
|
338
|
+
shard_offsets: List[List[int]] = [
|
|
339
|
+
[0, block_size * rank] for rank in range(num_col_wise_shards)
|
|
340
|
+
]
|
|
341
|
+
return shard_sizes, shard_offsets
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _get_tower_index(name: str, child_module: EmbeddingTowerCollection) -> int:
|
|
345
|
+
for i, tower in enumerate(child_module.towers):
|
|
346
|
+
for n, m in tower.named_modules():
|
|
347
|
+
if isinstance(m, nn.Embedding) or isinstance(m, nn.EmbeddingBag):
|
|
348
|
+
table_name = n.split(".")[-1]
|
|
349
|
+
if name == table_name:
|
|
350
|
+
return i
|
|
351
|
+
raise RuntimeError(
|
|
352
|
+
f"couldn't get the tower index for table {name}, tower collection: {child_module}"
|
|
353
|
+
)
|
|
@@ -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
|
+
import os
|
|
10
|
+
from functools import reduce
|
|
11
|
+
from multiprocessing.pool import ThreadPool as Pool
|
|
12
|
+
from time import perf_counter
|
|
13
|
+
from typing import cast, Dict, List, Optional, Tuple, Union
|
|
14
|
+
|
|
15
|
+
import numpy
|
|
16
|
+
|
|
17
|
+
import torch
|
|
18
|
+
|
|
19
|
+
import torch.distributed as dist
|
|
20
|
+
from torch import nn
|
|
21
|
+
from torchrec.distributed.collective_utils import invoke_on_rank_and_broadcast_result
|
|
22
|
+
from torchrec.distributed.planner.constants import MAX_SIZE
|
|
23
|
+
from torchrec.distributed.planner.enumerators import EmbeddingEnumerator
|
|
24
|
+
from torchrec.distributed.planner.partitioners import GreedyPerfPartitioner
|
|
25
|
+
from torchrec.distributed.planner.perf_models import NoopPerfModel
|
|
26
|
+
from torchrec.distributed.planner.proposers import (
|
|
27
|
+
GreedyProposer,
|
|
28
|
+
GridSearchProposer,
|
|
29
|
+
proposers_to_proposals_list,
|
|
30
|
+
UniformProposer,
|
|
31
|
+
)
|
|
32
|
+
from torchrec.distributed.planner.stats import EmbeddingStats
|
|
33
|
+
from torchrec.distributed.planner.storage_reservations import (
|
|
34
|
+
HeuristicalStorageReservation,
|
|
35
|
+
)
|
|
36
|
+
from torchrec.distributed.planner.types import (
|
|
37
|
+
Enumerator,
|
|
38
|
+
ParameterConstraints,
|
|
39
|
+
Partitioner,
|
|
40
|
+
PerfModel,
|
|
41
|
+
PlannerError,
|
|
42
|
+
Proposer,
|
|
43
|
+
ShardingOption,
|
|
44
|
+
Stats,
|
|
45
|
+
Storage,
|
|
46
|
+
StorageReservation,
|
|
47
|
+
Topology,
|
|
48
|
+
)
|
|
49
|
+
from torchrec.distributed.types import (
|
|
50
|
+
EnumerableShardingSpec,
|
|
51
|
+
ModuleSharder,
|
|
52
|
+
ParameterSharding,
|
|
53
|
+
ShardingPlan,
|
|
54
|
+
ShardingPlanner,
|
|
55
|
+
ShardingType,
|
|
56
|
+
ShardMetadata,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _to_sharding_plan(
|
|
61
|
+
sharding_options: List[ShardingOption],
|
|
62
|
+
topology: Topology,
|
|
63
|
+
) -> ShardingPlan:
|
|
64
|
+
def _placement(
|
|
65
|
+
compute_device: str,
|
|
66
|
+
rank: int,
|
|
67
|
+
local_size: int,
|
|
68
|
+
) -> str:
|
|
69
|
+
param_device = compute_device
|
|
70
|
+
if compute_device == "cuda":
|
|
71
|
+
param_device = torch.device("cuda", rank % local_size)
|
|
72
|
+
return f"rank:{rank}/{param_device}"
|
|
73
|
+
|
|
74
|
+
compute_device = topology.compute_device
|
|
75
|
+
local_size = topology.local_world_size
|
|
76
|
+
|
|
77
|
+
plan = {}
|
|
78
|
+
for sharding_option in sharding_options:
|
|
79
|
+
shards = sharding_option.shards
|
|
80
|
+
sharding_type = sharding_option.sharding_type
|
|
81
|
+
|
|
82
|
+
module_plan = plan.get(sharding_option.path, {})
|
|
83
|
+
module_plan[sharding_option.name] = ParameterSharding(
|
|
84
|
+
sharding_spec=None
|
|
85
|
+
if sharding_type == ShardingType.DATA_PARALLEL.value
|
|
86
|
+
else EnumerableShardingSpec(
|
|
87
|
+
[
|
|
88
|
+
ShardMetadata(
|
|
89
|
+
shard_sizes=shard.size,
|
|
90
|
+
shard_offsets=shard.offset,
|
|
91
|
+
placement=_placement(
|
|
92
|
+
compute_device, cast(int, shard.rank), local_size
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
for shard in shards
|
|
96
|
+
]
|
|
97
|
+
),
|
|
98
|
+
sharding_type=sharding_type,
|
|
99
|
+
compute_kernel=sharding_option.compute_kernel,
|
|
100
|
+
ranks=[cast(int, shard.rank) for shard in shards],
|
|
101
|
+
)
|
|
102
|
+
plan[sharding_option.path] = module_plan
|
|
103
|
+
return ShardingPlan(plan)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class ParallelizedEmbeddingShardingPlanner(ShardingPlanner):
|
|
107
|
+
"""
|
|
108
|
+
Provides an optimized sharding plan for a given module with shardable parameters
|
|
109
|
+
according to the provided sharders, topology, and constraints using multiprocessing to improve runtime and scalability.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
def __init__(
|
|
113
|
+
self,
|
|
114
|
+
topology: Topology,
|
|
115
|
+
enumerator: Optional[Enumerator] = None,
|
|
116
|
+
storage_reservation: Optional[StorageReservation] = None,
|
|
117
|
+
proposer: Optional[Union[Proposer, List[Proposer]]] = None,
|
|
118
|
+
custom_cpu_count: Optional[int] = None,
|
|
119
|
+
partitioner: Optional[Partitioner] = None,
|
|
120
|
+
performance_model: Optional[PerfModel] = None,
|
|
121
|
+
stats: Optional[Stats] = None,
|
|
122
|
+
constraints: Optional[Dict[str, ParameterConstraints]] = None,
|
|
123
|
+
debug: bool = True,
|
|
124
|
+
) -> None:
|
|
125
|
+
self._topology = topology
|
|
126
|
+
self._constraints = constraints
|
|
127
|
+
self._enumerator: Enumerator = (
|
|
128
|
+
enumerator
|
|
129
|
+
if enumerator
|
|
130
|
+
else EmbeddingEnumerator(
|
|
131
|
+
topology=topology,
|
|
132
|
+
constraints=constraints,
|
|
133
|
+
)
|
|
134
|
+
)
|
|
135
|
+
self._storage_reservation: StorageReservation = (
|
|
136
|
+
storage_reservation
|
|
137
|
+
if storage_reservation
|
|
138
|
+
else HeuristicalStorageReservation(percentage=0.15)
|
|
139
|
+
)
|
|
140
|
+
self._partitioner: Partitioner = (
|
|
141
|
+
partitioner if partitioner else GreedyPerfPartitioner()
|
|
142
|
+
)
|
|
143
|
+
if proposer:
|
|
144
|
+
self._proposers: List[Proposer] = (
|
|
145
|
+
[proposer] if not isinstance(proposer, list) else proposer
|
|
146
|
+
)
|
|
147
|
+
else:
|
|
148
|
+
self._proposers = [
|
|
149
|
+
GridSearchProposer(),
|
|
150
|
+
GreedyProposer(),
|
|
151
|
+
GreedyProposer(use_depth=False),
|
|
152
|
+
UniformProposer(),
|
|
153
|
+
]
|
|
154
|
+
self._perf_model: PerfModel = (
|
|
155
|
+
performance_model if performance_model else NoopPerfModel(topology=topology)
|
|
156
|
+
)
|
|
157
|
+
self._stats: Stats = stats if stats else EmbeddingStats()
|
|
158
|
+
self._debug = debug
|
|
159
|
+
self._num_proposals: int = 0
|
|
160
|
+
self._num_plans: int = 0
|
|
161
|
+
self._cpu_count: Optional[int] = (
|
|
162
|
+
custom_cpu_count if custom_cpu_count else os.cpu_count()
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
def collective_plan(
|
|
166
|
+
self,
|
|
167
|
+
module: nn.Module,
|
|
168
|
+
sharders: List[ModuleSharder[nn.Module]],
|
|
169
|
+
pg: dist.ProcessGroup,
|
|
170
|
+
) -> ShardingPlan:
|
|
171
|
+
"""
|
|
172
|
+
Call self.plan(...) on rank 0 and broadcast
|
|
173
|
+
"""
|
|
174
|
+
return invoke_on_rank_and_broadcast_result(
|
|
175
|
+
pg,
|
|
176
|
+
0,
|
|
177
|
+
self.plan,
|
|
178
|
+
module,
|
|
179
|
+
sharders,
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
def plan(
|
|
183
|
+
self,
|
|
184
|
+
module: nn.Module,
|
|
185
|
+
sharders: List[ModuleSharder[nn.Module]],
|
|
186
|
+
) -> ShardingPlan:
|
|
187
|
+
|
|
188
|
+
self._num_proposals = 0
|
|
189
|
+
self._num_plans = 0
|
|
190
|
+
start_time = perf_counter()
|
|
191
|
+
|
|
192
|
+
storage_constraint: Topology = self._storage_reservation.reserve(
|
|
193
|
+
topology=self._topology,
|
|
194
|
+
module=module,
|
|
195
|
+
sharders=sharders,
|
|
196
|
+
constraints=self._constraints,
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
search_space = self._enumerator.enumerate(
|
|
200
|
+
module=module,
|
|
201
|
+
sharders=sharders,
|
|
202
|
+
)
|
|
203
|
+
if not search_space:
|
|
204
|
+
# No shardable parameters
|
|
205
|
+
return ShardingPlan({})
|
|
206
|
+
|
|
207
|
+
proposals_list = proposers_to_proposals_list(
|
|
208
|
+
self._proposers, search_space=search_space
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
self._num_proposals = len(proposals_list)
|
|
212
|
+
|
|
213
|
+
def get_best_plan(
|
|
214
|
+
proposal_group: List[List[ShardingOption]],
|
|
215
|
+
) -> Tuple[Optional[List[ShardingOption]], float, Storage, int]:
|
|
216
|
+
|
|
217
|
+
group_plans_num = 0
|
|
218
|
+
lowest_storage = Storage(MAX_SIZE, MAX_SIZE)
|
|
219
|
+
best_perf_rating = MAX_SIZE
|
|
220
|
+
best_plan = None
|
|
221
|
+
|
|
222
|
+
for proposal in proposal_group:
|
|
223
|
+
try:
|
|
224
|
+
plan = self._partitioner.partition(
|
|
225
|
+
proposal=proposal,
|
|
226
|
+
storage_constraint=storage_constraint,
|
|
227
|
+
)
|
|
228
|
+
group_plans_num += 1
|
|
229
|
+
perf_rating = self._perf_model.rate(plan=plan)
|
|
230
|
+
|
|
231
|
+
if perf_rating < best_perf_rating:
|
|
232
|
+
best_perf_rating = perf_rating
|
|
233
|
+
best_plan = plan
|
|
234
|
+
|
|
235
|
+
except PlannerError:
|
|
236
|
+
current_storage = cast(
|
|
237
|
+
Storage,
|
|
238
|
+
reduce(
|
|
239
|
+
lambda x, y: x + y,
|
|
240
|
+
[
|
|
241
|
+
shard.storage
|
|
242
|
+
for option in proposal
|
|
243
|
+
for shard in option.shards
|
|
244
|
+
],
|
|
245
|
+
),
|
|
246
|
+
)
|
|
247
|
+
if current_storage < lowest_storage:
|
|
248
|
+
lowest_storage = current_storage
|
|
249
|
+
|
|
250
|
+
return (best_plan, best_perf_rating, lowest_storage, group_plans_num)
|
|
251
|
+
|
|
252
|
+
grouped_proposals = numpy.array_split(proposals_list, self._cpu_count)
|
|
253
|
+
|
|
254
|
+
pool = Pool(self._cpu_count)
|
|
255
|
+
group_best_plans = pool.map(get_best_plan, grouped_proposals)
|
|
256
|
+
pool.close()
|
|
257
|
+
pool.join()
|
|
258
|
+
|
|
259
|
+
lowest_storage = Storage(MAX_SIZE, MAX_SIZE)
|
|
260
|
+
best_perf_rating = MAX_SIZE
|
|
261
|
+
best_plan = None
|
|
262
|
+
|
|
263
|
+
for plan_info in group_best_plans:
|
|
264
|
+
current_plan = plan_info[0]
|
|
265
|
+
plan_perf_rating = plan_info[1]
|
|
266
|
+
plan_storage = plan_info[2]
|
|
267
|
+
self._num_plans += plan_info[3]
|
|
268
|
+
if plan_perf_rating < best_perf_rating:
|
|
269
|
+
best_plan = current_plan
|
|
270
|
+
best_perf_rating = plan_perf_rating
|
|
271
|
+
if plan_storage < lowest_storage:
|
|
272
|
+
lowest_storage = plan_storage
|
|
273
|
+
|
|
274
|
+
if best_plan is not None:
|
|
275
|
+
sharding_plan = _to_sharding_plan(best_plan, self._topology)
|
|
276
|
+
end_time = perf_counter()
|
|
277
|
+
self._stats.log(
|
|
278
|
+
sharding_plan=sharding_plan,
|
|
279
|
+
topology=self._topology,
|
|
280
|
+
storage_reservation=self._storage_reservation,
|
|
281
|
+
num_proposals=self._num_proposals,
|
|
282
|
+
num_plans=self._num_plans,
|
|
283
|
+
run_time=end_time - start_time,
|
|
284
|
+
best_plan=best_plan,
|
|
285
|
+
debug=self._debug,
|
|
286
|
+
)
|
|
287
|
+
return sharding_plan
|
|
288
|
+
else:
|
|
289
|
+
global_storage_capacity = reduce(
|
|
290
|
+
lambda x, y: x + y,
|
|
291
|
+
[device.storage for device in self._topology.devices],
|
|
292
|
+
)
|
|
293
|
+
global_storage_constraints = reduce(
|
|
294
|
+
lambda x, y: x + y,
|
|
295
|
+
[device.storage for device in storage_constraint.devices],
|
|
296
|
+
)
|
|
297
|
+
raise PlannerError(
|
|
298
|
+
f"Unable to find a plan for this model that evaluates {self._num_proposals} proposals."
|
|
299
|
+
"\nPossible solutions:"
|
|
300
|
+
f"\n 1) Increase the number of devices ({self._topology.world_size})"
|
|
301
|
+
f"\n 2) Reduce the model size ("
|
|
302
|
+
f"\n\t Global storage: {global_storage_capacity.hbm}, "
|
|
303
|
+
f"\n\t Available for model parallel: {global_storage_constraints},"
|
|
304
|
+
f"\n\t Requirement for model parallel: {lowest_storage})"
|
|
305
|
+
f"\n 3) Reduce local batch size ({self._topology.batch_size})"
|
|
306
|
+
"\n 4) Remove planner constraints that might be reducing search space or available storage\n"
|
|
307
|
+
)
|