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

#364 build_model refs replaced

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:hotfix/SG-000_remove_build_model
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
  1. import sys
  2. import itertools
  3. from contextlib import contextmanager
  4. import torch
  5. import torch.nn as nn
  6. from torch import distributed as dist
  7. from torch.cuda.amp import autocast
  8. from torch.distributed.elastic.multiprocessing import Std
  9. from torch.distributed.elastic.multiprocessing.errors import record
  10. from torch.distributed.launcher.api import LaunchConfig, elastic_launch
  11. from super_gradients.common.data_types.enum import MultiGPUMode
  12. from super_gradients.common.environment.env_helpers import find_free_port, is_distributed
  13. from super_gradients.common.abstractions.abstract_logger import get_logger
  14. logger = get_logger(__name__)
  15. def distributed_all_reduce_tensor_average(tensor, n):
  16. """
  17. This method performs a reduce operation on multiple nodes running distributed training
  18. It first sums all of the results and then divides the summation
  19. :param tensor: The tensor to perform the reduce operation for
  20. :param n: Number of nodes
  21. :return: Averaged tensor from all of the nodes
  22. """
  23. rt = tensor.clone()
  24. torch.distributed.all_reduce(rt, op=torch.distributed.ReduceOp.SUM)
  25. rt /= n
  26. return rt
  27. def reduce_results_tuple_for_ddp(validation_results_tuple, device):
  28. """Gather all validation tuples from the various devices and average them"""
  29. validation_results_list = list(validation_results_tuple)
  30. for i, validation_result in enumerate(validation_results_list):
  31. validation_results_list[i] = distributed_all_reduce_tensor_average(torch.tensor(validation_result).to(device),
  32. torch.distributed.get_world_size())
  33. validation_results_tuple = tuple(validation_results_list)
  34. return validation_results_tuple
  35. class MultiGPUModeAutocastWrapper():
  36. def __init__(self, func):
  37. self.func = func
  38. def __call__(self, *args, **kwargs):
  39. with autocast():
  40. out = self.func(*args, **kwargs)
  41. return out
  42. def scaled_all_reduce(tensors: torch.Tensor, num_gpus: int):
  43. """
  44. Performs the scaled all_reduce operation on the provided tensors.
  45. The input tensors are modified in-place.
  46. Currently supports only the sum
  47. reduction operator.
  48. The reduced values are scaled by the inverse size of the
  49. process group (equivalent to num_gpus).
  50. """
  51. # There is no need for reduction in the single-proc case
  52. if num_gpus == 1:
  53. return tensors
  54. # Queue the reductions
  55. reductions = []
  56. for tensor in tensors:
  57. reduction = torch.distributed.all_reduce(tensor, async_op=True)
  58. reductions.append(reduction)
  59. # Wait for reductions to finish
  60. for reduction in reductions:
  61. reduction.wait()
  62. # Scale the results
  63. for tensor in tensors:
  64. tensor.mul_(1.0 / num_gpus)
  65. return tensors
  66. @torch.no_grad()
  67. def compute_precise_bn_stats(model: nn.Module, loader: torch.utils.data.DataLoader, precise_bn_batch_size: int, num_gpus: int):
  68. '''
  69. :param model: The model being trained (ie: Trainer.net)
  70. :param loader: Training dataloader (ie: Trainer.train_loader)
  71. :param precise_bn_batch_size: The effective batch size we want to calculate the batchnorm on. For example, if we are training a model
  72. on 8 gpus, with a batch of 128 on each gpu, a good rule of thumb would be to give it 8192
  73. (ie: effective_batch_size * num_gpus = batch_per_gpu * num_gpus * num_gpus).
  74. If precise_bn_batch_size is not provided in the training_params, the latter heuristic
  75. will be taken.
  76. param num_gpus: The number of gpus we are training on
  77. '''
  78. # Compute the number of minibatches to use
  79. num_iter = int(precise_bn_batch_size / (loader.batch_size * num_gpus)) if precise_bn_batch_size else num_gpus
  80. num_iter = min(num_iter, len(loader))
  81. # Retrieve the BN layers
  82. bns = [m for m in model.modules() if isinstance(m, torch.nn.BatchNorm2d)]
  83. # Initialize BN stats storage for computing mean(mean(batch)) and mean(var(batch))
  84. running_means = [torch.zeros_like(bn.running_mean) for bn in bns]
  85. running_vars = [torch.zeros_like(bn.running_var) for bn in bns]
  86. # Remember momentum values
  87. momentums = [bn.momentum for bn in bns]
  88. # Set momentum to 1.0 to compute BN stats that only reflect the current batch
  89. for bn in bns:
  90. bn.momentum = 1.0
  91. # Average the BN stats for each BN layer over the batches
  92. for inputs, _labels in itertools.islice(loader, num_iter):
  93. model(inputs.cuda())
  94. for i, bn in enumerate(bns):
  95. running_means[i] += bn.running_mean / num_iter
  96. running_vars[i] += bn.running_var / num_iter
  97. # Sync BN stats across GPUs (no reduction if 1 GPU used)
  98. running_means = scaled_all_reduce(running_means, num_gpus=num_gpus)
  99. running_vars = scaled_all_reduce(running_vars, num_gpus=num_gpus)
  100. # Set BN stats and restore original momentum values
  101. for i, bn in enumerate(bns):
  102. bn.running_mean = running_means[i]
  103. bn.running_var = running_vars[i]
  104. bn.momentum = momentums[i]
  105. def get_local_rank():
  106. """
  107. Returns the local rank if running in DDP, and 0 otherwise
  108. :return: local rank
  109. """
  110. return dist.get_rank() if dist.is_initialized() else 0
  111. def get_world_size() -> int:
  112. """
  113. Returns the world size if running in DDP, and 1 otherwise
  114. :return: world size
  115. """
  116. if not dist.is_available():
  117. return 1
  118. if not dist.is_initialized():
  119. return 1
  120. return dist.get_world_size()
  121. @contextmanager
  122. def wait_for_the_master(local_rank: int):
  123. """
  124. Make all processes waiting for the master to do some task.
  125. """
  126. if local_rank > 0:
  127. dist.barrier()
  128. yield
  129. if local_rank == 0:
  130. if not dist.is_available():
  131. return
  132. if not dist.is_initialized():
  133. return
  134. else:
  135. dist.barrier()
  136. def setup_gpu_mode(gpu_mode: MultiGPUMode = MultiGPUMode.OFF, num_gpus: int = None):
  137. """
  138. If required, launch ddp subprocesses.
  139. :param gpu_mode: DDP, DP or Off
  140. :param num_gpus: Number of GPU's to use.
  141. """
  142. if require_gpu_setup(gpu_mode):
  143. num_gpus = num_gpus or torch.cuda.device_count()
  144. if num_gpus > torch.cuda.device_count():
  145. raise ValueError(f"You specified num_gpus={num_gpus} but only {torch.cuda.device_count()} GPU's are available")
  146. restart_script_with_ddp(num_gpus)
  147. def require_gpu_setup(gpu_mode: MultiGPUMode) -> bool:
  148. """Check if the environment requires a setup in order to work with DDP."""
  149. return (gpu_mode == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL) and (not is_distributed())
  150. @record
  151. def restart_script_with_ddp(num_gpus: int = None):
  152. """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).
  153. :param num_gpus: How many gpu's you want to run the script on. If not specified, every available device will be used.
  154. """
  155. ddp_port = find_free_port()
  156. # Get the value fom recipe if specified, otherwise take all available devices.
  157. num_gpus = num_gpus if num_gpus else torch.cuda.device_count()
  158. if num_gpus > torch.cuda.device_count():
  159. raise ValueError(f"You specified num_gpus={num_gpus} but only {torch.cuda.device_count()} GPU's are available")
  160. logger.info("Launching DDP with:\n"
  161. f" - ddp_port = {ddp_port}\n"
  162. f" - num_gpus = {num_gpus}/{torch.cuda.device_count()} available\n"
  163. "-------------------------------------")
  164. config = LaunchConfig(
  165. nproc_per_node=num_gpus,
  166. min_nodes=1,
  167. max_nodes=1,
  168. run_id='none',
  169. role='default',
  170. rdzv_endpoint=f'127.0.0.1:{ddp_port}',
  171. rdzv_backend='static',
  172. rdzv_configs={'rank': 0, 'timeout': 900},
  173. rdzv_timeout=-1,
  174. max_restarts=0,
  175. monitor_interval=5,
  176. start_method='spawn',
  177. log_dir=None,
  178. redirects=Std.NONE,
  179. tee=Std.NONE,
  180. metrics_cfg={})
  181. elastic_launch(config=config, entrypoint=sys.executable)(*sys.argv)
  182. # The code below should actually never be reached as the process will be in a loop inside elastic_launch until any subprocess crashes.
  183. sys.exit("Main process finished")
Discard
Tip!

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