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,531 @@
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 abc
9
+ import logging
10
+ from dataclasses import dataclass, field
11
+ from typing import (
12
+ Any,
13
+ cast,
14
+ Dict,
15
+ Generic,
16
+ Iterator,
17
+ List,
18
+ Optional,
19
+ Set,
20
+ Tuple,
21
+ TypeVar,
22
+ )
23
+
24
+ import torch
25
+ from torch.autograd.profiler import record_function
26
+ from torch.fx.node import Node
27
+ from torchrec.distributed.model_parallel import DistributedModelParallel, ShardedModule
28
+ from torchrec.distributed.types import Awaitable, ShardedModuleContext
29
+ from torchrec.streamable import Multistreamable, Pipelineable
30
+
31
+ logger: logging.Logger = logging.getLogger(__name__)
32
+
33
+
34
+ In = TypeVar("In", bound=Pipelineable)
35
+ Out = TypeVar("Out")
36
+ DistIn = TypeVar("DistIn", bound=Multistreamable)
37
+ DistOut = TypeVar("DistOut")
38
+
39
+
40
+ class TrainPipeline(abc.ABC, Generic[In, Out]):
41
+ @abc.abstractmethod
42
+ def progress(self, dataloader_iter: Iterator[In]) -> Out:
43
+ pass
44
+
45
+
46
+ def _to_device(batch: In, device: torch.device, non_blocking: bool) -> In:
47
+ assert isinstance(
48
+ batch, (torch.Tensor, Pipelineable)
49
+ ), f"{type(batch)} must implement Pipelineable interface"
50
+ return cast(In, batch.to(device=device, non_blocking=non_blocking))
51
+
52
+
53
+ def _wait_for_batch(batch: In, stream: Optional[torch.cuda.streams.Stream]) -> None:
54
+ if stream is None:
55
+ return
56
+ torch.cuda.current_stream().wait_stream(stream)
57
+ # As mentioned in https://pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html,
58
+ # PyTorch uses the "caching allocator" for memroy allocation for tensors. When a tensor is
59
+ # freed, its memory is likely to be reused by newly constructed tenosrs. By default,
60
+ # this allocator traces whether a tensor is still in use by only the CUDA stream where it
61
+ # was created. When a tensor is used by additional CUDA streams, we need to call record_stream
62
+ # to tell the allocator about all these streams. Otherwise, the allocator might free the
63
+ # underlying memory of the tensor once it is no longer used by the creator stream. This is
64
+ # a notable programming trick when we write programs using multi CUDA streams.
65
+ cur_stream = torch.cuda.current_stream()
66
+ assert isinstance(
67
+ batch, (torch.Tensor, Multistreamable)
68
+ ), f"{type(batch)} must implement Multistreamable interface"
69
+ batch.record_stream(cur_stream)
70
+
71
+
72
+ class TrainPipelineBase(TrainPipeline[In, Out]):
73
+ """
74
+ This class runs training iterations using a pipeline of two stages, each as a CUDA
75
+ stream, namely, the current (default) stream and `self._memcpy_stream`. For each
76
+ iteration, `self._memcpy_stream` moves the input from host (CPU) memory to GPU
77
+ memory, and the default stream runs forward, backward, and optimization.
78
+ """
79
+
80
+ def __init__(
81
+ self,
82
+ model: torch.nn.Module,
83
+ optimizer: torch.optim.Optimizer,
84
+ device: torch.device,
85
+ ) -> None:
86
+ self._model = model
87
+ self._optimizer = optimizer
88
+ self._device = device
89
+ self._memcpy_stream: Optional[torch.cuda.streams.Stream] = (
90
+ torch.cuda.Stream() if device.type == "cuda" else None
91
+ )
92
+ self._cur_batch: Optional[In] = None
93
+ self._connected = False
94
+
95
+ def _connect(self, dataloader_iter: Iterator[In]) -> None:
96
+ cur_batch = next(dataloader_iter)
97
+ self._cur_batch = cur_batch
98
+ with torch.cuda.stream(self._memcpy_stream):
99
+ self._cur_batch = _to_device(cur_batch, self._device, non_blocking=True)
100
+ self._connected = True
101
+
102
+ def progress(self, dataloader_iter: Iterator[In]) -> Out:
103
+ if not self._connected:
104
+ self._connect(dataloader_iter)
105
+
106
+ # Fetch next batch
107
+ with record_function("## next_batch ##"):
108
+ next_batch = next(dataloader_iter)
109
+ cur_batch = self._cur_batch
110
+ assert cur_batch is not None
111
+
112
+ if self._model.training:
113
+ with record_function("## zero_grad ##"):
114
+ self._optimizer.zero_grad()
115
+
116
+ with record_function("## wait_for_batch ##"):
117
+ _wait_for_batch(cur_batch, self._memcpy_stream)
118
+
119
+ with record_function("## forward ##"):
120
+ (losses, output) = self._model(cur_batch)
121
+
122
+ if self._model.training:
123
+ with record_function("## backward ##"):
124
+ torch.sum(losses, dim=0).backward()
125
+
126
+ # Copy the next batch to GPU
127
+ self._cur_batch = cur_batch = next_batch
128
+ with record_function("## copy_batch_to_gpu ##"):
129
+ with torch.cuda.stream(self._memcpy_stream):
130
+ self._cur_batch = _to_device(cur_batch, self._device, non_blocking=True)
131
+
132
+ # Update
133
+ if self._model.training:
134
+ with record_function("## optimizer ##"):
135
+ self._optimizer.step()
136
+
137
+ return output
138
+
139
+
140
+ class Tracer(torch.fx.Tracer):
141
+ # Disable proxying buffers during tracing. Ideally, proxying buffers would
142
+ # be disabled, but some models are currently mutating buffer values, which
143
+ # causes errors during tracing. If those models can be rewritten to not do
144
+ # that, we can likely remove this line
145
+ proxy_buffer_attributes = False
146
+
147
+ def __init__(self, unsharded_module_names: Optional[List[str]] = None) -> None:
148
+ super().__init__()
149
+ self._unsharded_module_names: List[str] = (
150
+ unsharded_module_names if unsharded_module_names is not None else []
151
+ )
152
+
153
+ def is_leaf_module(self, m: torch.nn.Module, module_qualified_name: str) -> bool:
154
+ if (
155
+ isinstance(m, ShardedModule)
156
+ or module_qualified_name in self._unsharded_module_names
157
+ ):
158
+ return True
159
+ return super().is_leaf_module(m, module_qualified_name)
160
+
161
+
162
+ @dataclass
163
+ class TrainPipelineContext:
164
+ # pyre-ignore [4]
165
+ input_dist_requests: Dict[str, Awaitable[Any]] = field(default_factory=dict)
166
+ module_contexts: Dict[str, ShardedModuleContext] = field(default_factory=dict)
167
+
168
+
169
+ @dataclass
170
+ class ArgInfo:
171
+ # attributes of input batch, e.g. batch.attr1.attr2 call
172
+ # will produce ["attr1", "attr2"]
173
+ input_attrs: List[str]
174
+ # batch[attr1].attr2 will produce [True, False]
175
+ is_getitems: List[bool]
176
+ # name for kwarg of pipelined forward() call or None
177
+ # for a positional arg
178
+ name: Optional[str]
179
+
180
+
181
+ class PipelinedForward(Generic[DistIn, DistOut, Out]):
182
+ def __init__(
183
+ self,
184
+ name: str,
185
+ args: List[ArgInfo],
186
+ module: ShardedModule[DistIn, DistOut, Out],
187
+ context: TrainPipelineContext,
188
+ dist_stream: Optional[torch.cuda.streams.Stream],
189
+ ) -> None:
190
+ self._name = name
191
+ self._args = args
192
+ self._module = module
193
+ self._context = context
194
+ self._dist_stream = dist_stream
195
+
196
+ # pyre-ignore [2]
197
+ def __call__(self, *input, **kwargs) -> Awaitable[Out]:
198
+ assert self._name in self._context.input_dist_requests
199
+ request = self._context.input_dist_requests[self._name]
200
+ assert isinstance(request, Awaitable)
201
+ with record_function("## wait_sparse_data_dist ##"):
202
+ # Finish waiting on the dist_stream,
203
+ # in case some delayed stream scheduling happens during the wait() call.
204
+ with torch.cuda.stream(self._dist_stream):
205
+ data = request.wait()
206
+
207
+ # Make sure that both result of input_dist and context
208
+ # are properly transferred to the current stream.
209
+ if self._dist_stream is not None:
210
+ torch.cuda.current_stream().wait_stream(self._dist_stream)
211
+ cur_stream = torch.cuda.current_stream()
212
+
213
+ assert isinstance(
214
+ data, (torch.Tensor, Multistreamable)
215
+ ), f"{type(data)} must implement Multistreamable interface"
216
+ # pyre-fixme[6]: For 1st param expected `Stream` but got `Stream`.
217
+ data.record_stream(cur_stream)
218
+
219
+ ctx = self._context.module_contexts[self._name]
220
+ ctx.record_stream(cur_stream)
221
+
222
+ return self._module.compute_and_output_dist(
223
+ self._context.module_contexts[self._name], data
224
+ )
225
+
226
+ @property
227
+ def name(self) -> str:
228
+ return self._name
229
+
230
+ @property
231
+ def args(self) -> List[ArgInfo]:
232
+ return self._args
233
+
234
+
235
+ def _start_data_dist(
236
+ pipelined_modules: List[ShardedModule],
237
+ batch: In,
238
+ context: TrainPipelineContext,
239
+ ) -> None:
240
+ context.input_dist_requests.clear()
241
+ context.module_contexts.clear()
242
+ for module in pipelined_modules:
243
+ forward = module.forward
244
+ assert isinstance(forward, PipelinedForward)
245
+
246
+ # Retrieve argument.
247
+ args = []
248
+ kwargs = {}
249
+ for arg_info in forward.args:
250
+ if arg_info.input_attrs:
251
+ arg = batch
252
+ for attr, is_getitem in zip(arg_info.input_attrs, arg_info.is_getitems):
253
+ if is_getitem:
254
+ arg = arg[attr]
255
+ else:
256
+ arg = getattr(arg, attr)
257
+ if arg_info.name:
258
+ kwargs[arg_info.name] = arg
259
+ else:
260
+ args.append(arg)
261
+ else:
262
+ args.append(None)
263
+
264
+ # Start input distribution.
265
+ module_ctx = module.create_context()
266
+ context.module_contexts[forward.name] = module_ctx
267
+ context.input_dist_requests[forward.name] = module.input_dist(
268
+ module_ctx, *args, **kwargs
269
+ )
270
+
271
+
272
+ # pyre-ignore
273
+ def _get_node_args_helper(arguments, num_found: int) -> Tuple[List[ArgInfo], int]:
274
+ """
275
+ Goes through the args/kwargs of a node and arranges them into a list of `ArgInfo`s.
276
+ It also counts the number of (args + kwargs) found.
277
+ """
278
+
279
+ arg_info_list = [ArgInfo([], [], None) for _ in range(len(arguments))]
280
+ for arg, arg_info in zip(arguments, arg_info_list):
281
+ if arg is None:
282
+ num_found += 1
283
+ continue
284
+ while True:
285
+ if not isinstance(arg, torch.fx.Node):
286
+ break
287
+ child_node = arg
288
+
289
+ if child_node.op == "placeholder":
290
+ num_found += 1
291
+ break
292
+ elif (
293
+ child_node.op == "call_function"
294
+ and child_node.target.__module__ == "builtins"
295
+ # pyre-ignore[16]
296
+ and child_node.target.__name__ == "getattr"
297
+ ):
298
+ arg_info.input_attrs.insert(0, child_node.args[1])
299
+ arg_info.is_getitems.insert(0, False)
300
+ arg = child_node.args[0]
301
+ elif (
302
+ child_node.op == "call_function"
303
+ and child_node.target.__module__ == "_operator"
304
+ # pyre-ignore[16]
305
+ and child_node.target.__name__ == "getitem"
306
+ ):
307
+ arg_info.input_attrs.insert(0, child_node.args[1])
308
+ arg_info.is_getitems.insert(0, True)
309
+ arg = child_node.args[0]
310
+ else:
311
+ break
312
+ return arg_info_list, num_found
313
+
314
+
315
+ def _get_node_args(node: Node) -> Tuple[List[ArgInfo], int]:
316
+ num_found = 0
317
+ pos_arg_info_list, num_found = _get_node_args_helper(node.args, num_found)
318
+ kwargs_arg_info_list, num_found = _get_node_args_helper(
319
+ node.kwargs.values(), num_found
320
+ )
321
+
322
+ # Replace with proper names for kwargs
323
+ for name, arg_info_list in zip(node.kwargs, kwargs_arg_info_list):
324
+ arg_info_list.name = name
325
+
326
+ arg_info_list = pos_arg_info_list + kwargs_arg_info_list
327
+ return arg_info_list, num_found
328
+
329
+
330
+ def _get_unsharded_module_names_helper(
331
+ model: torch.nn.Module,
332
+ path: str,
333
+ unsharded_module_names: Set[str],
334
+ ) -> bool:
335
+ sharded_children = set()
336
+ for name, child in model.named_children():
337
+ curr_path = path + name
338
+ if isinstance(child, ShardedModule):
339
+ sharded_children.add(name)
340
+ else:
341
+ child_sharded = _get_unsharded_module_names_helper(
342
+ child,
343
+ curr_path + ".",
344
+ unsharded_module_names,
345
+ )
346
+ if child_sharded:
347
+ sharded_children.add(name)
348
+
349
+ if len(sharded_children) > 0:
350
+ for name, _ in model.named_children():
351
+ if name not in sharded_children:
352
+ unsharded_module_names.add(path + name)
353
+
354
+ return len(sharded_children) > 0
355
+
356
+
357
+ def _get_unsharded_module_names(model: torch.nn.Module) -> List[str]:
358
+ """
359
+ Returns a list of top level modules do not contain any sharded sub modules.
360
+ """
361
+
362
+ unsharded_module_names: Set[str] = set()
363
+ _get_unsharded_module_names_helper(
364
+ model,
365
+ "",
366
+ unsharded_module_names,
367
+ )
368
+ return list(unsharded_module_names)
369
+
370
+
371
+ def _rewrite_model( # noqa C901
372
+ model: torch.nn.Module,
373
+ context: TrainPipelineContext,
374
+ dist_stream: Optional[torch.cuda.streams.Stream],
375
+ ) -> List[ShardedModule]:
376
+
377
+ # Get underlying nn.Module
378
+ if isinstance(model, DistributedModelParallel):
379
+ model = model.module
380
+
381
+ # Collect a list of sharded modules.
382
+ sharded_modules = {}
383
+ for name, m in model.named_modules():
384
+ if isinstance(m, ShardedModule):
385
+ sharded_modules[name] = m
386
+
387
+ # Trace a model.
388
+ tracer = Tracer(_get_unsharded_module_names(model))
389
+ graph = tracer.trace(model)
390
+
391
+ # Select sharded modules, which are top-level in the forward call graph,
392
+ # i.e. which don't have input transformations, i.e.
393
+ # rely only on 'builtins.getattr'.
394
+ ret = []
395
+ for node in graph.nodes:
396
+ if node.op == "call_module" and node.target in sharded_modules:
397
+ total_num_args = len(node.args) + len(node.kwargs)
398
+ if total_num_args == 0:
399
+ continue
400
+ arg_info_list, num_found = _get_node_args(node)
401
+ if num_found == total_num_args:
402
+ logger.info(f"Module '{node.target}'' will be pipelined")
403
+ child = sharded_modules[node.target]
404
+ child.forward = PipelinedForward(
405
+ node.target, arg_info_list, child, context, dist_stream
406
+ )
407
+ ret.append(child)
408
+ return ret
409
+
410
+
411
+ class TrainPipelineSparseDist(TrainPipeline[In, Out]):
412
+ """
413
+ This pipeline overlaps device transfer, and `ShardedModule.input_dist()` with
414
+ forward and backward. This helps hide the all2all latency while preserving the
415
+ training forward / backward ordering.
416
+
417
+ stage 3: forward, backward - uses default CUDA stream
418
+ stage 2: ShardedModule.input_dist() - uses data_dist CUDA stream
419
+ stage 1: device transfer - uses memcpy CUDA stream
420
+
421
+ `ShardedModule.input_dist()` is only done for top-level modules in the call graph.
422
+ To be considered a top-level module, a module can only depend on 'getattr' calls on
423
+ input.
424
+
425
+ Input model must be symbolically traceable with the exception of `ShardedModule` and
426
+ `DistributedDataParallel` modules.
427
+ """
428
+
429
+ def __init__(
430
+ self,
431
+ model: torch.nn.Module,
432
+ optimizer: torch.optim.Optimizer,
433
+ device: torch.device,
434
+ ) -> None:
435
+ self._model = model
436
+ self._optimizer = optimizer
437
+ self._device = device
438
+ # use two data streams to support two concurrent batches
439
+ if device.type == "cuda":
440
+ self._memcpy_stream: Optional[
441
+ torch.cuda.streams.Stream
442
+ ] = torch.cuda.Stream()
443
+ self._data_dist_stream: Optional[
444
+ torch.cuda.streams.Stream
445
+ ] = torch.cuda.Stream()
446
+ else:
447
+ self._memcpy_stream: Optional[torch.cuda.streams.Stream] = None
448
+ self._data_dist_stream: Optional[torch.cuda.streams.Stream] = None
449
+ self._batch_i: Optional[In] = None
450
+ self._batch_ip1: Optional[In] = None
451
+ self._batch_ip2: Optional[In] = None
452
+ self._connected = False
453
+ self._context = TrainPipelineContext()
454
+ self._pipelined_modules: List[ShardedModule] = []
455
+
456
+ def _connect(self, dataloader_iter: Iterator[In]) -> None:
457
+ # batch 1
458
+ with torch.cuda.stream(self._memcpy_stream):
459
+ batch_i = next(dataloader_iter)
460
+ self._batch_i = batch_i = _to_device(
461
+ batch_i, self._device, non_blocking=True
462
+ )
463
+ # Try to pipeline input data dist.
464
+ self._pipelined_modules = _rewrite_model(
465
+ self._model, self._context, self._data_dist_stream
466
+ )
467
+
468
+ with torch.cuda.stream(self._data_dist_stream):
469
+ _wait_for_batch(batch_i, self._memcpy_stream)
470
+ _start_data_dist(self._pipelined_modules, batch_i, self._context)
471
+
472
+ # batch 2
473
+ with torch.cuda.stream(self._memcpy_stream):
474
+ batch_ip1 = next(dataloader_iter)
475
+ self._batch_ip1 = batch_ip1 = _to_device(
476
+ batch_ip1, self._device, non_blocking=True
477
+ )
478
+ self._connected = True
479
+
480
+ def progress(self, dataloader_iter: Iterator[In]) -> Out:
481
+ if not self._connected:
482
+ self._connect(dataloader_iter)
483
+
484
+ if self._model.training:
485
+ with record_function("## zero_grad ##"):
486
+ self._optimizer.zero_grad()
487
+
488
+ with record_function("## copy_batch_to_gpu ##"):
489
+ with torch.cuda.stream(self._memcpy_stream):
490
+ batch_ip2 = next(dataloader_iter)
491
+ self._batch_ip2 = batch_ip2 = _to_device(
492
+ batch_ip2, self._device, non_blocking=True
493
+ )
494
+ batch_i = cast(In, self._batch_i)
495
+ batch_ip1 = cast(In, self._batch_ip1)
496
+
497
+ with record_function("## wait_for_batch ##"):
498
+ _wait_for_batch(batch_i, self._data_dist_stream)
499
+
500
+ # Forward
501
+ with record_function("## forward ##"):
502
+ # if using multiple streams (ie. CUDA), create an event in default stream
503
+ # before starting forward pass
504
+ if self._data_dist_stream:
505
+ event = torch.cuda.current_stream().record_event()
506
+ (losses, output) = cast(Tuple[torch.Tensor, Out], self._model(batch_i))
507
+
508
+ # Data Distribution
509
+ with record_function("## sparse_data_dist ##"):
510
+ with torch.cuda.stream(self._data_dist_stream):
511
+ _wait_for_batch(batch_ip1, self._memcpy_stream)
512
+ # Ensure event in default stream has been called before
513
+ # starting data dist
514
+ if self._data_dist_stream:
515
+ # pyre-ignore [61]: Local variable `event` is undefined, or not always defined
516
+ self._data_dist_stream.wait_event(event)
517
+ _start_data_dist(self._pipelined_modules, batch_ip1, self._context)
518
+
519
+ if self._model.training:
520
+ # Backward
521
+ with record_function("## backward ##"):
522
+ torch.sum(losses, dim=0).backward()
523
+
524
+ # Update
525
+ with record_function("## optimizer ##"):
526
+ self._optimizer.step()
527
+
528
+ self._batch_i = batch_ip1
529
+ self._batch_ip1 = batch_ip2
530
+
531
+ return output