-
Notifications
You must be signed in to change notification settings - Fork 25
/
train.py
177 lines (154 loc) · 6.98 KB
/
train.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
# the code mostly from https://github.com/sdoria/SimpleSelfAttention
#based on @grankin FastAI forum script
#updated by lessw2020 to use Mish XResNet
# adapted from https://github.com/fastai/fastai/blob/master/examples/train_imagenette.py
# changed per gpu bs for bs_rat
from fastai.script import *
from fastai.vision import *
from fastai.callbacks import *
from fastai.distributed import *
from fastprogress import fastprogress
from torchvision.models import *
#from fastai.vision.models.xresnet import *
#from fastai.vision.models.xresnet2 import *
#from fastai.vision.models.presnet import *
#from x2resnet import *
from mxresnet import *
from functools import partial
torch.backends.cudnn.benchmark = True
fastprogress.MAX_COLS = 80
def get_data(size, woof, bs, workers=None):
# if size<=128: path = URLs.IMAGEWOOF_160 if woof else URLs.IMAGENETTE_160
# elif size<=224: path = URLs.IMAGEWOOF_320 if woof else URLs.IMAGENETTE_320
# else :
if woof:
path = URLs.IMAGEWOOF # if woof
else:
path = URLs.IMAGENETTE
path = untar_data(path)
n_gpus = num_distrib() or 1
if workers is None: workers = min(8, num_cpus()//n_gpus)
return (ImageList.from_folder(path).split_by_folder(valid='val')
.label_from_folder().transform(([flip_lr(p=0.5)], []), size=size)
.databunch(bs=bs, num_workers=workers)
.presize(size, scale=(0.35,1))
.normalize(imagenet_stats))
#from radam import *
#from novograd import *
#from rangervar import *
from ranger import *
#from ralamb import *
#from over9000 import *
#from lookahead import *
#from adams import *
#from rangernovo import *
#from rangerlars import *
def fit_with_annealing(learn:Learner, num_epoch:int, lr:float=defaults.lr, annealing_start:float=0.7)->None:
n = len(learn.data.train_dl)
anneal_start = int(n*num_epoch*annealing_start)
phase0 = TrainingPhase(anneal_start).schedule_hp('lr', lr)
phase1 = TrainingPhase(n*num_epoch - anneal_start).schedule_hp('lr', lr, anneal=annealing_cos)
phases = [phase0, phase1]
sched = GeneralScheduler(learn, phases)
learn.callbacks.append(sched)
learn.fit(num_epoch)
def train(
gpu:Param("GPU to run on", str)=None,
woof: Param("Use imagewoof (otherwise imagenette)", int)=0,
lr: Param("Learning rate", float)=1e-3,
size: Param("Size (px: 128,192,224)", int)=128,
alpha: Param("Alpha", float)=0.99,
mom: Param("Momentum", float)=0.9,
eps: Param("epsilon", float)=1e-6,
epochs: Param("Number of epochs", int)=5,
bs: Param("Batch size", int)=256,
mixup: Param("Mixup", float)=0.,
opt: Param("Optimizer (adam,rms,sgd)", str)='adam',
arch: Param("Architecture (xresnet34, xresnet50)", str)='xresnet50',
sa: Param("Self-attention", int)=0,
sym: Param("Symmetry for self-attention", int)=0,
dump: Param("Print model; don't train", int)=0,
lrfinder: Param("Run learning rate finder; don't train", int)=0,
log: Param("Log file name", str)='log',
sched_type: Param("LR schedule type", str)='one_cycle',
ann_start: Param("Mixup", float)=-1.0,
):
"Distributed training of Imagenette."
bs_one_gpu = bs
gpu = setup_distrib(gpu)
if gpu is None: bs *= torch.cuda.device_count()
if opt=='adam' : opt_func = partial(optim.Adam, betas=(mom,alpha), eps=eps)
elif opt=='radam' : opt_func = partial(RAdam, betas=(mom,alpha), eps=eps)
elif opt=='novograd' : opt_func = partial(Novograd, betas=(mom,alpha), eps=eps)
elif opt=='rms' : opt_func = partial(optim.RMSprop, alpha=alpha, eps=eps)
elif opt=='sgd' : opt_func = partial(optim.SGD, momentum=mom)
elif opt=='rangervar' : opt_func = partial(RangerVar, betas=(mom,alpha), eps=eps)
elif opt=='ranger' : opt_func = partial(Ranger, betas=(mom,alpha), eps=eps)
elif opt=='ralamb' : opt_func = partial(Ralamb, betas=(mom,alpha), eps=eps)
elif opt=='over9000' : opt_func = partial(Over9000, k=12, betas=(mom,alpha), eps=eps)
elif opt=='lookahead' : opt_func = partial(LookaheadAdam, betas=(mom,alpha), eps=eps)
elif opt=='Adams': opt_func=partial(Adams)
elif opt=='rangernovo': opt_func=partial(RangerNovo)
elif opt=='rangerlars':opt_func=partial(RangerLars)
data = get_data(size, woof, bs)
bs_rat = bs/bs_one_gpu #originally bs/256
if gpu is not None: bs_rat *= max(num_distrib(), 1)
if not gpu: print(f'lr: {lr}; eff_lr: {lr*bs_rat}; size: {size}; alpha: {alpha}; mom: {mom}; eps: {eps}')
lr *= bs_rat
m = globals()[arch]
log_cb = partial(CSVLogger,filename=log)
learn = (Learner(data, m(c_out=10, sa=sa,sym=sym), wd=1e-2, opt_func=opt_func,
metrics=[accuracy,top_k_accuracy],
bn_wd=False, true_wd=True,
loss_func = LabelSmoothingCrossEntropy(),
callback_fns=[log_cb])
)
print(learn.path)
n = len(learn.data.train_dl)
ann_start2= int(n*epochs*ann_start)
print(ann_start2," annealing start")
if dump: print(learn.model); exit()
if mixup: learn = learn.mixup(alpha=mixup)
learn = learn.to_fp16(dynamic=True)
if gpu is None: learn.to_parallel()
elif num_distrib()>1: learn.to_distributed(gpu) # Requires `-m fastai.launch`
if lrfinder:
# run learning rate finder
IN_NOTEBOOK = 1
learn.lr_find(wd=1e-2)
learn.recorder.plot()
else:
if sched_type == 'one_cycle':
learn.fit_one_cycle(epochs, lr, div_factor=10, pct_start=0.3)
elif sched_type == 'flat_and_anneal':
fit_with_annealing(learn, epochs, lr, ann_start)
return learn.recorder.metrics[-1][0]
@call_parse
def main(
run: Param("Number of run", int)=5,
gpu:Param("GPU to run on", str)=None,
woof: Param("Use imagewoof (otherwise imagenette)", int)=0,
lr: Param("Learning rate", float)=1e-3,
size: Param("Size (px: 128,192,224)", int)=128,
alpha: Param("Alpha", float)=0.99,
mom: Param("Momentum", float)=0.9,
eps: Param("epsilon", float)=1e-6,
epochs: Param("Number of epochs", int)=5,
bs: Param("Batch size", int)=256,
mixup: Param("Mixup", float)=0.,
opt: Param("Optimizer (adam,rms,sgd)", str)='adam',
arch: Param("Architecture (mxresnet34, mxresnet50)", str)='mxresnet50',
sa: Param("Self-attention", int)=0,
sym: Param("Symmetry for self-attention", int)=0,
dump: Param("Print model; don't train", int)=0,
lrfinder: Param("Run learning rate finder; don't train", int)=0,
log: Param("Log file name", str)='log',
sched_type: Param("LR schedule type", str)='one_cycle',
ann_start: Param("Mixup", float)=-1.0,
):
acc = np.array(
[train(gpu,woof,lr,size,alpha,mom,eps,epochs,bs,mixup,opt,arch,sa,sym,dump,lrfinder,log,sched_type,ann_start)
for i in range(run)])
print(acc)
print(np.mean(acc))
print(np.std(acc))