-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
252 lines (210 loc) · 7.68 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
from collections import deque
import os
from collections import defaultdict, deque
import warnings
from xml.dom import NotSupportedErr
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch
import torch.distributed as dist
from continuum.datasets import CIFAR100, ImageFolderDataset, Food101
from continuum import ClassIncremental
from timm.data import create_transform
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from torchvision import transforms
try:
interpolation = torch.transforms.functional.InterpolationMode.BICUBIC
except:
interpolation = 3
class SmoothedValue(object):
def __init__(self, window_size=20, fmt=None):
if fmt is None:
fmt = "{median:.4f} ({global_avg:.4f})"
self.deque = deque(maxlen=window_size)
self.total = 0.0
self.count = 0
self.fmt = fmt
def update(self, value, n=1):
self.deque.append(value)
self.count += n
self.total += value * n
def synchronize_between_processes(self):
t = torch.tensor([self.count, self.total],
dtype=torch.float64, device='cuda')
dist.barrier()
dist.all_reduce(t)
t = t.tolist()
self.count = int(t[0])
self.total = t[1]
@property
def median(self):
d = torch.tensor(list(self.deque))
return d.median().item()
@property
def avg(self):
d = torch.tensor(list(self.deque), dtype=torch.float32)
return d.mean().item()
@property
def global_avg(self):
return self.total / self.count
@property
def max(self):
return max(self.deque)
@property
def value(self):
return self.deque[-1]
def __str__(self):
return self.fmt.format(
median=self.median,
avg=self.avg,
global_avg=self.global_avg,
max=self.max,
value=self.value)
class MetricLogger(object):
def __init__(self, delimiter="\t"):
self.meters = defaultdict(SmoothedValue)
self.delimiter = delimiter
def update(self, **kwargs):
for k, v in kwargs.items():
if v is None:
continue
if isinstance(v, torch.Tensor):
v = v.item()
assert isinstance(v, (float, int))
self.meters[k].update(v)
def update_dict(self, d):
for k, v in d.items():
if isinstance(v, torch.Tensor):
v = v.item()
assert isinstance(v, (float, int))
self.meters[k].update(v)
def __getattr__(self, attr):
if attr in self.meters:
return self.meters[attr]
if attr in self.__dict__:
return self.__dict__[attr]
raise AttributeError("'{}' object has no attribute '{}'".format(
type(self).__name__, attr))
def __str__(self):
loss_str = []
for name, meter in self.meters.items():
loss_str.append(
"{}: {}".format(name, str(meter))
)
return self.delimiter.join(loss_str)
def synchronize_between_processes(self):
for meter in self.meters.values():
meter.synchronize_between_processes()
def add_meter(self, name, meter):
self.meters[name] = meter
class SoftTarget(nn.Module):
def __init__(self, T=2):
super(SoftTarget, self).__init__()
self.T = T
def forward(self, out_s, out_t):
loss = F.kl_div(F.log_softmax(out_s/self.T, dim=1),
F.softmax(out_t/self.T, dim=1),
reduction='batchmean') * self.T * self.T
return loss
def init_distributed_mode(args):
if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
args.rank = int(os.environ["RANK"])
args.world_size = int(os.environ['WORLD_SIZE'])
args.gpu = int(os.environ['LOCAL_RANK'])
else:
print('Not using distributed mode')
args.distributed = False
raise NotSupportedErr("not supported yet!")
return
args.distributed = True
torch.cuda.set_device(args.gpu)
args.dist_backend = 'nccl'
print('| distributed init (rank {}): {}'.format(
args.rank, args.dist_url), flush=True)
torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
world_size=args.world_size, rank=args.rank)
torch.distributed.barrier()
setup_for_distributed(args.rank == 0)
def is_main_process():
return dist.get_rank() == 0
def setup_for_distributed(is_master):
import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
force = kwargs.pop('force', False)
if is_master or force:
builtin_print(*args, **kwargs)
__builtin__.print = print
class ImageNet1000(ImageFolderDataset):
def __init__(
self,
data_path: str,
train: bool = True,
download: bool = False,
):
super().__init__(data_path=data_path, train=train, download=download)
def get_data(self):
if self.train:
self.data_path = os.path.join(self.data_path, "train")
else:
self.data_path = os.path.join(self.data_path, "val")
return super().get_data()
def build_dataset(is_train, apply_da, args):
transform = build_transform(is_train, apply_da, args)
if args.data_set.lower() == 'cifar':
dataset = CIFAR100(args.data_path, train=is_train, download=True)
elif args.data_set.lower() == 'imagenet1000':
dataset = ImageNet1000(args.data_path, train=is_train)
elif args.data_set.lower() == 'food101':
dataset = Food101(args.data_path, train=is_train, download=True)
else:
raise ValueError(f'Unknown dataset {args.data_set}.')
scenario = ClassIncremental(
dataset,
initial_increment=args.num_bases,
increment=args.increment,
transformations=transform.transforms,
class_order=args.class_order
)
nb_classes = scenario.nb_classes
return scenario, nb_classes
def build_transform(is_train, apply_da, args):
if args.aa == 'none':
args.aa = None
with warnings.catch_warnings():
resize_im = args.input_size > 32
if is_train and apply_da:
transform = create_transform(
input_size=args.input_size,
is_training=True,
color_jitter=args.color_jitter,
auto_augment=args.aa,
interpolation='bicubic',
re_prob=args.reprob,
re_mode=args.remode,
re_count=args.recount,
)
if not resize_im:
transform.transforms[0] = transforms.RandomCrop(
args.input_size, padding=4)
if args.input_size == 32 and args.data_set == 'CIFAR':
transform.transforms[-1] = transforms.Normalize(
(0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761))
return transform
t = []
if resize_im:
size = int((256 / 224) * args.input_size)
t.append(
transforms.Resize(size, interpolation=interpolation),
)
t.append(transforms.CenterCrop(args.input_size))
t.append(transforms.ToTensor())
print(args.input_size == 32 and args.data_set == 'CIFAR')
if args.input_size == 32 and args.data_set == 'CIFAR':
t.append(transforms.Normalize(
(0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761)))
else:
t.append(transforms.Normalize(
IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD))
return transforms.Compose(t)