Track a series of values and provide access to smoothed values over a window or the global series average.
| 38 | |
| 39 | # From https://github.com/facebookresearch/detr/blob/master/util/misc.py |
| 40 | class SmoothedValue(object): |
| 41 | """Track a series of values and provide access to smoothed values over a |
| 42 | window or the global series average. |
| 43 | """ |
| 44 | |
| 45 | def __init__(self, window_size=20, fmt=None): |
| 46 | if fmt is None: |
| 47 | fmt = "{median:.4f} ({global_avg:.4f})" |
| 48 | self.deque = deque(maxlen=window_size) |
| 49 | self.total = 0.0 |
| 50 | self.count = 0 |
| 51 | self.fmt = fmt |
| 52 | |
| 53 | def update(self, value, n=1): |
| 54 | self.deque.append(value) |
| 55 | self.count += n |
| 56 | self.total += value * n |
| 57 | |
| 58 | def synchronize_between_processes(self): |
| 59 | """ |
| 60 | Warning: does not synchronize the deque! |
| 61 | """ |
| 62 | if not is_distributed(): |
| 63 | return |
| 64 | t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda") |
| 65 | barrier() |
| 66 | all_reduce_sum(t) |
| 67 | t = t.tolist() |
| 68 | self.count = int(t[0]) |
| 69 | self.total = t[1] |
| 70 | |
| 71 | @property |
| 72 | def median(self): |
| 73 | d = torch.tensor(list(self.deque)) |
| 74 | return d.median().item() |
| 75 | |
| 76 | @property |
| 77 | def avg(self): |
| 78 | d = torch.tensor(list(self.deque), dtype=torch.float32) |
| 79 | return d.mean().item() |
| 80 | |
| 81 | @property |
| 82 | def global_avg(self): |
| 83 | return self.total / self.count |
| 84 | |
| 85 | @property |
| 86 | def max(self): |
| 87 | return max(self.deque) |
| 88 | |
| 89 | @property |
| 90 | def value(self): |
| 91 | return self.deque[-1] |
| 92 | |
| 93 | def __str__(self): |
| 94 | return self.fmt.format( |
| 95 | median=self.median, |
| 96 | avg=self.avg, |
| 97 | global_avg=self.global_avg, |