-
Notifications
You must be signed in to change notification settings - Fork 75
/
train.py
250 lines (227 loc) · 6.64 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
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
import argparse
import time
import torch
import torch.nn.functional as F
import utils
import tabulate
import models
from data import get_data
from qtorch.quant import *
from qtorch.optim import OptimLP
from torch.optim import SGD
from qtorch import BlockFloatingPoint, FixedPoint, FloatingPoint
num_types = ["weight", "activate", "grad", "error", "momentum"]
parser = argparse.ArgumentParser(description="SGD/SWA training")
parser.add_argument(
"--dataset", type=str, default="CIFAR10", help="dataset name: CIFAR10 or IMAGENET12"
)
parser.add_argument(
"--data_path",
type=str,
default="./data",
required=True,
metavar="PATH",
help='path to datasets location (default: "./data")',
)
parser.add_argument(
"--batch_size",
type=int,
default=128,
metavar="N",
help="input batch size (default: 128)",
)
parser.add_argument(
"--model",
type=str,
default=None,
required=True,
metavar="MODEL",
help="model name (default: None)",
)
parser.add_argument(
"--epochs",
type=int,
default=200,
metavar="N",
help="number of epochs to train (default: 200)",
)
parser.add_argument(
"--eval_freq",
type=int,
default=5,
metavar="N",
help="evaluation frequency (default: 5)",
)
parser.add_argument(
"--lr_init",
type=float,
default=0.01,
metavar="LR",
help="initial learning rate (default: 0.01)",
)
parser.add_argument(
"--wd", type=float, default=1e-4, help="weight decay (default: 1e-4)"
)
parser.add_argument(
"--seed", type=int, default=200, metavar="N", help="random seed (default: 1)"
)
for num in num_types:
parser.add_argument(
"--wl-{}".format(num),
type=int,
default=-1,
metavar="N",
help="word length in bits for {}; -1 if full precision.".format(num),
)
parser.add_argument(
"--fl-{}".format(num),
type=int,
default=-1,
metavar="N",
help="number of fractional bits for {}; -1 if full precision.".format(num),
)
parser.add_argument(
"--{}-man".format(num),
type=int,
default=-1,
metavar="N",
help="number of bits to use for mantissa of {}; -1 if full precision.".format(
num
),
)
parser.add_argument(
"--{}-exp".format(num),
type=int,
default=-1,
metavar="N",
help="number of bits to use for exponent of {}; -1 if full precision.".format(
num
),
)
parser.add_argument(
"--{}-type".format(num),
type=str,
default="full",
metavar="S",
choices=["fixed", "block", "float", "full"],
help="quantization type for {}; fixed or block.".format(num),
)
parser.add_argument(
"--{}-rounding".format(num),
type=str,
default="stochastic",
metavar="S",
choices=["stochastic", "nearest"],
help="rounding method for {}, stochastic or nearest".format(num),
)
args = parser.parse_args()
args.cuda = torch.cuda.is_available()
utils.set_seed(args.seed, args.cuda)
loaders = get_data(args.dataset, args.data_path, args.batch_size)
def make_number(number, wl=-1, fl=-1, exp=-1, man=-1):
if number == "fixed":
return FixedPoint(wl, fl)
elif number == "block":
return BlockFloatingPoint(wl)
elif number == "float":
return FloatingPoint(exp, man)
elif number == "full":
return FloatingPoint(8, 23)
else:
raise ValueError("invalid number type")
number_dict = {}
for num in num_types:
num_wl = getattr(args, "wl_{}".format(num))
num_fl = getattr(args, "fl_{}".format(num))
num_type = getattr(args, "{}_type".format(num))
num_rounding = getattr(args, "{}_rounding".format(num))
num_man = getattr(args, "{}_man".format(num))
num_exp = getattr(args, "{}_exp".format(num))
number_dict[num] = make_number(
num_type, wl=num_wl, fl=num_fl, exp=num_exp, man=num_man
)
print("{:10}: {}".format(num, number_dict[num]))
weight_quantizer = quantizer(
forward_number=number_dict["weight"], forward_rounding=args.weight_rounding
)
grad_quantizer = quantizer(
forward_number=number_dict["grad"], forward_rounding=args.grad_rounding
)
momentum_quantizer = quantizer(
forward_number=number_dict["momentum"], forward_rounding=args.momentum_rounding
)
acc_err_quant = lambda: Quantizer(
number_dict["activate"],
number_dict["error"],
args.activate_rounding,
args.error_rounding,
)
# Build model
print("Model: {}".format(args.model))
model_cfg = getattr(models, args.model)
model_cfg.kwargs.update({"quant": acc_err_quant})
if args.dataset == "CIFAR10":
num_classes = 10
elif args.dataset == "CIFAR100":
num_classes = 100
elif args.dataset == "IMAGENET12":
num_classes = 1000
model = model_cfg.base(*model_cfg.args, num_classes=num_classes, **model_cfg.kwargs)
model.cuda()
def schedule(epoch):
t = (epoch) / args.epochs
lr_ratio = 0.01
if t <= 0.5:
factor = 1.0
elif t <= 0.9:
factor = 1.0 - (1.0 - lr_ratio) * (t - 0.5) / 0.4
else:
factor = lr_ratio
return args.lr_init * factor
criterion = F.cross_entropy
optimizer = SGD(model.parameters(), lr=args.lr_init, momentum=0.9, weight_decay=args.wd)
optimizer = OptimLP(
optimizer,
weight_quant=weight_quantizer,
grad_quant=grad_quantizer,
momentum_quant=momentum_quantizer,
)
# Prepare logging
columns = ["ep", "lr", "tr_loss", "tr_acc", "tr_time", "te_loss", "te_acc", "te_time"]
for epoch in range(args.epochs):
time_ep = time.time()
lr = schedule(epoch)
utils.adjust_learning_rate(optimizer, lr)
train_res = utils.run_epoch(
loaders["train"], model, criterion, optimizer=optimizer, phase="train"
)
time_pass = time.time() - time_ep
train_res["time_pass"] = time_pass
if (
epoch == 0
or epoch % args.eval_freq == args.eval_freq - 1
or epoch == args.epochs - 1
):
time_ep = time.time()
test_res = utils.run_epoch(loaders["test"], model, criterion, phase="eval")
time_pass = time.time() - time_ep
test_res["time_pass"] = time_pass
else:
test_res = {"loss": None, "accuracy": None, "time_pass": None}
values = [
epoch + 1,
lr,
train_res["loss"],
train_res["accuracy"],
train_res["time_pass"],
test_res["loss"],
test_res["accuracy"],
test_res["time_pass"],
]
table = tabulate.tabulate([values], columns, tablefmt="simple", floatfmt="8.4f")
if epoch % 40 == 0:
table = table.split("\n")
table = "\n".join([table[1]] + table)
else:
table = table.split("\n")[2]
print(table)