forked from arxyzan/data2vec-pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
49 lines (40 loc) · 1.33 KB
/
utils.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
import os
import torch
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=':f'):
self.name = name
self.fmt = fmt
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def __str__(self):
fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'
return fmtstr.format(**self.__dict__)
def maybe_save_checkpoint(model, optimizer, path, epoch_num, save_freq):
"""
Save a checkpoint specific to Data2Vec
Args:
model: a nn.Module instance
optimizer
path: path to save checkpoint to
epoch_num: current epoch number
save_freq: save frequency based on epoch number
"""
if not os.path.exists(path):
os.makedirs(path)
path = os.path.join(path, f'{epoch_num}.pt')
if epoch_num % save_freq == 0:
checkpoint = {'data2vec': model.state_dict(),
'encoder': model.encoder.encoder.state_dict(),
'optimizer': optimizer.state_dict()}
torch.save(checkpoint, path)
print(f'Saved checkpoint to `{path}`')