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.4 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
  1. import datetime
  2. import os
  3. import time
  4. from collections import defaultdict, deque
  5. import torch
  6. import torch.distributed as dist
  7. import torch.nn.functional as F
  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="{median:.4f} ({global_avg:.4f})"):
  13. self.deque = deque(maxlen=window_size)
  14. self.total = 0.0
  15. self.count = 0
  16. self.fmt = fmt
  17. def update(self, value, n=1):
  18. self.deque.append(value)
  19. self.count += n
  20. self.total += value * n
  21. def synchronize_between_processes(self):
  22. """
  23. Warning: does not synchronize the deque!
  24. """
  25. t = reduce_across_processes([self.count, self.total])
  26. t = t.tolist()
  27. self.count = int(t[0])
  28. self.total = t[1]
  29. @property
  30. def median(self):
  31. d = torch.tensor(list(self.deque))
  32. return d.median().item()
  33. @property
  34. def avg(self):
  35. d = torch.tensor(list(self.deque), dtype=torch.float32)
  36. return d.mean().item()
  37. @property
  38. def global_avg(self):
  39. return self.total / self.count
  40. @property
  41. def max(self):
  42. return max(self.deque)
  43. @property
  44. def value(self):
  45. return self.deque[-1]
  46. def __str__(self):
  47. return self.fmt.format(
  48. median=self.median, avg=self.avg, global_avg=self.global_avg, max=self.max, value=self.value
  49. )
  50. class MetricLogger:
  51. def __init__(self, delimiter="\t"):
  52. self.meters = defaultdict(SmoothedValue)
  53. self.delimiter = delimiter
  54. def update(self, **kwargs):
  55. for k, v in kwargs.items():
  56. if isinstance(v, torch.Tensor):
  57. v = v.item()
  58. if not isinstance(v, (float, int)):
  59. raise TypeError(
  60. f"This method expects the value of the input arguments to be of type float or int, instead got {type(v)}"
  61. )
  62. self.meters[k].update(v)
  63. def __getattr__(self, attr):
  64. if attr in self.meters:
  65. return self.meters[attr]
  66. if attr in self.__dict__:
  67. return self.__dict__[attr]
  68. raise AttributeError(f"'{type(self).__name__}' object has no attribute '{attr}'")
  69. def __str__(self):
  70. loss_str = []
  71. for name, meter in self.meters.items():
  72. loss_str.append(f"{name}: {str(meter)}")
  73. return self.delimiter.join(loss_str)
  74. def synchronize_between_processes(self):
  75. for meter in self.meters.values():
  76. meter.synchronize_between_processes()
  77. def add_meter(self, name, **kwargs):
  78. self.meters[name] = SmoothedValue(**kwargs)
  79. def log_every(self, iterable, print_freq=5, header=None):
  80. i = 0
  81. if not header:
  82. header = ""
  83. start_time = time.time()
  84. end = time.time()
  85. iter_time = SmoothedValue(fmt="{avg:.4f}")
  86. data_time = SmoothedValue(fmt="{avg:.4f}")
  87. space_fmt = ":" + str(len(str(len(iterable)))) + "d"
  88. if torch.cuda.is_available():
  89. log_msg = self.delimiter.join(
  90. [
  91. header,
  92. "[{0" + space_fmt + "}/{1}]",
  93. "eta: {eta}",
  94. "{meters}",
  95. "time: {time}",
  96. "data: {data}",
  97. "max mem: {memory:.0f}",
  98. ]
  99. )
  100. else:
  101. log_msg = self.delimiter.join(
  102. [header, "[{0" + space_fmt + "}/{1}]", "eta: {eta}", "{meters}", "time: {time}", "data: {data}"]
  103. )
  104. MB = 1024.0 * 1024.0
  105. for obj in iterable:
  106. data_time.update(time.time() - end)
  107. yield obj
  108. iter_time.update(time.time() - end)
  109. if print_freq is not None and i % print_freq == 0:
  110. eta_seconds = iter_time.global_avg * (len(iterable) - i)
  111. eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
  112. if torch.cuda.is_available():
  113. print(
  114. log_msg.format(
  115. i,
  116. len(iterable),
  117. eta=eta_string,
  118. meters=str(self),
  119. time=str(iter_time),
  120. data=str(data_time),
  121. memory=torch.cuda.max_memory_allocated() / MB,
  122. )
  123. )
  124. else:
  125. print(
  126. log_msg.format(
  127. i, len(iterable), eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time)
  128. )
  129. )
  130. i += 1
  131. end = time.time()
  132. total_time = time.time() - start_time
  133. total_time_str = str(datetime.timedelta(seconds=int(total_time)))
  134. print(f"{header} Total time: {total_time_str}")
  135. def compute_metrics(flow_pred, flow_gt, valid_flow_mask=None):
  136. epe = ((flow_pred - flow_gt) ** 2).sum(dim=1).sqrt()
  137. flow_norm = (flow_gt**2).sum(dim=1).sqrt()
  138. if valid_flow_mask is not None:
  139. epe = epe[valid_flow_mask]
  140. flow_norm = flow_norm[valid_flow_mask]
  141. relative_epe = epe / flow_norm
  142. metrics = {
  143. "epe": epe.mean().item(),
  144. "1px": (epe < 1).float().mean().item(),
  145. "3px": (epe < 3).float().mean().item(),
  146. "5px": (epe < 5).float().mean().item(),
  147. "f1": ((epe > 3) & (relative_epe > 0.05)).float().mean().item() * 100,
  148. }
  149. return metrics, epe.numel()
  150. def sequence_loss(flow_preds, flow_gt, valid_flow_mask, gamma=0.8, max_flow=400):
  151. """Loss function defined over sequence of flow predictions"""
  152. if gamma > 1:
  153. raise ValueError(f"Gamma should be < 1, got {gamma}.")
  154. # exclude invalid pixels and extremely large diplacements
  155. flow_norm = torch.sum(flow_gt**2, dim=1).sqrt()
  156. valid_flow_mask = valid_flow_mask & (flow_norm < max_flow)
  157. valid_flow_mask = valid_flow_mask[:, None, :, :]
  158. flow_preds = torch.stack(flow_preds) # shape = (num_flow_updates, batch_size, 2, H, W)
  159. abs_diff = (flow_preds - flow_gt).abs()
  160. abs_diff = (abs_diff * valid_flow_mask).mean(axis=(1, 2, 3, 4))
  161. num_predictions = flow_preds.shape[0]
  162. weights = gamma ** torch.arange(num_predictions - 1, -1, -1).to(flow_gt.device)
  163. flow_loss = (abs_diff * weights).sum()
  164. return flow_loss
  165. class InputPadder:
  166. """Pads images such that dimensions are divisible by 8"""
  167. # TODO: Ideally, this should be part of the eval transforms preset, instead
  168. # of being part of the validation code. It's not obvious what a good
  169. # solution would be, because we need to unpad the predicted flows according
  170. # to the input images' size, and in some datasets (Kitti) images can have
  171. # variable sizes.
  172. def __init__(self, dims, mode="sintel"):
  173. self.ht, self.wd = dims[-2:]
  174. pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) % 8
  175. pad_wd = (((self.wd // 8) + 1) * 8 - self.wd) % 8
  176. if mode == "sintel":
  177. self._pad = [pad_wd // 2, pad_wd - pad_wd // 2, pad_ht // 2, pad_ht - pad_ht // 2]
  178. else:
  179. self._pad = [pad_wd // 2, pad_wd - pad_wd // 2, 0, pad_ht]
  180. def pad(self, *inputs):
  181. return [F.pad(x, self._pad, mode="replicate") for x in inputs]
  182. def unpad(self, x):
  183. ht, wd = x.shape[-2:]
  184. c = [self._pad[2], ht - self._pad[3], self._pad[0], wd - self._pad[1]]
  185. return x[..., c[0] : c[1], c[2] : c[3]]
  186. def _redefine_print(is_main):
  187. """disables printing when not in main process"""
  188. import builtins as __builtin__
  189. builtin_print = __builtin__.print
  190. def print(*args, **kwargs):
  191. force = kwargs.pop("force", False)
  192. if is_main or force:
  193. builtin_print(*args, **kwargs)
  194. __builtin__.print = print
  195. def setup_ddp(args):
  196. # Set the local_rank, rank, and world_size values as args fields
  197. # This is done differently depending on how we're running the script. We
  198. # currently support either torchrun or the custom run_with_submitit.py
  199. # If you're confused (like I was), this might help a bit
  200. # https://discuss.pytorch.org/t/what-is-the-difference-between-rank-and-local-rank/61940/2
  201. if all(key in os.environ for key in ("LOCAL_RANK", "RANK", "WORLD_SIZE")):
  202. # if we're here, the script was called with torchrun. Otherwise,
  203. # these args will be set already by the run_with_submitit script
  204. args.local_rank = int(os.environ["LOCAL_RANK"])
  205. args.rank = int(os.environ["RANK"])
  206. args.world_size = int(os.environ["WORLD_SIZE"])
  207. elif "gpu" in args:
  208. # if we're here, the script was called by run_with_submitit.py
  209. args.local_rank = args.gpu
  210. else:
  211. print("Not using distributed mode!")
  212. args.distributed = False
  213. args.world_size = 1
  214. return
  215. args.distributed = True
  216. _redefine_print(is_main=(args.rank == 0))
  217. torch.cuda.set_device(args.local_rank)
  218. dist.init_process_group(
  219. backend="nccl",
  220. rank=args.rank,
  221. world_size=args.world_size,
  222. init_method=args.dist_url,
  223. )
  224. torch.distributed.barrier()
  225. def reduce_across_processes(val):
  226. t = torch.tensor(val, device="cuda")
  227. dist.barrier()
  228. dist.all_reduce(t)
  229. return t
  230. def freeze_batch_norm(model):
  231. for m in model.modules():
  232. if isinstance(m, torch.nn.BatchNorm2d):
  233. m.eval()
Tip!

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

Comments

Loading...