|
| 1 | +import torch |
| 2 | + |
| 3 | + |
| 4 | +class TensorRunningMean(object): |
| 5 | + """ |
| 6 | + Tracks a running mean without graph references. |
| 7 | + Round robbin for the mean |
| 8 | +
|
| 9 | + Examples: |
| 10 | + >>> accum = TensorRunningMean(5) |
| 11 | + >>> accum.last(), accum.mean() |
| 12 | + (None, None) |
| 13 | + >>> accum.append(torch.tensor(1.5)) |
| 14 | + >>> accum.last(), accum.mean() |
| 15 | + (tensor(1.5000), tensor(1.5000)) |
| 16 | + >>> accum.append(torch.tensor(2.5)) |
| 17 | + >>> accum.last(), accum.mean() |
| 18 | + (tensor(2.5000), tensor(2.)) |
| 19 | + >>> accum.reset() |
| 20 | + >>> _= [accum.append(torch.tensor(i)) for i in range(13)] |
| 21 | + >>> accum.last(), accum.mean() |
| 22 | + (tensor(12.), tensor(10.)) |
| 23 | + """ |
| 24 | + def __init__(self, window_length: int): |
| 25 | + self.window_length = window_length |
| 26 | + self.memory = torch.Tensor(self.window_length) |
| 27 | + self.current_idx: int = 0 |
| 28 | + self.last_idx: int = None |
| 29 | + self.rotated: bool = False |
| 30 | + |
| 31 | + def reset(self) -> None: |
| 32 | + self = TensorRunningMean(self.window_length) |
| 33 | + |
| 34 | + def last(self): |
| 35 | + if self.last_idx is not None: |
| 36 | + return self.memory[self.last_idx] |
| 37 | + |
| 38 | + def append(self, x): |
| 39 | + # map proper type for memory if they don't match |
| 40 | + if self.memory.type() != x.type(): |
| 41 | + self.memory.type_as(x) |
| 42 | + |
| 43 | + # store without grads |
| 44 | + with torch.no_grad(): |
| 45 | + self.memory[self.current_idx] = x |
| 46 | + self.last_idx = self.current_idx |
| 47 | + |
| 48 | + # increase index |
| 49 | + self.current_idx += 1 |
| 50 | + |
| 51 | + # reset index when hit limit of tensor |
| 52 | + self.current_idx = self.current_idx % self.window_length |
| 53 | + if self.current_idx == 0: |
| 54 | + self.rotated = True |
| 55 | + |
| 56 | + def mean(self): |
| 57 | + if self.last_idx is not None: |
| 58 | + return self.memory.mean() if self.rotated else self.memory[:self.current_idx].mean() |
0 commit comments