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

utils.py 7.7 KB

You have to be logged in to leave a comment. Sign In
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
  1. import datetime
  2. import errno
  3. import os
  4. import time
  5. from collections import defaultdict, deque
  6. import torch
  7. import torch.distributed as dist
  8. class SmoothedValue:
  9. """Track a series of values and provide access to smoothed values over a
  10. window or the global series average.
  11. """
  12. def __init__(self, window_size=20, fmt=None):
  13. if fmt is None:
  14. fmt = "{median:.4f} ({global_avg:.4f})"
  15. self.deque = deque(maxlen=window_size)
  16. self.total = 0.0
  17. self.count = 0
  18. self.fmt = fmt
  19. def update(self, value, n=1):
  20. self.deque.append(value)
  21. self.count += n
  22. self.total += value * n
  23. def synchronize_between_processes(self):
  24. """
  25. Warning: does not synchronize the deque!
  26. """
  27. t = reduce_across_processes([self.count, self.total])
  28. t = t.tolist()
  29. self.count = int(t[0])
  30. self.total = t[1]
  31. @property
  32. def median(self):
  33. d = torch.tensor(list(self.deque))
  34. return d.median().item()
  35. @property
  36. def avg(self):
  37. d = torch.tensor(list(self.deque), dtype=torch.float32)
  38. return d.mean().item()
  39. @property
  40. def global_avg(self):
  41. return self.total / self.count
  42. @property
  43. def max(self):
  44. return max(self.deque)
  45. @property
  46. def value(self):
  47. return self.deque[-1]
  48. def __str__(self):
  49. return self.fmt.format(
  50. median=self.median, avg=self.avg, global_avg=self.global_avg, max=self.max, value=self.value
  51. )
  52. class MetricLogger:
  53. def __init__(self, delimiter="\t"):
  54. self.meters = defaultdict(SmoothedValue)
  55. self.delimiter = delimiter
  56. def update(self, **kwargs):
  57. for k, v in kwargs.items():
  58. if isinstance(v, torch.Tensor):
  59. v = v.item()
  60. if not isinstance(v, (float, int)):
  61. raise TypeError(
  62. f"This method expects the value of the input arguments to be of type float or int, instead got {type(v)}"
  63. )
  64. self.meters[k].update(v)
  65. def __getattr__(self, attr):
  66. if attr in self.meters:
  67. return self.meters[attr]
  68. if attr in self.__dict__:
  69. return self.__dict__[attr]
  70. raise AttributeError(f"'{type(self).__name__}' object has no attribute '{attr}'")
  71. def __str__(self):
  72. loss_str = []
  73. for name, meter in self.meters.items():
  74. loss_str.append(f"{name}: {str(meter)}")
  75. return self.delimiter.join(loss_str)
  76. def synchronize_between_processes(self):
  77. for meter in self.meters.values():
  78. meter.synchronize_between_processes()
  79. def add_meter(self, name, meter):
  80. self.meters[name] = meter
  81. def log_every(self, iterable, print_freq, header=None):
  82. i = 0
  83. if not header:
  84. header = ""
  85. start_time = time.time()
  86. end = time.time()
  87. iter_time = SmoothedValue(fmt="{avg:.4f}")
  88. data_time = SmoothedValue(fmt="{avg:.4f}")
  89. space_fmt = ":" + str(len(str(len(iterable)))) + "d"
  90. if torch.cuda.is_available():
  91. log_msg = self.delimiter.join(
  92. [
  93. header,
  94. "[{0" + space_fmt + "}/{1}]",
  95. "eta: {eta}",
  96. "{meters}",
  97. "time: {time}",
  98. "data: {data}",
  99. "max mem: {memory:.0f}",
  100. ]
  101. )
  102. else:
  103. log_msg = self.delimiter.join(
  104. [header, "[{0" + space_fmt + "}/{1}]", "eta: {eta}", "{meters}", "time: {time}", "data: {data}"]
  105. )
  106. MB = 1024.0 * 1024.0
  107. for obj in iterable:
  108. data_time.update(time.time() - end)
  109. yield obj
  110. iter_time.update(time.time() - end)
  111. if i % print_freq == 0:
  112. eta_seconds = iter_time.global_avg * (len(iterable) - i)
  113. eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
  114. if torch.cuda.is_available():
  115. print(
  116. log_msg.format(
  117. i,
  118. len(iterable),
  119. eta=eta_string,
  120. meters=str(self),
  121. time=str(iter_time),
  122. data=str(data_time),
  123. memory=torch.cuda.max_memory_allocated() / MB,
  124. )
  125. )
  126. else:
  127. print(
  128. log_msg.format(
  129. i, len(iterable), eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time)
  130. )
  131. )
  132. i += 1
  133. end = time.time()
  134. total_time = time.time() - start_time
  135. total_time_str = str(datetime.timedelta(seconds=int(total_time)))
  136. print(f"{header} Total time: {total_time_str}")
  137. def accuracy(output, target, topk=(1,)):
  138. """Computes the accuracy over the k top predictions for the specified values of k"""
  139. with torch.inference_mode():
  140. maxk = max(topk)
  141. batch_size = target.size(0)
  142. _, pred = output.topk(maxk, 1, True, True)
  143. pred = pred.t()
  144. correct = pred.eq(target[None])
  145. res = []
  146. for k in topk:
  147. correct_k = correct[:k].flatten().sum(dtype=torch.float32)
  148. res.append(correct_k * (100.0 / batch_size))
  149. return res
  150. def mkdir(path):
  151. try:
  152. os.makedirs(path)
  153. except OSError as e:
  154. if e.errno != errno.EEXIST:
  155. raise
  156. def setup_for_distributed(is_master):
  157. """
  158. This function disables printing when not in master process
  159. """
  160. import builtins as __builtin__
  161. builtin_print = __builtin__.print
  162. def print(*args, **kwargs):
  163. force = kwargs.pop("force", False)
  164. if is_master or force:
  165. builtin_print(*args, **kwargs)
  166. __builtin__.print = print
  167. def is_dist_avail_and_initialized():
  168. if not dist.is_available():
  169. return False
  170. if not dist.is_initialized():
  171. return False
  172. return True
  173. def get_world_size():
  174. if not is_dist_avail_and_initialized():
  175. return 1
  176. return dist.get_world_size()
  177. def get_rank():
  178. if not is_dist_avail_and_initialized():
  179. return 0
  180. return dist.get_rank()
  181. def is_main_process():
  182. return get_rank() == 0
  183. def save_on_master(*args, **kwargs):
  184. if is_main_process():
  185. torch.save(*args, **kwargs)
  186. def init_distributed_mode(args):
  187. if "RANK" in os.environ and "WORLD_SIZE" in os.environ:
  188. args.rank = int(os.environ["RANK"])
  189. args.world_size = int(os.environ["WORLD_SIZE"])
  190. args.gpu = int(os.environ["LOCAL_RANK"])
  191. elif "SLURM_PROCID" in os.environ:
  192. args.rank = int(os.environ["SLURM_PROCID"])
  193. args.gpu = args.rank % torch.cuda.device_count()
  194. elif hasattr(args, "rank"):
  195. pass
  196. else:
  197. print("Not using distributed mode")
  198. args.distributed = False
  199. return
  200. args.distributed = True
  201. torch.cuda.set_device(args.gpu)
  202. args.dist_backend = "nccl"
  203. print(f"| distributed init (rank {args.rank}): {args.dist_url}", flush=True)
  204. torch.distributed.init_process_group(
  205. backend=args.dist_backend, init_method=args.dist_url, world_size=args.world_size, rank=args.rank
  206. )
  207. torch.distributed.barrier()
  208. setup_for_distributed(args.rank == 0)
  209. def reduce_across_processes(val, op=dist.ReduceOp.SUM):
  210. if not is_dist_avail_and_initialized():
  211. # nothing to sync, but we still convert to tensor for consistency with the distributed case.
  212. return torch.tensor(val)
  213. t = torch.tensor(val, device="cuda")
  214. dist.barrier()
  215. dist.all_reduce(t, op=op)
  216. return t
Tip!

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

Comments

Loading...