-
Notifications
You must be signed in to change notification settings - Fork 46
/
main.py
178 lines (153 loc) · 5.02 KB
/
main.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
import os
import time
import importlib
import json
from collections import OrderedDict
import logging
import argparse
import numpy as np
import random
import time
from eval import plot_accuracy_epoch, plot_loss_epoch, make_heat_map
from tqdm.notebook import tqdm
import torch
import torch.nn as nn
import torch.optim
import torch.utils.data
import torch.backends.cudnn
import torchvision.utils
import torch.nn.functional as F
from REPVGG_main import REPVGG
from block import fcbn, block
from dataloader import get_loader
def parse_args():
parser = argparse.ArgumentParser()
# model config
parser.add_argument("--block_type", type=str, default="basic", required=True)
parser.add_argument("--depth", type=int, default=3, required=True)
parser.add_argument("--option", type=str, default="A")
# optim config
parser.add_argument("--epochs", type=int, default=160)
parser.add_argument("--batch_size", type=int, default=128)
parser.add_argument("--base_lr", type=float, default=0.1)
parser.add_argument("--weight_decay", type=float, default=1e-4)
parser.add_argument("--momentum", type=float, default=0.9)
parser.add_argument("--milestones", type=str, default="[80, 120]")
parser.add_argument("--lr_decay", type=float, default=0.1)
# run_config
parser.add_argument("--device", type=str, default="cpu")
parser.add_argument("--num_workers", type=int, default=2)
args = parser.parse_args()
model_config = OrderedDict(
[
("multiplier", args.multiplier),
("depth", args.depth),
("blocks", args.blocks),
("in_channels", args.in_channels),
("reparametrize", args.reparametrize),
]
)
optim_config = OrderedDict(
[
("epochs", args.epochs),
("batch_size", args.batch_size),
("base_lr", args.base_lr),
("weight_decay", args.weight_decay),
("momentum", args.momentum),
("milestones", json.loads(args.milestones)),
("lr_decay", args.lr_decay),
]
)
data_config = OrderedDict(
[
("dataset", "CIFAR10"),
]
)
run_config = OrderedDict(
[
("device", args.device),
("num_workers", args.num_workers),
]
)
config = OrderedDict(
[
("model_config", model_config),
("optim_config", optim_config),
("data_config", data_config),
("run_config", run_config),
]
)
return config
config = parse_args()
model = REPVGG(
blocks=config["model_config"]["block"],
multipl=config["model_config"]["multiplier"],
in_channels=config["model_config"]["in_channels"],
num_classes=config["model_config"]["numclasses"],
)
optimizer = torch.optim.Adam(
params=model.parameters(),
lr=config["optim_config"]["base_lr"],
weight_decay=config["optim_config"]["weight_decay"],
)
scheduler = torch.optim.lr_scheduler.MultiStepLR(
optimizer,
milestones=config["optim_config"]["milestones"],
gamma=config["optim_config"]["lr_decay"],
)
criterion = nn.CrossEntropyLoss()
def train(
model, epochs, trainloader, testloader, device, criterion, optimizer, scheduler
):
for epoch in range(epochs):
for i, (images, labels) in enumerate(train_loader):
start_time = time.time()
images = images.to(device)
labels = labels.to(device)
outputs = model(images).to(device)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i + 1) % 250 == 0:
elapsed_time = time.time() - start_time
total_time += elapsed_time
print(
"Epoch {}, Step {} Loss: {:.4f} time : {:.4f}min".format(
epoch + 1, i + 1, loss.item(), total_time
)
)
return train_losses
device = config["run_config"]["device"]
model.to(device)
criterion = nn.CrossEntropyLoss()
train_loader, test_loader = get_loader(
config["optim_config"]["batch_size"], config["run_config"]["num_workers"]
)
if config["model_config"]["reparametrize"] == False:
train_loss = train(
model,
config["optim_config"]["epochs"],
train_loader,
test_loader,
device,
criterion,
optimizer,
scheduler,
)
plot_loss_epoch(train_loss)
if config["model_config"]["reparametriz"] == True:
train_loss = train(
model,
config["optim_config"]["epochs"],
train_loader,
test_loader,
device,
criterion,
optimizer,
scheduler,
)
plot_loss_epoch(train_loss)
model.reparametrize()
_, test_checker = get_loader(10000, config["run_config"]["num_workers"])
make_heat_map(model, test_checker, device)