39 lines
1.1 KiB
Python
39 lines
1.1 KiB
Python
from re import L
|
|
import torch
|
|
from torchmetrics import Metric
|
|
from collections import OrderedDict
|
|
|
|
class MeanDictMetric(Metric):
|
|
def __init__(self, names, dist_sync_on_step=False):
|
|
super().__init__(dist_sync_on_step=dist_sync_on_step)
|
|
|
|
self.names = names
|
|
self.add_state("num_iters", default=torch.tensor(0), dist_reduce_fx="sum")
|
|
|
|
for iname in self.names:
|
|
self.add_state(iname, default=torch.tensor(0), dist_reduce_fx="sum")
|
|
|
|
def update(self, loss_dict):
|
|
for (key, value) in loss_dict.items():
|
|
if key not in self.names: continue
|
|
|
|
current_val = getattr(self, key)
|
|
setattr(self, key, current_val + value)
|
|
|
|
self.num_iters += 1
|
|
|
|
def compute(self):
|
|
for iname in self.names:
|
|
current_val = getattr(self, iname)
|
|
setattr(self, iname, current_val.float() / self.num_iters)
|
|
|
|
|
|
def compute_to_dict(self):
|
|
self.compute()
|
|
|
|
loss_dict = OrderedDict()
|
|
for iname in self.names:
|
|
loss_dict[iname] = getattr(self, iname)
|
|
|
|
return loss_dict
|