-
Notifications
You must be signed in to change notification settings - Fork 9
/
training.py
209 lines (178 loc) · 6.99 KB
/
training.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
import json
from datetime import datetime
import argparse
import torch
from tensorboardX import SummaryWriter
from helper import Helper
from models.simple import Net, NetTF
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm as tqdm
import yaml
import logging
logger = logging.getLogger("logger")
writer = SummaryWriter()
layout = {'accuracy_per_class': {
'accuracy_per_class': ['Multiline', ['accuracy_per_class/accuracy_var',
'accuracy_per_class/accuracy_min',
'accuracy_per_class/accuracy_max']]}}
writer.add_custom_scalars(layout)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def plot(x, y, name):
writer.add_scalar(tag=name, scalar_value=y, global_step=x)
def create_table(params: dict):
header = f"| {' | '.join([x[:10] for x in params.keys()])} |"
line = f"|{'|:'.join([3*'-' for x in range(len(params.keys()))])}|"
values = f"| {' | '.join([str(x) for x in params.values()])} |"
return '\n'.join([header, line, values])
def compute_norm(model, norm_type=2):
total_norm = 0
for p in model.parameters():
param_norm = p.grad.data.norm(norm_type)
total_norm += param_norm.item() ** norm_type
total_norm = total_norm ** (1. / norm_type)
return total_norm
def test(net, epoch, name, testloader, vis=True):
net.eval()
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
inputs, labels = data
inputs = inputs.to(device)
labels = labels.to(device)
outputs = net(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
logger.info(f'Name: {name}. Epoch {epoch}. acc: {100 * correct / total}')
if vis:
plot(epoch, 100 * correct / total, name)
return 100 * correct / total
def train_dp(trainloader, model, optimizer, epoch):
"""
Differentially Private version of the training procedure
:param trainloader:
:param model:
:param optimizer:
:param epoch:
:return:
"""
model.train()
running_loss = 0.0
for i, data in tqdm(enumerate(trainloader, 0), leave=True):
inputs, labels = data
inputs = inputs.to(device)
labels = labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
running_loss += torch.mean(loss).item()
losses = torch.mean(loss.reshape(num_microbatches, -1), dim=1)
saved_var = dict()
for tensor_name, tensor in model.named_parameters():
saved_var[tensor_name] = torch.zeros_like(tensor)
for j in losses:
j.backward(retain_graph=True)
torch.nn.utils.clip_grad_norm_(model.parameters(), S)
for tensor_name, tensor in model.named_parameters():
new_grad = tensor.grad
saved_var[tensor_name].add_(new_grad)
model.zero_grad()
for tensor_name, tensor in model.named_parameters():
if device.type =='cuda':
noise = torch.cuda.FloatTensor(tensor.grad.shape).normal_(0, sigma)
else:
noise = torch.FloatTensor(tensor.grad.shape).normal_(0, sigma)
saved_var[tensor_name].add_(noise)
tensor.grad = saved_var[tensor_name] / num_microbatches
optimizer.step()
if i > 0 and i % 20 == 0:
# logger.info('[%d, %5d] loss: %.3f' %
# (epoch + 1, i + 1, running_loss / 2000))
plot(epoch * len(trainloader) + i, running_loss, 'Train Loss')
running_loss = 0.0
def clip_grad(parameters, max_norm, norm_type=2):
parameters = list(filter(lambda p: p.grad is not None, parameters))
total_norm = 0
for p in parameters:
param_norm = p.grad.data.norm(norm_type)
total_norm += param_norm.item() ** norm_type
def train(trainloader, model, optimizer, epoch):
"""
Normal training
"""
model.train()
running_loss = 0.0
for i, data in tqdm(enumerate(trainloader, 0), leave=True):
# get the inputs
inputs, labels = data
inputs = inputs.to(device)
labels = labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
if i > 0 and i % 20 == 0:
# logger.info('[%d, %5d] loss: %.3f' %
# (epoch + 1, i + 1, running_loss / 2000))
plot(epoch * len(trainloader) + i, running_loss, 'Train Loss')
running_loss = 0.0
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='PPDL')
parser.add_argument('--params', dest='params', default='utils/params.yaml')
args = parser.parse_args()
with open(args.params) as f:
params = yaml.load(f)
helper = Helper(current_time=datetime.now().strftime('%b.%d_%H.%M.%S'), params=params, name='utk')
batch_size = int(helper.params['batch_size'])
num_microbatches = int(helper.params['num_microbatches'])
lr = float(helper.params['lr'])
momentum = float(helper.params['momentum'])
decay = float(helper.params['decay'])
epochs = int(helper.params['epochs'])
S = float(helper.params['S'])
z = float(helper.params['z'])
sigma = z * S
dp = helper.params['dp']
logger.info(f'DP: {dp}')
logger.info(batch_size)
logger.info(lr)
logger.info(momentum)
helper.load_data()
helper.create_loaders()
if helper.params['useTF']:
net = NetTF()
else:
net = Net()
print(count_parameters(net))
net.to(device)
if dp:
criterion = nn.CrossEntropyLoss(reduction='none')
else:
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=lr, momentum=momentum, weight_decay=decay)
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer,
milestones=[0.5 * epochs,
0.75 * epochs],
gamma=0.1)
table = create_table(helper.params)
writer.add_text('Model Params', table)
name = "accuracy"
for epoch in range(1, epochs): # loop over the dataset multiple times
if dp:
train_dp(helper.train_loader, net, optimizer, epoch)
else:
train(helper.train_loader, net, optimizer, epoch)
if helper.params.get('scheduler', False):
scheduler.step()
acc = test(net, epoch, name, helper.test_loader, vis=True)
acc_list = list()
helper.save_model(net, epoch, acc)