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.
Files changed (167) hide show
  1. examples/__init__.py +0 -0
  2. examples/datasets/__init__.py +8 -0
  3. examples/datasets/criteo_dataframes.py +101 -0
  4. examples/ray/__init__.py +0 -0
  5. examples/ray/compute_world_size.py +51 -0
  6. examples/ray/train_torchrec.py +133 -0
  7. examples/retrieval/__init__.py +6 -0
  8. examples/retrieval/data/__init__.py +6 -0
  9. examples/retrieval/data/dataloader.py +44 -0
  10. examples/retrieval/knn_index.py +67 -0
  11. examples/retrieval/modules/__init__.py +6 -0
  12. examples/retrieval/modules/two_tower.py +229 -0
  13. examples/retrieval/two_tower_retrieval.py +192 -0
  14. examples/retrieval/two_tower_train.py +253 -0
  15. examples/torcharrow/__init__.py +8 -0
  16. examples/torcharrow/dataloader.py +116 -0
  17. examples/torcharrow/run.py +126 -0
  18. fbgemm_gpu/__init__.py +16 -0
  19. fbgemm_gpu/batched_unary_embeddings_ops.py +82 -0
  20. fbgemm_gpu/enums.py +21 -0
  21. fbgemm_gpu/fbgemm_gpu_py.so +0 -0
  22. fbgemm_gpu/permute_pooled_embedding_modules.py +73 -0
  23. fbgemm_gpu/permute_pooled_embedding_modules_split.py +76 -0
  24. fbgemm_gpu/split_embedding_codegen_lookup_invokers/__init__.py +19 -0
  25. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_adagrad.py +120 -0
  26. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_adam.py +149 -0
  27. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad.py +128 -0
  28. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad_with_counter.py +134 -0
  29. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad_with_weight_decay.py +128 -0
  30. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_sgd.py +105 -0
  31. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_args.py +54 -0
  32. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_lamb.py +149 -0
  33. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_lars_sgd.py +128 -0
  34. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_partial_rowwise_adam.py +149 -0
  35. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_partial_rowwise_lamb.py +149 -0
  36. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad.py +128 -0
  37. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad_with_counter.py +134 -0
  38. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad_with_weight_decay.py +128 -0
  39. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_weighted_adagrad.py +130 -0
  40. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_sgd.py +105 -0
  41. fbgemm_gpu/split_embedding_configs.py +182 -0
  42. fbgemm_gpu/split_embedding_inference_converter.py +208 -0
  43. fbgemm_gpu/split_table_batched_embeddings_ops.py +2503 -0
  44. fbgemm_gpu/uvm.py +35 -0
  45. torchrec/__init__.py +27 -0
  46. torchrec/datasets/__init__.py +31 -0
  47. torchrec/datasets/criteo.py +831 -0
  48. torchrec/datasets/movielens.py +140 -0
  49. torchrec/datasets/random.py +188 -0
  50. torchrec/datasets/scripts/__init__.py +0 -0
  51. torchrec/datasets/scripts/contiguous_preproc_criteo.py +75 -0
  52. torchrec/datasets/scripts/npy_preproc_criteo.py +73 -0
  53. torchrec/datasets/test_utils/__init__.py +0 -0
  54. torchrec/datasets/test_utils/criteo_test_utils.py +139 -0
  55. torchrec/datasets/utils.py +341 -0
  56. torchrec/distributed/__init__.py +55 -0
  57. torchrec/distributed/batched_embedding_kernel.py +697 -0
  58. torchrec/distributed/collective_utils.py +71 -0
  59. torchrec/distributed/comm.py +149 -0
  60. torchrec/distributed/comm_ops.py +930 -0
  61. torchrec/distributed/dist_data.py +949 -0
  62. torchrec/distributed/embedding.py +638 -0
  63. torchrec/distributed/embedding_kernel.py +326 -0
  64. torchrec/distributed/embedding_lookup.py +760 -0
  65. torchrec/distributed/embedding_sharding.py +660 -0
  66. torchrec/distributed/embedding_tower_sharding.py +992 -0
  67. torchrec/distributed/embedding_types.py +369 -0
  68. torchrec/distributed/embeddingbag.py +731 -0
  69. torchrec/distributed/fused_embeddingbag.py +148 -0
  70. torchrec/distributed/grouped_position_weighted.py +103 -0
  71. torchrec/distributed/model_parallel.py +555 -0
  72. torchrec/distributed/planner/__init__.py +24 -0
  73. torchrec/distributed/planner/constants.py +77 -0
  74. torchrec/distributed/planner/enumerators.py +353 -0
  75. torchrec/distributed/planner/parallelized_planners.py +307 -0
  76. torchrec/distributed/planner/partitioners.py +280 -0
  77. torchrec/distributed/planner/perf_models.py +24 -0
  78. torchrec/distributed/planner/planners.py +290 -0
  79. torchrec/distributed/planner/proposers.py +270 -0
  80. torchrec/distributed/planner/shard_estimators.py +971 -0
  81. torchrec/distributed/planner/stats.py +477 -0
  82. torchrec/distributed/planner/storage_reservations.py +168 -0
  83. torchrec/distributed/planner/types.py +423 -0
  84. torchrec/distributed/planner/utils.py +30 -0
  85. torchrec/distributed/quant_embedding.py +307 -0
  86. torchrec/distributed/quant_embedding_kernel.py +295 -0
  87. torchrec/distributed/quant_embeddingbag.py +288 -0
  88. torchrec/distributed/sharding/__init__.py +0 -0
  89. torchrec/distributed/sharding/cw_sequence_sharding.py +71 -0
  90. torchrec/distributed/sharding/cw_sharding.py +242 -0
  91. torchrec/distributed/sharding/dp_sequence_sharding.py +87 -0
  92. torchrec/distributed/sharding/dp_sharding.py +217 -0
  93. torchrec/distributed/sharding/rw_sequence_sharding.py +130 -0
  94. torchrec/distributed/sharding/rw_sharding.py +393 -0
  95. torchrec/distributed/sharding/sequence_sharding.py +69 -0
  96. torchrec/distributed/sharding/tw_sequence_sharding.py +211 -0
  97. torchrec/distributed/sharding/tw_sharding.py +469 -0
  98. torchrec/distributed/sharding/twcw_sharding.py +32 -0
  99. torchrec/distributed/sharding/twrw_sharding.py +543 -0
  100. torchrec/distributed/sharding/vb_cw_sharding.py +91 -0
  101. torchrec/distributed/sharding/vb_rw_sharding.py +250 -0
  102. torchrec/distributed/sharding/vb_sharding.py +54 -0
  103. torchrec/distributed/sharding/vb_tw_sharding.py +148 -0
  104. torchrec/distributed/sharding/vb_twrw_sharding.py +388 -0
  105. torchrec/distributed/test_utils/__init__.py +0 -0
  106. torchrec/distributed/test_utils/multi_process.py +132 -0
  107. torchrec/distributed/test_utils/test_model.py +818 -0
  108. torchrec/distributed/test_utils/test_model_parallel.py +74 -0
  109. torchrec/distributed/test_utils/test_model_parallel_base.py +117 -0
  110. torchrec/distributed/test_utils/test_sharding.py +280 -0
  111. torchrec/distributed/train_pipeline.py +531 -0
  112. torchrec/distributed/types.py +594 -0
  113. torchrec/distributed/utils.py +186 -0
  114. torchrec/fused_planner.py +57 -0
  115. torchrec/fx/__init__.py +15 -0
  116. torchrec/fx/tracer.py +78 -0
  117. torchrec/inference/__init__.py +25 -0
  118. torchrec/inference/client.py +127 -0
  119. torchrec/inference/model_packager.py +102 -0
  120. torchrec/inference/modules.py +155 -0
  121. torchrec/inference/state_dict_transform.py +103 -0
  122. torchrec/metrics/__init__.py +0 -0
  123. torchrec/metrics/auc.py +159 -0
  124. torchrec/metrics/calibration.py +108 -0
  125. torchrec/metrics/ctr.py +104 -0
  126. torchrec/metrics/metric_module.py +358 -0
  127. torchrec/metrics/metrics_config.py +152 -0
  128. torchrec/metrics/metrics_namespace.py +114 -0
  129. torchrec/metrics/model_utils.py +85 -0
  130. torchrec/metrics/mse.py +134 -0
  131. torchrec/metrics/ne.py +164 -0
  132. torchrec/metrics/rec_metric.py +686 -0
  133. torchrec/metrics/throughput.py +174 -0
  134. torchrec/models/__init__.py +27 -0
  135. torchrec/models/deepfm.py +346 -0
  136. torchrec/models/dlrm.py +708 -0
  137. torchrec/modules/__init__.py +34 -0
  138. torchrec/modules/activation.py +55 -0
  139. torchrec/modules/crossnet.py +446 -0
  140. torchrec/modules/deepfm.py +213 -0
  141. torchrec/modules/embedding_configs.py +148 -0
  142. torchrec/modules/embedding_modules.py +381 -0
  143. torchrec/modules/embedding_tower.py +150 -0
  144. torchrec/modules/feature_processor.py +74 -0
  145. torchrec/modules/fused_embedding_modules.py +625 -0
  146. torchrec/modules/lazy_extension.py +258 -0
  147. torchrec/modules/mlp.py +172 -0
  148. torchrec/modules/utils.py +117 -0
  149. torchrec/optim/__init__.py +35 -0
  150. torchrec/optim/clipping.py +53 -0
  151. torchrec/optim/fused.py +42 -0
  152. torchrec/optim/keyed.py +399 -0
  153. torchrec/optim/rowwise_adagrad.py +222 -0
  154. torchrec/optim/test_utils/__init__.py +19 -0
  155. torchrec/optim/warmup.py +147 -0
  156. torchrec/quant/__init__.py +34 -0
  157. torchrec/quant/embedding_modules.py +545 -0
  158. torchrec/sparse/__init__.py +33 -0
  159. torchrec/sparse/jagged_tensor.py +1281 -0
  160. torchrec/sparse/test_utils/__init__.py +45 -0
  161. torchrec/streamable.py +46 -0
  162. torchrec/test_utils/__init__.py +111 -0
  163. torchrec-0.2.dev0.dist-info/LICENSE +29 -0
  164. torchrec-0.2.dev0.dist-info/METADATA +175 -0
  165. torchrec-0.2.dev0.dist-info/RECORD +167 -0
  166. torchrec-0.2.dev0.dist-info/WHEEL +5 -0
  167. torchrec-0.2.dev0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,477 @@
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 logging
9
+ from collections import defaultdict
10
+ from typing import Any, cast, Dict, List, Tuple, Union
11
+
12
+ from torchrec.distributed.planner.constants import BIGINT_DTYPE
13
+ from torchrec.distributed.planner.storage_reservations import (
14
+ FixedPercentageReservation,
15
+ HeuristicalStorageReservation,
16
+ )
17
+ from torchrec.distributed.planner.types import (
18
+ ShardingOption,
19
+ Stats,
20
+ Storage,
21
+ StorageReservation,
22
+ Topology,
23
+ )
24
+ from torchrec.distributed.planner.utils import bytes_to_gb, bytes_to_mb
25
+ from torchrec.distributed.types import ParameterSharding, ShardingPlan, ShardingType
26
+
27
+
28
+ logger: logging.Logger = logging.getLogger(__name__)
29
+
30
+
31
+ MIN_WIDTH = 90
32
+
33
+
34
+ class EmbeddingStats(Stats):
35
+ """
36
+ Stats for a sharding planner execution.
37
+ """
38
+
39
+ def __init__(self) -> None:
40
+ self._width: int = MIN_WIDTH
41
+ self._stats_table: List[str] = []
42
+
43
+ def log(
44
+ self,
45
+ sharding_plan: ShardingPlan,
46
+ topology: Topology,
47
+ storage_reservation: StorageReservation,
48
+ num_proposals: int,
49
+ num_plans: int,
50
+ run_time: float,
51
+ best_plan: List[ShardingOption],
52
+ debug: bool = True,
53
+ ) -> None:
54
+ """
55
+ Logs stats for a given sharding plan.
56
+
57
+ Provides a tabular view of stats for the given sharding plan with per device
58
+ storage usage (HBM and DDR), perf, input, output, and number/type of shards.
59
+
60
+ Args:
61
+ sharding_plan (ShardingPlan): sharding plan chosen by the planner.
62
+ topology (Topology): device topology.
63
+ storage_constraint (Topology): available storage after storage reservation.
64
+ storage_reservation (StorageReservation): reserves storage for unsharded
65
+ parts of the model
66
+ num_proposals (int): number of proposals evaluated.
67
+ num_plans (int): number of proposals successfully partitioned.
68
+ run_time (float): time taken to find plan (in seconds).
69
+ best_plan (List[ShardingOption]): plan with expected performance.
70
+ debug (bool): whether to enable debug mode.
71
+ """
72
+
73
+ shard_by_fqn = {
74
+ module_name + "." + param_name: value
75
+ for module_name, param_dict in sharding_plan.plan.items()
76
+ for param_name, value in param_dict.items()
77
+ }
78
+ stats: Dict[int, Dict[str, Any]] = {
79
+ rank: {"type": {}, "input_sizes": 0.0, "output_sizes": 0.0}
80
+ for rank in range(topology.world_size)
81
+ }
82
+
83
+ used_sharding_types = set()
84
+ compute_kernels_to_count = defaultdict(int)
85
+
86
+ reserved_percent = (
87
+ storage_reservation._percentage
88
+ if isinstance(
89
+ storage_reservation,
90
+ (FixedPercentageReservation, HeuristicalStorageReservation),
91
+ )
92
+ else 0.0
93
+ )
94
+ dense_storage = (
95
+ storage_reservation._dense_storage
96
+ if isinstance(storage_reservation, HeuristicalStorageReservation)
97
+ and storage_reservation._dense_storage
98
+ else Storage(0, 0)
99
+ )
100
+ kjt_storage = (
101
+ storage_reservation._kjt_storage
102
+ if isinstance(storage_reservation, HeuristicalStorageReservation)
103
+ and storage_reservation._kjt_storage
104
+ else Storage(0, 0)
105
+ )
106
+
107
+ for sharding_option in best_plan:
108
+ fqn = sharding_option.fqn
109
+
110
+ if shard_by_fqn.get(fqn) is None:
111
+ continue
112
+ shard: ParameterSharding = shard_by_fqn[fqn]
113
+
114
+ ranks, input_sizes, output_sizes = self._get_shard_stats(
115
+ shard=shard,
116
+ sharding_option=sharding_option,
117
+ world_size=topology.world_size,
118
+ local_size=topology.local_world_size,
119
+ )
120
+ sharding_type_abbr = _get_sharding_type_abbr(shard.sharding_type)
121
+ used_sharding_types.add(sharding_type_abbr)
122
+ compute_kernels_to_count[sharding_option.compute_kernel] += 1
123
+
124
+ for i, rank in enumerate(ranks):
125
+ count = stats[rank]["type"].get(sharding_type_abbr, 0)
126
+ stats[rank]["type"][sharding_type_abbr] = count + 1
127
+ stats[rank]["input_sizes"] += input_sizes[i]
128
+ stats[rank]["output_sizes"] += output_sizes[i]
129
+
130
+ used_hbm = [0] * topology.world_size
131
+ used_ddr = [0] * topology.world_size
132
+ perf = [0.0] * topology.world_size
133
+ for sharding_option in best_plan:
134
+ for shard in sharding_option.shards:
135
+ shard_storage = cast(Storage, shard.storage)
136
+ rank = cast(int, shard.rank)
137
+ used_hbm[rank] += shard_storage.hbm
138
+ used_ddr[rank] += shard_storage.ddr
139
+ perf[rank] += cast(float, shard.perf)
140
+
141
+ used_hbm = [hbm + dense_storage.hbm + kjt_storage.hbm for hbm in used_hbm]
142
+ used_ddr = [ddr + dense_storage.ddr + kjt_storage.ddr for ddr in used_ddr]
143
+
144
+ table: List[List[Union[str, int]]] = [
145
+ [
146
+ "Rank",
147
+ "HBM (GB)",
148
+ "DDR (GB)",
149
+ "Perf (ms)",
150
+ "Input (MB)",
151
+ "Output (MB)",
152
+ "Shards",
153
+ ],
154
+ [
155
+ "------",
156
+ "----------",
157
+ "----------",
158
+ "-----------",
159
+ "------------",
160
+ "-------------",
161
+ "--------",
162
+ ],
163
+ ]
164
+
165
+ for rank, device in enumerate(topology.devices):
166
+ used_hbm_gb = bytes_to_gb(used_hbm[rank])
167
+ used_hbm_ratio = (
168
+ used_hbm[rank] / ((1 - reserved_percent) * device.storage.hbm)
169
+ if topology.compute_device == "cuda"
170
+ else 0
171
+ )
172
+ used_ddr_gb = bytes_to_gb(used_ddr[rank])
173
+ used_ddr_ratio = used_ddr[rank] / (
174
+ (1 - reserved_percent) * device.storage.ddr
175
+ )
176
+ for sharding_type in used_sharding_types:
177
+ if sharding_type not in stats[rank]["type"]:
178
+ stats[rank]["type"][sharding_type] = 0
179
+
180
+ rank_hbm = f"{round(used_hbm_gb, 1)} ({used_hbm_ratio:.0%})"
181
+ rank_ddr = f"{round(used_ddr_gb, 1)} ({used_ddr_ratio:.0%})"
182
+ rank_perf = f"{round(perf[rank], 3)}"
183
+ rank_input = f"{round(stats[rank]['input_sizes'], 2)}"
184
+ rank_output = f"{round(stats[rank]['output_sizes'], 2)}"
185
+ rank_shards = " ".join(
186
+ f"{sharding_type}: {num_tables}"
187
+ for sharding_type, num_tables in sorted(stats[rank]["type"].items())
188
+ )
189
+ table.append(
190
+ [
191
+ rank,
192
+ rank_hbm,
193
+ rank_ddr,
194
+ rank_perf,
195
+ rank_input,
196
+ rank_output,
197
+ rank_shards,
198
+ ]
199
+ )
200
+ formatted_table = _format_table(table)
201
+ self._width = max(self._width, len(formatted_table[0]) + 8)
202
+
203
+ if debug:
204
+ param_table: List[List[Union[str, int]]] = [
205
+ [
206
+ "FQN",
207
+ "Sharding",
208
+ "Compute Kernel",
209
+ "Perf (ms)",
210
+ "Pooling Factor",
211
+ "Output",
212
+ "Features",
213
+ "Ranks",
214
+ ],
215
+ [
216
+ "-----",
217
+ "----------",
218
+ "----------------",
219
+ "-----------",
220
+ "----------------",
221
+ "--------",
222
+ "----------",
223
+ "-------",
224
+ ],
225
+ ]
226
+ for so in best_plan:
227
+ ranks = sorted([cast(int, shard.rank) for shard in so.shards])
228
+ ranks = _collapse_consecutive_ranks(ranks)
229
+ shard_perfs = str(
230
+ round(sum([cast(float, shard.perf) for shard in so.shards]), 3)
231
+ )
232
+ pooling_factor = str(round(sum(so.input_lengths), 3))
233
+ output = "pooled" if so.is_pooled else "sequence"
234
+ num_features = len(so.input_lengths)
235
+ param_table.append(
236
+ [
237
+ so.fqn,
238
+ _get_sharding_type_abbr(so.sharding_type),
239
+ so.compute_kernel,
240
+ shard_perfs,
241
+ pooling_factor,
242
+ output,
243
+ num_features,
244
+ ",".join(ranks),
245
+ ]
246
+ )
247
+ formatted_param_table = _format_table(param_table)
248
+ self._width = max(self._width, len(formatted_param_table[0]) + 6)
249
+
250
+ self._stats_table.clear()
251
+ self._stats_table.append("#" * self._width)
252
+ header_text = "--- Planner Statistics ---"
253
+ self._stats_table.append(f"#{header_text: ^{self._width-2}}#")
254
+
255
+ iter_text = (
256
+ f"--- Evalulated {num_proposals} proposal(s), "
257
+ f"found {num_plans} possible plan(s), "
258
+ f"ran for {run_time:.2f}s ---"
259
+ )
260
+ self._stats_table.append(f"#{iter_text: ^{self._width-2}}#")
261
+
262
+ divider = "-" * (self._width - 4)
263
+ self._stats_table.append(f"#{divider: ^{self._width-2}}#")
264
+
265
+ for row in formatted_table:
266
+ self._stats_table.append(f"# {row: <{self._width-3}}#")
267
+
268
+ legend = "Input: MB/iteration, Output: MB/iteration, Shards: number of tables"
269
+ hbm_info = "HBM: estimated peak memory usage for shards, dense tensors, and features (KJT)"
270
+ self._stats_table.append(f"#{'' : ^{self._width-2}}#")
271
+ self._stats_table.append(f"# {legend: <{self._width-3}}#")
272
+ self._stats_table.append(f"# {hbm_info: <{self._width-3}}#")
273
+
274
+ if debug:
275
+ self._stats_table.append(f"#{'' : ^{self._width-2}}#")
276
+ self._stats_table.append(f"# {'Parameter Info:' : <{self._width-3}}#")
277
+ for row in formatted_param_table:
278
+ self._stats_table.append(f"# {row: <{self._width-3}}#")
279
+
280
+ batch_size = f"Batch Size: {topology.batch_size}"
281
+ self._stats_table.append(f"#{'' : ^{self._width-2}}#")
282
+ self._stats_table.append(f"# {batch_size : <{self._width-3}}#")
283
+
284
+ self._log_compute_kernel_stats(compute_kernels_to_count)
285
+
286
+ if debug:
287
+ self._log_max_perf_and_max_hbm(perf, used_hbm)
288
+ self._log_storage_reservation_stats(
289
+ storage_reservation,
290
+ topology,
291
+ reserved_percent,
292
+ dense_storage,
293
+ kjt_storage,
294
+ )
295
+
296
+ self._stats_table.append("#" * self._width)
297
+
298
+ for row in self._stats_table:
299
+ logger.info(row)
300
+
301
+ def _get_shard_stats(
302
+ self,
303
+ shard: ParameterSharding,
304
+ sharding_option: ShardingOption,
305
+ world_size: int,
306
+ local_size: int,
307
+ ) -> Tuple[List[int], List[float], List[float]]:
308
+ """
309
+ Gets ranks, input sizes, and output sizes per shard.
310
+ Input size is a function of pooling factor.
311
+ Output size is a function of embedding dimension * number of features.
312
+
313
+ Returns:
314
+ ranks: list of ranks.
315
+ input_sizes: input size per iter in MB across ranks for given shard.
316
+ output_sizes: output size per iter in MB across ranks for given shard.
317
+ """
318
+ assert shard.ranks
319
+ ranks = shard.ranks
320
+
321
+ batch_size = world_size * sharding_option.batch_size
322
+ input_data_type_size = BIGINT_DTYPE
323
+ pooling_factor = float(sum(sharding_option.input_lengths))
324
+ output_data_type_size = sharding_option.tensor.element_size()
325
+ num_outputs = float(
326
+ len(sharding_option.input_lengths)
327
+ if sharding_option.is_pooled
328
+ else sum(sharding_option.input_lengths)
329
+ )
330
+
331
+ if shard.sharding_type == ShardingType.DATA_PARALLEL.value:
332
+ batch_size = sharding_option.batch_size
333
+ elif shard.sharding_type == ShardingType.ROW_WISE.value:
334
+ pooling_factor /= world_size
335
+ if sharding_option.is_pooled:
336
+ num_outputs /= world_size
337
+ elif shard.sharding_type == ShardingType.TABLE_ROW_WISE.value:
338
+ pooling_factor /= local_size
339
+ if sharding_option.is_pooled:
340
+ num_outputs /= local_size
341
+
342
+ input_sizes = [
343
+ bytes_to_mb(batch_size * pooling_factor * input_data_type_size)
344
+ ] * len(ranks)
345
+ output_sizes = (
346
+ [
347
+ bytes_to_mb(
348
+ batch_size
349
+ * sharding_option.tensor.shape[1] # embedding dim
350
+ * num_outputs
351
+ * output_data_type_size
352
+ )
353
+ ]
354
+ * len(ranks)
355
+ if shard.sharding_type == ShardingType.DATA_PARALLEL.value
356
+ else [
357
+ bytes_to_mb(
358
+ batch_size
359
+ * int(shard.shard_sizes[1]) # embedding dim
360
+ * num_outputs
361
+ * output_data_type_size
362
+ )
363
+ # pyre-ignore [16]
364
+ for shard in shard.sharding_spec.shards
365
+ ]
366
+ )
367
+ return ranks, input_sizes, output_sizes
368
+
369
+ def _log_max_perf_and_max_hbm(self, perf: List[float], used_hbm: List[int]) -> None:
370
+ max_perf = max(perf)
371
+ max_perf_indices = [i for i in range(len(perf)) if perf[i] == max_perf]
372
+ rank_text = "ranks" if len(max_perf_indices) > 1 else "rank"
373
+ max_perf_indices = _collapse_consecutive_ranks(max_perf_indices)
374
+ max_perf_ranks = f"{rank_text} {','.join(max_perf_indices)}"
375
+ longest_critical_path = (
376
+ f"Longest Critical Path: {round(max_perf, 3)} ms on {max_perf_ranks}"
377
+ )
378
+ self._stats_table.append(f"#{'' : ^{self._width-2}}#")
379
+ self._stats_table.append(f"# {longest_critical_path : <{self._width-3}}#")
380
+
381
+ max_hbm = max(used_hbm)
382
+ max_hbm_indices = [i for i in range(len(used_hbm)) if used_hbm[i] == max_hbm]
383
+ rank_text = "ranks" if len(max_hbm_indices) > 1 else "rank"
384
+ max_hbm_indices = _collapse_consecutive_ranks(max_hbm_indices)
385
+ max_hbm_ranks = f"{rank_text} {','.join(max_hbm_indices)}"
386
+ peak_memory_pressure = f"Peak Memory Pressure: {round(bytes_to_gb(max_hbm), 3)} GB on {max_hbm_ranks}"
387
+ self._stats_table.append(f"#{'' : ^{self._width-2}}#")
388
+ self._stats_table.append(f"# {peak_memory_pressure : <{self._width-3}}#")
389
+
390
+ def _log_storage_reservation_stats(
391
+ self,
392
+ storage_reservation: StorageReservation,
393
+ topology: Topology,
394
+ reserved_percent: float,
395
+ dense_storage: Storage,
396
+ kjt_storage: Storage,
397
+ ) -> None:
398
+ device_storage = topology.devices[0].storage
399
+ usable_hbm = round(
400
+ bytes_to_gb(int((1 - reserved_percent) * device_storage.hbm)), 3
401
+ )
402
+ usable_ddr = round(
403
+ bytes_to_gb(int((1 - reserved_percent) * device_storage.ddr)), 3
404
+ )
405
+ usable_memory = f"HBM: {usable_hbm} GB, DDR: {usable_ddr} GB"
406
+ usable_percentage = f"Percent of Total: {(1 - reserved_percent):.0%}"
407
+ self._stats_table.append(f"#{'' : ^{self._width-2}}#")
408
+ self._stats_table.append(f"# {'Usable Memory:' : <{self._width-3}}#")
409
+ self._stats_table.append(f"# {usable_memory : <{self._width-6}}#")
410
+ self._stats_table.append(f"# {usable_percentage : <{self._width-6}}#")
411
+
412
+ if isinstance(storage_reservation, HeuristicalStorageReservation):
413
+ dense_hbm = round(bytes_to_gb(dense_storage.hbm), 3)
414
+ dense_ddr = round(bytes_to_gb(dense_storage.ddr), 3)
415
+ dense_storage_text = f"HBM: {dense_hbm} GB, DDR: {dense_ddr} GB"
416
+ self._stats_table.append(f"#{'' : ^{self._width-2}}#")
417
+ self._stats_table.append(
418
+ f"# {'Dense Storage (per rank): ' : <{self._width-3}}#"
419
+ )
420
+ self._stats_table.append(f"# {dense_storage_text : <{self._width-6}}#")
421
+
422
+ kjt_hbm = round(bytes_to_gb(kjt_storage.hbm), 3)
423
+ kjt_ddr = round(bytes_to_gb(kjt_storage.ddr), 3)
424
+ kjt_storage_text = f"HBM: {kjt_hbm} GB, DDR: {kjt_ddr} GB"
425
+ self._stats_table.append(f"#{'' : ^{self._width-2}}#")
426
+ self._stats_table.append(
427
+ f"# {'KJT Storage (per rank): ' : <{self._width-3}}#"
428
+ )
429
+ self._stats_table.append(f"# {kjt_storage_text : <{self._width-6}}#")
430
+
431
+ def _log_compute_kernel_stats(
432
+ self, compute_kernels_to_count: Dict[str, int]
433
+ ) -> None:
434
+ compute_kernels_count = [
435
+ f"{compute_kernel}: {count}"
436
+ for compute_kernel, count in sorted(compute_kernels_to_count.items())
437
+ ]
438
+ self._stats_table.append(f"#{'' : ^{self._width-2}}#")
439
+ self._stats_table.append(f"# {'Compute Kernels:' : <{self._width-3}}#")
440
+ for compute_kernel_count in compute_kernels_count:
441
+ self._stats_table.append(f"# {compute_kernel_count : <{self._width-6}}#")
442
+
443
+
444
+ def _get_sharding_type_abbr(sharding_type: str) -> str:
445
+ if sharding_type == ShardingType.DATA_PARALLEL.value:
446
+ return "DP"
447
+ elif sharding_type == ShardingType.TABLE_WISE.value:
448
+ return "TW"
449
+ elif sharding_type == ShardingType.COLUMN_WISE.value:
450
+ return "CW"
451
+ elif sharding_type == ShardingType.ROW_WISE.value:
452
+ return "RW"
453
+ elif sharding_type == ShardingType.TABLE_ROW_WISE.value:
454
+ return "TWRW"
455
+ elif sharding_type == ShardingType.TABLE_COLUMN_WISE.value:
456
+ return "TWCW"
457
+ else:
458
+ raise ValueError(
459
+ f"Unrecognized or unsupported sharding type provided: {sharding_type}"
460
+ )
461
+
462
+
463
+ def _format_table(table: List[List[Union[str, int]]]) -> List[str]:
464
+ longest_cols = [
465
+ (max([len(str(row[i])) for row in table]) + 3) for i in range(len(table[0]))
466
+ ]
467
+ row_format = "".join(
468
+ ["{:>" + str(longest_col) + "}" for longest_col in longest_cols]
469
+ )
470
+ return [row_format.format(*row) for row in table]
471
+
472
+
473
+ def _collapse_consecutive_ranks(ranks: List[int]) -> List[str]:
474
+ if len(ranks) > 1 and ranks == list(range(min(ranks), max(ranks) + 1)):
475
+ return [f"{min(ranks)}-{max(ranks)}"]
476
+ else:
477
+ return [str(rank) for rank in ranks]
@@ -0,0 +1,168 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import copy
9
+ import math
10
+ from typing import Dict, List, Optional, Set
11
+
12
+ from torch import nn
13
+ from torchrec.distributed.planner.constants import BIGINT_DTYPE, POOLING_FACTOR
14
+ from torchrec.distributed.planner.types import (
15
+ ParameterConstraints,
16
+ Storage,
17
+ StorageReservation,
18
+ Topology,
19
+ )
20
+ from torchrec.distributed.planner.utils import sharder_name
21
+ from torchrec.distributed.types import ModuleSharder
22
+
23
+
24
+ class FixedPercentageReservation(StorageReservation):
25
+ def __init__(self, percentage: float) -> None:
26
+ assert percentage >= 0 and percentage <= 1
27
+ self._percentage: float = percentage
28
+
29
+ def reserve(
30
+ self,
31
+ topology: Topology,
32
+ module: nn.Module,
33
+ sharders: List[ModuleSharder[nn.Module]],
34
+ constraints: Optional[Dict[str, ParameterConstraints]] = None,
35
+ ) -> Topology:
36
+ reserved_topology = copy.deepcopy(topology)
37
+ _reserve_storage_percentage(reserved_topology, self._percentage)
38
+ return reserved_topology
39
+
40
+
41
+ class HeuristicalStorageReservation(StorageReservation):
42
+ """
43
+ Reserves storage for model to be sharded with heuristical calculation. The storage
44
+ reservation is comprised of unshardable tensor storage, KJT storage, and an extra
45
+ percentage.
46
+
47
+ Args:
48
+ percentage (float): extra storage percentage to reserve that acts as a margin of
49
+ error beyond heuristic calculation of storage.
50
+ """
51
+
52
+ def __init__(self, percentage: float) -> None:
53
+ assert percentage >= 0 and percentage <= 1
54
+ self._percentage: float = percentage
55
+ self._dense_storage: Optional[Storage] = None
56
+ self._kjt_storage: Optional[Storage] = None
57
+
58
+ def reserve(
59
+ self,
60
+ topology: Topology,
61
+ module: nn.Module,
62
+ sharders: List[ModuleSharder[nn.Module]],
63
+ constraints: Optional[Dict[str, ParameterConstraints]] = None,
64
+ ) -> Topology:
65
+ reserved_topology = copy.deepcopy(topology)
66
+
67
+ sharder_map: Dict[str, ModuleSharder[nn.Module]] = {
68
+ sharder_name(sharder.module_type): sharder for sharder in sharders
69
+ }
70
+ shardable_parameters: Set[nn.Parameter] = set()
71
+ all_input_lengths: List[float] = []
72
+
73
+ for child_module in module.modules():
74
+ sharder_key = sharder_name(type(child_module))
75
+ sharder = sharder_map.get(sharder_key)
76
+ if not sharder:
77
+ continue
78
+
79
+ names = sharder.shardable_parameters(child_module).keys()
80
+ parameters = sharder.shardable_parameters(child_module).values()
81
+
82
+ shardable_parameters.update(parameters)
83
+
84
+ all_input_lengths.extend(
85
+ [
86
+ sum(constraints[name].pooling_factors)
87
+ if constraints and constraints.get(name)
88
+ else POOLING_FACTOR
89
+ for name in names
90
+ ]
91
+ )
92
+
93
+ _reserve_storage_percentage(reserved_topology, self._percentage)
94
+
95
+ self._dense_storage = _reserve_dense_storage(
96
+ reserved_topology, module, shardable_parameters
97
+ )
98
+
99
+ self._kjt_storage = _reserve_kjt_storage(
100
+ reserved_topology, all_input_lengths, BIGINT_DTYPE
101
+ )
102
+
103
+ return reserved_topology
104
+
105
+
106
+ def _reserve_dense_storage(
107
+ topology: Topology, module: nn.Module, shardable_parameters: Set[nn.Parameter]
108
+ ) -> Storage:
109
+ unshardable_parameters = set(module.parameters()) - shardable_parameters
110
+
111
+ unshardable_parameters_size = sum(
112
+ [
113
+ # heuristic: 6 * dense parameter size (https://fburl.com/q8qcxvgx)
114
+ # parameter + optimizer (~2x parameter) + ddp (~3x parameter)
115
+ 6 * parameter.element_size() * parameter.nelement()
116
+ for parameter in unshardable_parameters
117
+ ]
118
+ )
119
+
120
+ buffers_size = sum(
121
+ [
122
+ buffer.element_size() * buffer.nelement()
123
+ for _, buffer in module.named_buffers()
124
+ ]
125
+ )
126
+
127
+ unshardable_tensors_size = unshardable_parameters_size + buffers_size
128
+
129
+ unshardable_tensors_storage = Storage(
130
+ hbm=unshardable_tensors_size if topology.compute_device == "cuda" else 0,
131
+ ddr=unshardable_tensors_size if topology.compute_device == "cpu" else 0,
132
+ )
133
+
134
+ for device in topology.devices:
135
+ device.storage -= unshardable_tensors_storage
136
+
137
+ return unshardable_tensors_storage
138
+
139
+
140
+ def _reserve_kjt_storage(
141
+ topology: Topology,
142
+ all_input_lengths: List[float],
143
+ input_data_type_size: int,
144
+ ) -> Storage:
145
+ kjt_size = (
146
+ math.ceil(
147
+ float(topology.batch_size)
148
+ * sum(all_input_lengths)
149
+ * float(input_data_type_size)
150
+ )
151
+ * 20 # 2 pipelined batches each with 10 internal copies
152
+ )
153
+
154
+ kjt_storage = Storage(
155
+ hbm=kjt_size if topology.compute_device == "cuda" else 0,
156
+ ddr=kjt_size if topology.compute_device == "cpu" else 0,
157
+ )
158
+
159
+ for device in topology.devices:
160
+ device.storage -= kjt_storage
161
+
162
+ return kjt_storage
163
+
164
+
165
+ def _reserve_storage_percentage(topology: Topology, percent: float) -> None:
166
+ for device in topology.devices:
167
+ device.storage.hbm = int((1 - percent) * device.storage.hbm)
168
+ device.storage.ddr = int((1 - percent) * device.storage.ddr)