2020-08-22 14:24:34 +00:00
|
|
|
import torch
|
|
|
|
|
|
|
|
# Utility class that stores detached, named losses in a rotating buffer for smooth metric outputting.
|
|
|
|
class LossAccumulator:
|
2020-08-23 23:22:34 +00:00
|
|
|
def __init__(self, buffer_sz=50):
|
2020-08-22 14:24:34 +00:00
|
|
|
self.buffer_sz = buffer_sz
|
|
|
|
self.buffers = {}
|
|
|
|
|
|
|
|
def add_loss(self, name, tensor):
|
|
|
|
if name not in self.buffers.keys():
|
|
|
|
self.buffers[name] = (0, torch.zeros(self.buffer_sz))
|
|
|
|
i, buf = self.buffers[name]
|
2020-10-03 04:53:42 +00:00
|
|
|
# Can take tensors or just plain python numbers.
|
|
|
|
if isinstance(tensor, torch.Tensor):
|
|
|
|
buf[i] = tensor.detach().cpu()
|
|
|
|
else:
|
|
|
|
buf[i] = tensor
|
2020-08-22 14:24:34 +00:00
|
|
|
self.buffers[name] = ((i+1) % self.buffer_sz, buf)
|
|
|
|
|
|
|
|
def as_dict(self):
|
|
|
|
result = {}
|
2020-08-23 23:22:34 +00:00
|
|
|
for k, v in self.buffers.items():
|
|
|
|
result["loss_" + k] = torch.mean(v[1])
|
2020-08-22 14:24:34 +00:00
|
|
|
return result
|