-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_low_rank.py
236 lines (217 loc) · 8.37 KB
/
main_low_rank.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
import os
import sys
sys.path.append(os.environ['EFCP_ROOT'])
from datetime import datetime
import argparse
import time
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from lib.data.datasets import *
from optimizers.lowrank.low_rank_optim import LowRankAggregateMFAC, LowRankMFAC, RankOneAggregateMFAC
N_GRADS = 1024
N_PERGRAD = 128
EVAL_BATCHSIZE = N_PERGRAD
N_WORKERS = 6
# Test model `model` on dataset `data` using batchsize `batch_size`
@torch.no_grad()
def test(model, data, batch_size=EVAL_BATCHSIZE):
preds = []
ys = []
for batch in DataLoader(data, shuffle=True, batch_size=batch_size, num_workers=N_WORKERS, pin_memory=True):
x, y = batch
x = x.to(model.device)
y = y.to(model.device)
preds.append(torch.argmax(model(x), 1))
ys.append(y)
return torch.mean((torch.cat(preds) == torch.cat(ys)).float()).item()
# Train model `model` on dataset `train_data` using optimizer `optim`, batchsize `batch_size` and
# decaying the learning rate by a factor of 0.1 before each epoch in `decay_at`. Further, test the
# current model after each epoch on dataset `test_data` and save a checkpoint as file `save`.
def train(
model, train_data, optim, nepochs,
test_data=None, decay_at=[], batch_size=N_PERGRAD, save='trained.pth'
):
print('Starting training')
start_time = datetime.now()
criterion = nn.functional.cross_entropy
for i in range(nepochs):
tick = time.time()
print(f'Epoch {i}')
if i in decay_at:
for param_group in optim.param_groups:
param_group['lr'] *= .1
runloss = 0.
step = 0
for x, y in DataLoader(
train_data, shuffle=True, batch_size=batch_size, num_workers=N_WORKERS, pin_memory=True
):
x = x.to(model.device)
y = y.to(model.device)
optim.zero_grad()
loss = criterion(model(x), y)
runloss += loss.item()
loss.backward()
optim.step()
step += 1
if test_data is not None:
model.eval()
print('test: %.4f' % test(model, test_data))
model.train()
print('loss: %.4f' % (runloss / step))
print('time: %.1f' % (time.time() - tick))
print('total elapsed:', datetime.now() - start_time)
print('datetime:', datetime.now())
print()
torch.save(model.state_dict(), save)
def train_profile(
model, train_data, optim, nepochs,
test_data=None, decay_at=[], batch_size=N_PERGRAD, save='trained.pth'
):
def trace_handler(p):
output = p.key_averages().table(sort_by="self_cuda_time_total", row_limit=30)
with open(f'profile/trace_{p.step_num}.txt', 'w') as f:
print(output, file=f)
with torch.profiler.profile(
activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA],
schedule=torch.profiler.schedule(
wait=1,
warmup=1,
active=2),
on_trace_ready=trace_handler
) as p:
criterion = nn.functional.cross_entropy
for i in range(nepochs):
tick = time.time()
print(i)
if i in decay_at:
for param_group in optim.param_groups:
param_group['lr'] *= .1
runloss = 0.
step = 0
for x, y in DataLoader(
train_data, shuffle=True, batch_size=batch_size, num_workers=N_WORKERS, pin_memory=True
):
x = x.to(model.device)
y = y.to(model.device)
optim.zero_grad()
loss = criterion(model(x), y)
runloss += loss.item()
loss.backward()
optim.step()
step += 1
if test_data is not None:
model.eval()
print('test: %.4f' % test(model, test_data))
model.train()
print('loss: %.4f' % (runloss / step))
print('time: %.1f' % (time.time() - tick))
torch.save(model.state_dict(), save)
p.step()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--model', choices=['resnet20', 'resnet32', 'mobilenet', 'wideresnet-22-2', 'wideresnet-40-2', 'wideresnet-22-4'], required=True,
help='Type of model to train.'
)
parser.add_argument(
'--dataset_path', type=str, required=True,
help='Path to dataset to use for training.'
)
parser.add_argument(
'--optim', choices=['sgd', 'adam', 'mfac_lowrank', 'mfac_rank1'], required=True,
help='Type of optimizer to use for training.'
)
parser.add_argument(
'--ngrads', type=int, default=N_GRADS,
help='Size of the gradient buffer to use for the M-FAC optimizer.'
)
parser.add_argument(
'--save', type=str, default='trained.pth',
help='Name of the file where the checkpoint of the most recent epoch is persisted.'
)
parser.add_argument(
'--batchsize', type=int, default=N_PERGRAD,
help='Batchsize to use for training.'
)
parser.add_argument(
'--momentum', type=float, default=0,
help='Momentum to use for the optimizer.'
)
parser.add_argument(
'--weightdecay', type=float, default=0,
help='Weight decay to use for the optimizer.'
)
parser.add_argument(
'--rank', type=int, default=1,
help='Rank of matrices into which gradients are decomposed.'
)
args1 = parser.parse_args()
if args1.model == 'resnet20':
from lib.models.resnet_cifar10 import *
model = resnet20()
train_data, test_data = get_datasets('cifar10', args1.dataset_path)
if args1.model == 'resnet32':
from lib.models.resnet_cifar10 import *
model = resnet32()
train_data, test_data = get_datasets('cifar10', args1.dataset_path)
if args1.model == 'mobilenet':
from lib.models.mobilenet import *
model = mobilenet()
train_data, test_data = get_datasets('imagenet', args1.dataset_path)
if args1.model == 'wideresnet-22-2':
from lib.models.wide_resnet import *
model = Wide_ResNet(22, 2, 0, 100)
train_data, test_data = get_datasets('cifar100', args1.dataset_path)
if args1.model == 'wideresnet-40-2':
from lib.models.wide_resnet import *
model = Wide_ResNet(40, 2, 0, 100)
train_data, test_data = get_datasets('cifar100', args1.dataset_path)
if args1.model == 'wideresnet-22-4':
from lib.models.wide_resnet import *
model = Wide_ResNet(22, 4, 0, 100)
train_data, test_data = get_datasets('cifar100', args1.dataset_path)
dev = torch.device('cuda:0')
torch.cuda.set_device(dev)
model = model.to(dev)
model.device = dev
model.dtype = torch.float32
model.train()
if torch.cuda.device_count() == 1:
gpus = [dev]
else:
gpus = [torch.device('cuda:' + str(i)) for i in range(1, torch.cuda.device_count())]
optim = {
'sgd': lambda: torch.optim.SGD(
model.parameters(),
lr=.1, momentum=.9, weight_decay=args1.weightdecay
),
'adam': lambda: torch.optim.Adam(model.parameters()),
'mfac_lowrank': lambda: LowRankAggregateMFAC(
model.parameters(), lr=.001, num_grads=args1.ngrads, damp=1e-5,
rank=args1.rank,
moddev=dev, optdev=dev,
momentum=args1.momentum, weight_decay=args1.weightdecay
),
'mfac_rank1': lambda: RankOneAggregateMFAC(
model.parameters(), lr=.001, num_grads=args1.ngrads, damp=1e-5,
moddev=dev, optdev=dev,
momentum=args1.momentum, weight_decay=args1.weightdecay
)
}[args1.optim]()
print('Training ...')
if args1.model in ['resnet20', 'resnet32']:
train(
model, train_data, optim, 164, decay_at=[82, 123],
batch_size=args1.batchsize, test_data=test_data, save=args1.save
)
if 'wideresnet' in args1.model:
train(
model, train_data, optim, 200, decay_at=[100, 150],
batch_size=args1.batchsize, test_data=test_data, save=args1.save
)
if args1.model in ['mobilenet']:
train(
model, train_data, optim, 100, decay_at=[50, 75],
batch_size=args1.batchsize, test_data=test_data, save=args1.save
)