-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresnext_baseline.py
140 lines (93 loc) · 3.82 KB
/
resnext_baseline.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
import numpy as np
import torch
from torch import nn
from torchvision.datasets import CIFAR10
from torchvision import transforms
from models.resnext import ResNeXt29_4x64d
from tqdm import trange
'''
baseline: num_workers=2, no checkpoint, FP32
'''
num_epochs = 10
batch_size = 128
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
train_data = CIFAR10(root = "./data/", transform = transform_train, train = True, download = True)
train_data_loader = torch.utils.data.DataLoader(dataset = train_data, batch_size = batch_size, shuffle = True, num_workers=2)
testset = CIFAR10(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=2)
def init_weights(m):
if type(m) == nn.Linear or type(m) == nn.Conv2d:
nn.init.kaiming_uniform_(m.weight)
model = ResNeXt29_4x64d()
# model.fc = nn.Linear(in_features=model.fc.in_features, out_features=10)
model.apply(init_weights)
model = model.cuda()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
loss = nn.CrossEntropyLoss()
training_loss = []
training_acc = []
testing_acc = []
def test(model):
model.eval()
correct = 0
total = 0
with torch.no_grad():
for batch_idx, (inputs, targets) in enumerate(testloader):
inputs, targets = inputs.cuda(), targets.cuda()
outputs = model(inputs)
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
return 100.*correct / total
with torch.autograd.profiler.emit_nvtx():
torch.cuda.nvtx.range_push("training resnext baseline")
for i in trange(num_epochs):
torch.cuda.nvtx.range_push(f"epoch {i}")
model.train()
running_loss = 0
correct = 0
for j, (x, y) in enumerate(train_data_loader):
if j > 0:
torch.cuda.nvtx.range_pop() #data load
torch.cuda.nvtx.range_push(f"epoch {i} - step {j}")
torch.cuda.nvtx.range_push("data copy")
x = x.cuda()
y = y.cuda()
torch.cuda.nvtx.range_pop() #data copy
torch.cuda.nvtx.range_push("zero grad")
optimizer.zero_grad()
torch.cuda.nvtx.range_pop() #zero grad
torch.cuda.nvtx.range_push("forward")
y_hat = model(x)
torch.cuda.nvtx.range_pop() #forward
l = loss(y_hat, y)
l.backward()
torch.cuda.nvtx.range_push("optimizer")
optimizer.step()
torch.cuda.nvtx.range_pop() #optimizer
running_loss += l.item() * x.size(0)
_, predicted = y_hat.max(1)
correct += predicted.eq(y).sum().item()
torch.cuda.nvtx.range_pop() #step
if j < len(train_data_loader)-1:
torch.cuda.nvtx.range_push("data load")
training_loss.append(running_loss / 50000)
training_acc.append(100*correct / 50000)
torch.cuda.nvtx.range_push("validation")
testing_acc.append(test(model))
torch.cuda.nvtx.range_pop() #validation
# if i % 50 == 49:
# torch.save(model.state_dict(), f"model_history/resnest_baseline_epoch{i+1}.pt")
torch.cuda.nvtx.range_pop() # epoch
torch.cuda.nvtx.range_pop()
torch.save(model.state_dict(), "model_history/resnext_baseline.pt")
np.savez("model_history/resnext_baseline.npz", loss=training_loss, acc=training_acc, test_acc=testing_acc)