Track a series of values and provide access to smoothed values over a window or the global series average.
| 153 | |
| 154 | |
| 155 | class SmoothedValue: |
| 156 | """Track a series of values and provide access to smoothed values over a |
| 157 | window or the global series average. |
| 158 | """ |
| 159 | |
| 160 | def __init__(self, window_size=20, fmt=None): |
| 161 | if fmt is None: |
| 162 | fmt = "{median:.4f} ({global_avg:.4f})" |
| 163 | self.deque = deque(maxlen=window_size) |
| 164 | self.total = 0.0 |
| 165 | self.count = 0 |
| 166 | self.fmt = fmt |
| 167 | |
| 168 | def update(self, value, num=1): |
| 169 | self.deque.append(value) |
| 170 | self.count += num |
| 171 | self.total += value * num |
| 172 | |
| 173 | def synchronize_between_processes(self): |
| 174 | """ |
| 175 | Distributed synchronization of the metric |
| 176 | Warning: does not synchronize the deque! |
| 177 | """ |
| 178 | if not distributed.is_enabled(): |
| 179 | return |
| 180 | t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda") |
| 181 | torch.distributed.barrier() |
| 182 | torch.distributed.all_reduce(t) |
| 183 | t = t.tolist() |
| 184 | self.count = int(t[0]) |
| 185 | self.total = t[1] |
| 186 | |
| 187 | @property |
| 188 | def median(self): |
| 189 | d = torch.tensor(list(self.deque)) |
| 190 | return d.median().item() |
| 191 | |
| 192 | @property |
| 193 | def avg(self): |
| 194 | d = torch.tensor(list(self.deque), dtype=torch.float32) |
| 195 | return d.mean().item() |
| 196 | |
| 197 | @property |
| 198 | def global_avg(self): |
| 199 | return self.total / self.count |
| 200 | |
| 201 | @property |
| 202 | def max(self): |
| 203 | return max(self.deque) |
| 204 | |
| 205 | @property |
| 206 | def value(self): |
| 207 | return self.deque[-1] |
| 208 | |
| 209 | def __str__(self): |
| 210 | return self.fmt.format( |
| 211 | median=self.median, |
| 212 | avg=self.avg, |