forked from xrenaa/DisCo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
51 lines (42 loc) · 1.26 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
50
51
import torch
import torch.nn.functional as F
from torch import nn
import numpy as np
import random
from models.DisCo.latent_deformator import DeformatorType
DEFORMATOR_TYPE_DICT = {
'fc': DeformatorType.FC,
'linear': DeformatorType.LINEAR,
'id': DeformatorType.ID,
'ortho': DeformatorType.ORTHO,
'proj': DeformatorType.PROJECTIVE,
'random': DeformatorType.RANDOM,
'deeper': DeformatorType.DEEPER_FC
}
class MeanTracker(object):
def __init__(self, name):
self.values = []
self.name = name
def add(self, val):
self.values.append(float(val))
def mean(self):
return np.mean(self.values)
def flush(self):
mean = self.mean()
self.values = []
return self.name, mean
class DataParallelPassthrough(nn.DataParallel):
def __getattr__(self, name):
try:
return super(DataParallelPassthrough, self).__getattr__(name)
except AttributeError:
return getattr(self.module, name)
def random_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
def entropy(p):
p = F.softmax(p)
return -torch.mean(torch.sum(p * torch.log(p+1e-5), 1))