-
Notifications
You must be signed in to change notification settings - Fork 0
/
cnn_cifar10.py
243 lines (194 loc) · 8.54 KB
/
cnn_cifar10.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
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
from cnn_class import CNN
import torch.optim as optim
from utils import *
# test modification twice
########################################################################
# 1. Defining hardware non-idealty
SI = 1 # reminder for sign bit
IL = 5 # IL = torch.IntTensor([4]) Not including the signed bit
FL = 14 # FL = torch.IntTensor([12])
nonideal_train = 1 #fixed point train
nonideal_inference = 1 #fixed point inference
en_ntv_inference = 1
en_ntv_train = 0
<<<<<<< HEAD
p_flip = 0.000001
=======
p_flip = 0.00001
>>>>>>> origin/master
flip_len = IL + FL + SI # flip all bits
save_model = 0
load_model = 1
en_plot = 0
EPOCH = 0
########################################################################
# 2. Preparing CIFAR10 data
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4,
shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
########################################################################
# 3. defining non-idealty hooks
def fixed_point_hook(self, input, output):
apply_format_inplace('FXP', output.data, IL, FL)
def fixed_point_back_hook(self, grad_in, grad_out):
'''
print('Inside ' + self.__class__.__name__ + ' backward')
print('grad_input tuple size: ', grad_in.__len__())
#print('grad_output size:', grad_out[0].size())
#print(type(grad_in))
#print('grad_input size:', grad_in[0].size())
#print(grad_in[0])
if grad_in.__len__() > 1:
if not (grad_in[0] is None):
print('grad_input size:', grad_in[0].size())
print('grad_input size:', grad_in[1].size())
print('grad_input size:', grad_in[2].size())
'''
if grad_in.__len__() > 1:
#grad_in[0] = Variable(None)
apply_format_inplace('FXP', grad_in[1].data, IL, FL) # weight
apply_format_inplace('FXP', grad_in[2].data, IL, FL) # bias
if not (grad_in[0] is None):
apply_format_inplace('FXP', grad_in[0].data, IL, FL)
return grad_in
########################################################################
# 4. Create CNN instance and sgd optimizer
net = CNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)#, momentum=0.9)
juanji1 = list(net.conv1.parameters())
juanji2 = list(net.conv2.parameters())
linear1 = list(net.fc1.parameters())
linear2 = list(net.fc2.parameters())
linear3 = list(net.fc3.parameters())
# 4.1
if(nonideal_train):
# add backward
net.conv1.register_backward_hook(fixed_point_back_hook)
net.conv2.register_backward_hook(fixed_point_back_hook)
net.fc1.register_backward_hook(fixed_point_back_hook)
net.fc2.register_backward_hook(fixed_point_back_hook)
net.fc3.register_backward_hook(fixed_point_back_hook)
net.activation.register_backward_hook(fixed_point_back_hook)
# add forward
net.conv1.register_forward_hook(fixed_point_hook)
net.conv2.register_forward_hook(fixed_point_hook)
net.fc1.register_forward_hook(fixed_point_hook)
net.fc2.register_forward_hook(fixed_point_hook)
net.fc3.register_forward_hook(fixed_point_hook)
net.activation.register_forward_hook(fixed_point_hook)
# 4.2 weight init
# BLA BLA BLA
########################################################################
# 5. Train the network
for epoch in range(EPOCH): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs
inputs, labels = data
# wrap them in Variable
inputs, labels = Variable(inputs), Variable(labels)
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if nonideal_train:
apply_format_inplace('FXP', juanji1[0].data, IL, FL) # weight regulation
apply_format_inplace('FXP', juanji1[1].data, IL, FL) # bias regulation
apply_format_inplace('FXP', juanji2[0].data, IL, FL) # weight regulation
apply_format_inplace('FXP', juanji2[1].data, IL, FL) # bias regulation
apply_format_inplace('FXP', linear1[0].data, IL, FL) # weight regulation
apply_format_inplace('FXP', linear1[1].data, IL, FL) # bias regulation
apply_format_inplace('FXP', linear2[0].data, IL, FL) # weight regulation
apply_format_inplace('FXP', linear2[1].data, IL, FL) # bias regulation
apply_format_inplace('FXP', linear3[0].data, IL, FL) # weight regulation
apply_format_inplace('FXP', linear3[1].data, IL, FL) # bias regulation
if en_ntv_train:
apply_bitflip(juanji1[0].data, p_flip, IL, FL, flip_len)
apply_bitflip(juanji2[0].data, p_flip, IL, FL, flip_len)
apply_bitflip(linear1[0].data, p_flip, IL, FL, flip_len)
apply_bitflip(linear2[0].data, p_flip, IL, FL, flip_len)
apply_bitflip(linear3[0].data, p_flip, IL, FL, flip_len)
# print statistics
running_loss += loss.data[0]
if i % 2000 == 1999: # print every 2000 mini-batches
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
if save_model:
print('Saving model......')
torch.save(net, 'cnn_cifar10_model.pkl')
#>>>>>>>>Test neural network performance
if load_model:
print('Loading model......')
net = torch.load('cnn_cifar10_model.pkl')
########################################################################
# 6. Test the network
#
#
# 6.1 dump the handle from trained network layer
juanji1 = list(net.conv1.parameters())
juanji2 = list(net.conv2.parameters())
linear1 = list(net.fc1.parameters())
linear2 = list(net.fc2.parameters())
linear3 = list(net.fc3.parameters())
# 6.2
if nonideal_inference:
apply_format_inplace('FXP',juanji1[0].data,IL,FL) # weight regulation
apply_format_inplace('FXP', juanji1[1].data, IL, FL) # bias regulation
apply_format_inplace('FXP',juanji2[0].data,IL,FL) # weight regulation
apply_format_inplace('FXP', juanji2[1].data, IL, FL) # bias regulation
apply_format_inplace('FXP',linear1[0].data,IL,FL) # weight regulation
apply_format_inplace('FXP', linear1[1].data, IL, FL) # bias regulation
apply_format_inplace('FXP',linear2[0].data,IL,FL) # weight regulation
apply_format_inplace('FXP', linear2[1].data, IL, FL) # bias regulation
apply_format_inplace('FXP',linear3[0].data,IL,FL) # weight regulation
apply_format_inplace('FXP', linear3[1].data, IL, FL) # bias regulation
if en_ntv_inference:
print("injecting bit flip fault model...")
apply_bitflip(juanji1[0].data,p_flip,IL,FL,flip_len)
apply_bitflip(juanji2[0].data, p_flip, IL, FL, flip_len)
apply_bitflip(linear1[0].data, p_flip, IL, FL, flip_len)
apply_bitflip(linear2[0].data, p_flip, IL, FL, flip_len)
apply_bitflip(linear3[0].data, p_flip, IL, FL, flip_len)
if nonideal_inference and (not nonideal_train ):
net.conv1.register_forward_hook(fixed_point_hook)
net.conv2.register_forward_hook(fixed_point_hook)
net.fc1.register_forward_hook(fixed_point_hook)
net.fc2.register_forward_hook(fixed_point_hook)
net.fc3.register_forward_hook(fixed_point_hook)
net.activation.register_forward_hook(fixed_point_hook)
correct = 0
total = 0
for data in testloader:
images, labels = data
if nonideal_inference:
apply_format_inplace('FXP', images, IL, FL) # input regulation
outputs = net(Variable(images))
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum()
print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))