-
Notifications
You must be signed in to change notification settings - Fork 3
/
my_meter.py
65 lines (52 loc) · 1.67 KB
/
my_meter.py
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
# --------------------------------------------------------
# TinyViT Utils
# Copyright (c) 2022 Microsoft
# --------------------------------------------------------
import torch
import torch.distributed as dist
from utils import reduce_tensor
class AverageMeter:
"""Computes and stores the average and current value"""
def __init__(self):
self._world_size = dist.get_world_size()
self.reset()
def reset(self):
# local
self._val = 0
self._sum = 0
self._count = 0
# global
self._history_avg = 0
self._history_count = 0
self._avg = None
def update(self, val, n=1):
self._val = val
self._sum += val * n
self._count += n
self._avg = None
@property
def val(self):
return self._val
@property
def count(self):
return self._count + self._history_count
@property
def avg(self):
if self._avg is None:
# compute avg
r = self._history_count / max(1, self._history_count + self._count)
_avg = self._sum / max(1, self._count)
self._avg = r * self._history_avg + (1.0 - r) * _avg
return self._avg
def sync(self):
buf = torch.tensor([self._sum, self._count],
dtype=torch.float32).cuda()
buf = reduce_tensor(buf, 1)
_sum, _count = buf.tolist()
_avg = _sum / max(1, _count)
r = self._history_count / max(1, self._history_count + _count)
self._history_avg = r * self._history_avg + (1.0 - r) * _avg
self._history_count += _count
self._sum = 0
self._count = 0
self._avg = None