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 9.0 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
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
  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 ConfusionMatrix:
  53. def __init__(self, num_classes):
  54. self.num_classes = num_classes
  55. self.mat = None
  56. def update(self, a, b):
  57. n = self.num_classes
  58. if self.mat is None:
  59. self.mat = torch.zeros((n, n), dtype=torch.int64, device=a.device)
  60. with torch.inference_mode():
  61. k = (a >= 0) & (a < n)
  62. inds = n * a[k].to(torch.int64) + b[k]
  63. self.mat += torch.bincount(inds, minlength=n**2).reshape(n, n)
  64. def reset(self):
  65. self.mat.zero_()
  66. def compute(self):
  67. h = self.mat.float()
  68. acc_global = torch.diag(h).sum() / h.sum()
  69. acc = torch.diag(h) / h.sum(1)
  70. iu = torch.diag(h) / (h.sum(1) + h.sum(0) - torch.diag(h))
  71. return acc_global, acc, iu
  72. def reduce_from_all_processes(self):
  73. self.mat = reduce_across_processes(self.mat).to(torch.int64)
  74. def __str__(self):
  75. acc_global, acc, iu = self.compute()
  76. return ("global correct: {:.1f}\naverage row correct: {}\nIoU: {}\nmean IoU: {:.1f}").format(
  77. acc_global.item() * 100,
  78. [f"{i:.1f}" for i in (acc * 100).tolist()],
  79. [f"{i:.1f}" for i in (iu * 100).tolist()],
  80. iu.mean().item() * 100,
  81. )
  82. class MetricLogger:
  83. def __init__(self, delimiter="\t"):
  84. self.meters = defaultdict(SmoothedValue)
  85. self.delimiter = delimiter
  86. def update(self, **kwargs):
  87. for k, v in kwargs.items():
  88. if isinstance(v, torch.Tensor):
  89. v = v.item()
  90. if not isinstance(v, (float, int)):
  91. raise TypeError(
  92. f"This method expects the value of the input arguments to be of type float or int, instead got {type(v)}"
  93. )
  94. self.meters[k].update(v)
  95. def __getattr__(self, attr):
  96. if attr in self.meters:
  97. return self.meters[attr]
  98. if attr in self.__dict__:
  99. return self.__dict__[attr]
  100. raise AttributeError(f"'{type(self).__name__}' object has no attribute '{attr}'")
  101. def __str__(self):
  102. loss_str = []
  103. for name, meter in self.meters.items():
  104. loss_str.append(f"{name}: {str(meter)}")
  105. return self.delimiter.join(loss_str)
  106. def synchronize_between_processes(self):
  107. for meter in self.meters.values():
  108. meter.synchronize_between_processes()
  109. def add_meter(self, name, meter):
  110. self.meters[name] = meter
  111. def log_every(self, iterable, print_freq, header=None):
  112. i = 0
  113. if not header:
  114. header = ""
  115. start_time = time.time()
  116. end = time.time()
  117. iter_time = SmoothedValue(fmt="{avg:.4f}")
  118. data_time = SmoothedValue(fmt="{avg:.4f}")
  119. space_fmt = ":" + str(len(str(len(iterable)))) + "d"
  120. if torch.cuda.is_available():
  121. log_msg = self.delimiter.join(
  122. [
  123. header,
  124. "[{0" + space_fmt + "}/{1}]",
  125. "eta: {eta}",
  126. "{meters}",
  127. "time: {time}",
  128. "data: {data}",
  129. "max mem: {memory:.0f}",
  130. ]
  131. )
  132. else:
  133. log_msg = self.delimiter.join(
  134. [header, "[{0" + space_fmt + "}/{1}]", "eta: {eta}", "{meters}", "time: {time}", "data: {data}"]
  135. )
  136. MB = 1024.0 * 1024.0
  137. for obj in iterable:
  138. data_time.update(time.time() - end)
  139. yield obj
  140. iter_time.update(time.time() - end)
  141. if i % print_freq == 0:
  142. eta_seconds = iter_time.global_avg * (len(iterable) - i)
  143. eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
  144. if torch.cuda.is_available():
  145. print(
  146. log_msg.format(
  147. i,
  148. len(iterable),
  149. eta=eta_string,
  150. meters=str(self),
  151. time=str(iter_time),
  152. data=str(data_time),
  153. memory=torch.cuda.max_memory_allocated() / MB,
  154. )
  155. )
  156. else:
  157. print(
  158. log_msg.format(
  159. i, len(iterable), eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time)
  160. )
  161. )
  162. i += 1
  163. end = time.time()
  164. total_time = time.time() - start_time
  165. total_time_str = str(datetime.timedelta(seconds=int(total_time)))
  166. print(f"{header} Total time: {total_time_str}")
  167. def cat_list(images, fill_value=0):
  168. max_size = tuple(max(s) for s in zip(*[img.shape for img in images]))
  169. batch_shape = (len(images),) + max_size
  170. batched_imgs = images[0].new(*batch_shape).fill_(fill_value)
  171. for img, pad_img in zip(images, batched_imgs):
  172. pad_img[..., : img.shape[-2], : img.shape[-1]].copy_(img)
  173. return batched_imgs
  174. def collate_fn(batch):
  175. images, targets = list(zip(*batch))
  176. batched_imgs = cat_list(images, fill_value=0)
  177. batched_targets = cat_list(targets, fill_value=255)
  178. return batched_imgs, batched_targets
  179. def mkdir(path):
  180. try:
  181. os.makedirs(path)
  182. except OSError as e:
  183. if e.errno != errno.EEXIST:
  184. raise
  185. def setup_for_distributed(is_master):
  186. """
  187. This function disables printing when not in master process
  188. """
  189. import builtins as __builtin__
  190. builtin_print = __builtin__.print
  191. def print(*args, **kwargs):
  192. force = kwargs.pop("force", False)
  193. if is_master or force:
  194. builtin_print(*args, **kwargs)
  195. __builtin__.print = print
  196. def is_dist_avail_and_initialized():
  197. if not dist.is_available():
  198. return False
  199. if not dist.is_initialized():
  200. return False
  201. return True
  202. def get_world_size():
  203. if not is_dist_avail_and_initialized():
  204. return 1
  205. return dist.get_world_size()
  206. def get_rank():
  207. if not is_dist_avail_and_initialized():
  208. return 0
  209. return dist.get_rank()
  210. def is_main_process():
  211. return get_rank() == 0
  212. def save_on_master(*args, **kwargs):
  213. if is_main_process():
  214. torch.save(*args, **kwargs)
  215. def init_distributed_mode(args):
  216. if "RANK" in os.environ and "WORLD_SIZE" in os.environ:
  217. args.rank = int(os.environ["RANK"])
  218. args.world_size = int(os.environ["WORLD_SIZE"])
  219. args.gpu = int(os.environ["LOCAL_RANK"])
  220. # elif "SLURM_PROCID" in os.environ:
  221. # args.rank = int(os.environ["SLURM_PROCID"])
  222. # args.gpu = args.rank % torch.cuda.device_count()
  223. elif hasattr(args, "rank"):
  224. pass
  225. else:
  226. print("Not using distributed mode")
  227. args.distributed = False
  228. return
  229. args.distributed = True
  230. torch.cuda.set_device(args.gpu)
  231. args.dist_backend = "nccl"
  232. print(f"| distributed init (rank {args.rank}): {args.dist_url}", flush=True)
  233. torch.distributed.init_process_group(
  234. backend=args.dist_backend, init_method=args.dist_url, world_size=args.world_size, rank=args.rank
  235. )
  236. torch.distributed.barrier()
  237. setup_for_distributed(args.rank == 0)
  238. def reduce_across_processes(val):
  239. if not is_dist_avail_and_initialized():
  240. # nothing to sync, but we still convert to tensor for consistency with the distributed case.
  241. return torch.tensor(val)
  242. t = torch.tensor(val, device="cuda")
  243. dist.barrier()
  244. dist.all_reduce(t)
  245. return t
Tip!

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

Comments

Loading...