Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

#609 Ci fix

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:bugfix/infra-000_ci
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
  1. import sys
  2. import os
  3. import itertools
  4. from typing import List, Tuple
  5. from contextlib import contextmanager
  6. import torch
  7. import torch.nn as nn
  8. from torch import distributed as dist
  9. from torch.cuda.amp import autocast
  10. from torch.distributed.elastic.multiprocessing import Std
  11. from torch.distributed.elastic.multiprocessing.errors import record
  12. from torch.distributed.launcher.api import LaunchConfig, elastic_launch
  13. from super_gradients.common.environment.ddp_utils import init_trainer
  14. from super_gradients.common.data_types.enum import MultiGPUMode
  15. from super_gradients.common.environment.argparse_utils import EXTRA_ARGS
  16. from super_gradients.common.environment.ddp_utils import find_free_port, is_distributed, is_launched_using_sg
  17. from super_gradients.common.abstractions.abstract_logger import get_logger, mute_current_process
  18. from super_gradients.common.environment.device_utils import device_config
  19. from super_gradients.common.decorators.factory_decorator import resolve_param
  20. from super_gradients.common.factories.type_factory import TypeFactory
  21. logger = get_logger(__name__)
  22. def distributed_all_reduce_tensor_average(tensor, n):
  23. """
  24. This method performs a reduce operation on multiple nodes running distributed training
  25. It first sums all of the results and then divides the summation
  26. :param tensor: The tensor to perform the reduce operation for
  27. :param n: Number of nodes
  28. :return: Averaged tensor from all of the nodes
  29. """
  30. rt = tensor.clone()
  31. torch.distributed.all_reduce(rt, op=torch.distributed.ReduceOp.SUM)
  32. rt /= n
  33. return rt
  34. def reduce_results_tuple_for_ddp(validation_results_tuple, device):
  35. """Gather all validation tuples from the various devices and average them"""
  36. validation_results_list = list(validation_results_tuple)
  37. for i, validation_result in enumerate(validation_results_list):
  38. if torch.is_tensor(validation_result):
  39. validation_result = validation_result.clone().detach()
  40. else:
  41. validation_result = torch.tensor(validation_result)
  42. validation_results_list[i] = distributed_all_reduce_tensor_average(tensor=validation_result.to(device), n=torch.distributed.get_world_size())
  43. validation_results_tuple = tuple(validation_results_list)
  44. return validation_results_tuple
  45. class MultiGPUModeAutocastWrapper:
  46. def __init__(self, func):
  47. self.func = func
  48. def __call__(self, *args, **kwargs):
  49. with autocast():
  50. out = self.func(*args, **kwargs)
  51. return out
  52. def scaled_all_reduce(tensors: torch.Tensor, num_gpus: int):
  53. """
  54. Performs the scaled all_reduce operation on the provided tensors.
  55. The input tensors are modified in-place.
  56. Currently supports only the sum
  57. reduction operator.
  58. The reduced values are scaled by the inverse size of the
  59. process group (equivalent to num_gpus).
  60. """
  61. # There is no need for reduction in the single-proc case
  62. if num_gpus == 1:
  63. return tensors
  64. # Queue the reductions
  65. reductions = []
  66. for tensor in tensors:
  67. reduction = torch.distributed.all_reduce(tensor, async_op=True)
  68. reductions.append(reduction)
  69. # Wait for reductions to finish
  70. for reduction in reductions:
  71. reduction.wait()
  72. # Scale the results
  73. for tensor in tensors:
  74. tensor.mul_(1.0 / num_gpus)
  75. return tensors
  76. @torch.no_grad()
  77. def compute_precise_bn_stats(model: nn.Module, loader: torch.utils.data.DataLoader, precise_bn_batch_size: int, num_gpus: int):
  78. """
  79. :param model: The model being trained (ie: Trainer.net)
  80. :param loader: Training dataloader (ie: Trainer.train_loader)
  81. :param precise_bn_batch_size: The effective batch size we want to calculate the batchnorm on. For example, if we are training a model
  82. on 8 gpus, with a batch of 128 on each gpu, a good rule of thumb would be to give it 8192
  83. (ie: effective_batch_size * num_gpus = batch_per_gpu * num_gpus * num_gpus).
  84. If precise_bn_batch_size is not provided in the training_params, the latter heuristic
  85. will be taken.
  86. param num_gpus: The number of gpus we are training on
  87. """
  88. # Compute the number of minibatches to use
  89. num_iter = int(precise_bn_batch_size / (loader.batch_size * num_gpus)) if precise_bn_batch_size else num_gpus
  90. num_iter = min(num_iter, len(loader))
  91. # Retrieve the BN layers
  92. bns = [m for m in model.modules() if isinstance(m, torch.nn.BatchNorm2d)]
  93. # Initialize BN stats storage for computing mean(mean(batch)) and mean(var(batch))
  94. running_means = [torch.zeros_like(bn.running_mean) for bn in bns]
  95. running_vars = [torch.zeros_like(bn.running_var) for bn in bns]
  96. # Remember momentum values
  97. momentums = [bn.momentum for bn in bns]
  98. # Set momentum to 1.0 to compute BN stats that only reflect the current batch
  99. for bn in bns:
  100. bn.momentum = 1.0
  101. # Average the BN stats for each BN layer over the batches
  102. for inputs, _labels in itertools.islice(loader, num_iter):
  103. model(inputs.cuda())
  104. for i, bn in enumerate(bns):
  105. running_means[i] += bn.running_mean / num_iter
  106. running_vars[i] += bn.running_var / num_iter
  107. # Sync BN stats across GPUs (no reduction if 1 GPU used)
  108. running_means = scaled_all_reduce(running_means, num_gpus=num_gpus)
  109. running_vars = scaled_all_reduce(running_vars, num_gpus=num_gpus)
  110. # Set BN stats and restore original momentum values
  111. for i, bn in enumerate(bns):
  112. bn.running_mean = running_means[i]
  113. bn.running_var = running_vars[i]
  114. bn.momentum = momentums[i]
  115. def get_local_rank():
  116. """
  117. Returns the local rank if running in DDP, and 0 otherwise
  118. :return: local rank
  119. """
  120. return dist.get_rank() if dist.is_initialized() else 0
  121. def require_ddp_setup() -> bool:
  122. return device_config.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL and device_config.assigned_rank != get_local_rank()
  123. def is_ddp_subprocess():
  124. return torch.distributed.get_rank() > 0 if dist.is_initialized() else False
  125. def get_world_size() -> int:
  126. """
  127. Returns the world size if running in DDP, and 1 otherwise
  128. :return: world size
  129. """
  130. if not dist.is_available():
  131. return 1
  132. if not dist.is_initialized():
  133. return 1
  134. return dist.get_world_size()
  135. def get_device_ids() -> List[int]:
  136. return list(range(get_world_size()))
  137. def count_used_devices() -> int:
  138. return len(get_device_ids())
  139. @contextmanager
  140. def wait_for_the_master(local_rank: int):
  141. """
  142. Make all processes waiting for the master to do some task.
  143. """
  144. if local_rank > 0:
  145. dist.barrier()
  146. yield
  147. if local_rank == 0:
  148. if not dist.is_available():
  149. return
  150. if not dist.is_initialized():
  151. return
  152. else:
  153. dist.barrier()
  154. def setup_gpu_mode(gpu_mode: MultiGPUMode = MultiGPUMode.OFF, num_gpus: int = None):
  155. """[DEPRECATED in favor of setup_device] If required, launch ddp subprocesses.
  156. :param gpu_mode: DDP, DP, Off or AUTO
  157. :param num_gpus: Number of GPU's to use. When None, use all available devices on DDP or only one device on DP/OFF.
  158. """
  159. logger.warning("setup_gpu_mode is now deprecated in favor of setup_device")
  160. setup_device(multi_gpu=gpu_mode, num_gpus=num_gpus)
  161. @resolve_param("multi_gpu", TypeFactory(MultiGPUMode.dict()))
  162. def setup_device(multi_gpu: MultiGPUMode = MultiGPUMode.AUTO, num_gpus: int = None, device: str = "cuda"):
  163. """
  164. If required, launch ddp subprocesses.
  165. :param multi_gpu: DDP, DP, Off or AUTO
  166. :param num_gpus: Number of GPU's to use. When None, use all available devices on DDP or only one device on DP/OFF.
  167. """
  168. init_trainer()
  169. # When launching with torch.distributed.launch or torchrun, multi_gpu might not be set to DDP (since we are not using the recipe params)
  170. # To avoid any issue we force multi_gpu to be DDP if the current process is ddp subprocess. We also set num_gpus, device to run smoothly.
  171. if not is_launched_using_sg() and is_distributed():
  172. multi_gpu, num_gpus, device = MultiGPUMode.DISTRIBUTED_DATA_PARALLEL, None, "cuda"
  173. if device is None:
  174. device = "cuda"
  175. if device == "cuda" and not torch.cuda.is_available():
  176. logger.warning("CUDA device is not available on your device... Moving to CPU.")
  177. device = "cpu"
  178. if device == "cpu":
  179. setup_cpu(multi_gpu, num_gpus)
  180. elif device == "cuda":
  181. setup_gpu(multi_gpu, num_gpus)
  182. else:
  183. raise ValueError(f"Only valid values for device are: 'cpu' and 'cuda'. Received: '{device}'")
  184. def setup_cpu(multi_gpu: MultiGPUMode = MultiGPUMode.AUTO, num_gpus: int = None):
  185. """
  186. :param multi_gpu: DDP, DP, Off or AUTO
  187. :param num_gpus: Number of GPU's to use.
  188. """
  189. if multi_gpu not in (MultiGPUMode.OFF, MultiGPUMode.AUTO):
  190. raise ValueError(f"device='cpu' and multi_gpu={multi_gpu} are not compatible together.")
  191. if num_gpus not in (0, None):
  192. raise ValueError(f"device='cpu' and num_gpus={num_gpus} are not compatible together.")
  193. device_config.device = "cpu"
  194. device_config.multi_gpu = MultiGPUMode.OFF
  195. def setup_gpu(multi_gpu: MultiGPUMode = MultiGPUMode.AUTO, num_gpus: int = None):
  196. """
  197. If required, launch ddp subprocesses.
  198. :param multi_gpu: DDP, DP, Off or AUTO
  199. :param num_gpus: Number of GPU's to use. When None, use all available devices on DDP or only one device on DP/OFF.
  200. """
  201. if num_gpus == 0:
  202. raise ValueError("device='cuda' and num_gpus=0 are not compatible together.")
  203. multi_gpu, num_gpus = _resolve_gpu_params(multi_gpu=multi_gpu, num_gpus=num_gpus)
  204. device_config.device = "cuda"
  205. device_config.multi_gpu = multi_gpu
  206. if is_distributed():
  207. initialize_ddp()
  208. elif multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL:
  209. restart_script_with_ddp(num_gpus=num_gpus)
  210. def _resolve_gpu_params(multi_gpu: MultiGPUMode, num_gpus: int) -> Tuple[MultiGPUMode, int]:
  211. """
  212. Resolve the values multi_gpu in (None, MultiGPUMode.AUTO) and num_gpus in (None, -1), and check compatibility between both parameters.
  213. :param multi_gpu: DDP, DP, Off or AUTO
  214. :param num_gpus: Number of GPU's to use. When None, use all available devices on DDP or only one device on DP/OFF.
  215. """
  216. # Resolve None
  217. if multi_gpu is None:
  218. if num_gpus is None: # When Nothing is specified, just run on single GPU
  219. multi_gpu = MultiGPUMode.OFF
  220. num_gpus = 1
  221. else:
  222. multi_gpu = MultiGPUMode.AUTO
  223. if num_gpus is None:
  224. num_gpus = -1
  225. # Resolve multi_gpu
  226. if num_gpus == -1:
  227. if multi_gpu in (MultiGPUMode.OFF, MultiGPUMode.DATA_PARALLEL):
  228. num_gpus = 1
  229. elif multi_gpu in (MultiGPUMode.AUTO, MultiGPUMode.DISTRIBUTED_DATA_PARALLEL):
  230. num_gpus = torch.cuda.device_count()
  231. # Resolve multi_gpu
  232. if multi_gpu == MultiGPUMode.AUTO:
  233. if num_gpus > 1:
  234. multi_gpu = MultiGPUMode.DISTRIBUTED_DATA_PARALLEL
  235. else:
  236. multi_gpu = MultiGPUMode.OFF
  237. # Check compatibility between num_gpus and multi_gpu
  238. if multi_gpu in (MultiGPUMode.OFF, MultiGPUMode.DATA_PARALLEL):
  239. if num_gpus != 1:
  240. raise ValueError(f"You specified num_gpus={num_gpus} but it has not be 1 on when working with multi_gpu={multi_gpu}")
  241. else:
  242. if num_gpus > torch.cuda.device_count():
  243. raise ValueError(f"You specified num_gpus={num_gpus} but only {torch.cuda.device_count()} GPU's are available")
  244. return multi_gpu, num_gpus
  245. def initialize_ddp():
  246. """
  247. Initialize Distributed Data Parallel
  248. Important note: (1) in distributed training it is customary to specify learning rates and batch sizes per GPU.
  249. Whatever learning rate and schedule you specify will be applied to the each GPU individually.
  250. Since gradients are passed and summed (reduced) from all to all GPUs, the effective batch size is the
  251. batch you specify times the number of GPUs. In the literature there are several "best practices" to set
  252. learning rates and schedules for large batch sizes.
  253. """
  254. if device_config.assigned_rank > 0:
  255. mute_current_process()
  256. logger.info("Distributed training starting...")
  257. if not torch.distributed.is_initialized():
  258. backend = "gloo" if os.name == "nt" else "nccl"
  259. torch.distributed.init_process_group(backend=backend, init_method="env://")
  260. torch.cuda.set_device(device_config.assigned_rank)
  261. if torch.distributed.get_rank() == 0:
  262. logger.info(f"Training in distributed mode... with {str(torch.distributed.get_world_size())} GPUs")
  263. device_config.device = "cuda:%d" % device_config.assigned_rank
  264. @record
  265. def restart_script_with_ddp(num_gpus: int = None):
  266. """Launch the same script as the one that was launched (i.e. the command used to start the current process is re-used) but on subprocesses (i.e. with DDP).
  267. :param num_gpus: How many gpu's you want to run the script on. If not specified, every available device will be used.
  268. """
  269. ddp_port = find_free_port()
  270. # Get the value fom recipe if specified, otherwise take all available devices.
  271. num_gpus = num_gpus if num_gpus is not None else torch.cuda.device_count()
  272. if num_gpus > torch.cuda.device_count():
  273. raise ValueError(f"You specified num_gpus={num_gpus} but only {torch.cuda.device_count()} GPU's are available")
  274. logger.info(
  275. "Launching DDP with:\n"
  276. f" - ddp_port = {ddp_port}\n"
  277. f" - num_gpus = {num_gpus}/{torch.cuda.device_count()} available\n"
  278. "-------------------------------------\n"
  279. )
  280. config = LaunchConfig(
  281. nproc_per_node=num_gpus,
  282. min_nodes=1,
  283. max_nodes=1,
  284. run_id="sg_initiated",
  285. role="default",
  286. rdzv_endpoint=f"127.0.0.1:{ddp_port}",
  287. rdzv_backend="static",
  288. rdzv_configs={"rank": 0, "timeout": 900},
  289. rdzv_timeout=-1,
  290. max_restarts=0,
  291. monitor_interval=5,
  292. start_method="spawn",
  293. log_dir=None,
  294. redirects=Std.NONE,
  295. tee=Std.NONE,
  296. metrics_cfg={},
  297. )
  298. elastic_launch(config=config, entrypoint=sys.executable)(*sys.argv, *EXTRA_ARGS)
  299. # The code below should actually never be reached as the process will be in a loop inside elastic_launch until any subprocess crashes.
  300. sys.exit(0)
  301. def get_gpu_mem_utilization():
  302. """GPU memory managed by the caching allocator in bytes for a given device."""
  303. # Workaround to work on any torch version
  304. if hasattr(torch.cuda, "memory_reserved"):
  305. return torch.cuda.memory_reserved()
  306. else:
  307. return torch.cuda.memory_cached()
  308. class DDPNotSetupException(Exception):
  309. """
  310. Exception raised when DDP setup is required but was not done
  311. Attributes:
  312. message -- explanation of the error
  313. """
  314. def __init__(self):
  315. self.message = (
  316. "Your environment was not setup correctly for DDP.\n"
  317. "Please run at the beginning of your script:\n"
  318. ">>> from super_gradients.training.utils.distributed_training_utils import setup_device'\n"
  319. ">>> from super_gradients.common.data_types.enum import MultiGPUMode\n"
  320. ">>> setup_device(multi_gpu=MultiGPUMode.DISTRIBUTED_DATA_PARALLEL, num_gpus=...)"
  321. )
  322. super().__init__(self.message)
Discard
Tip!

Press p or to see the previous file or, n or to see the next file