-
Notifications
You must be signed in to change notification settings - Fork 5
/
client.py
210 lines (166 loc) · 7.13 KB
/
client.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
import torch
import torch.optim as optim
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from federated_learning.schedulers import MinCapableStepLR
import os
import numpy
import copy
class Client:
def __init__(self, args, client_idx, train_data_loader, test_data_loader):
"""
:param args: experiment arguments
:type args: Arguments
:param client_idx: Client index
:type client_idx: int
:param train_data_loader: Training data loader
:type train_data_loader: torch.utils.data.DataLoader
:param test_data_loader: Test data loader
:type test_data_loader: torch.utils.data.DataLoader
"""
self.args = args
self.client_idx = client_idx
self.device = self.initialize_device()
self.set_net(self.load_default_model())
self.loss_function = self.args.get_loss_function()()
self.optimizer = optim.SGD(self.net.parameters(),
lr=self.args.get_learning_rate(),
momentum=self.args.get_momentum())
self.scheduler = MinCapableStepLR(self.args.get_logger(), self.optimizer,
self.args.get_scheduler_step_size(),
self.args.get_scheduler_gamma(),
self.args.get_min_lr())
self.train_data_loader = train_data_loader
self.test_data_loader = test_data_loader
def initialize_device(self):
"""
Creates appropriate torch device for client operation.
"""
if torch.cuda.is_available() and self.args.get_cuda():
return torch.device("cuda:0")
else:
return torch.device("cpu")
def set_net(self, net):
"""
Set the client's NN.
:param net: torch.nn
"""
self.net = net
self.net.to(self.device)
def load_default_model(self):
"""
Load a model from default model file.
This is used to ensure consistent default model behavior.
"""
model_class = self.args.get_net()
default_model_path = os.path.join(self.args.get_default_model_folder_path(), model_class.__name__ + ".model")
return self.load_model_from_file(default_model_path)
def load_model_from_file(self, model_file_path):
"""
Load a model from a file.
:param model_file_path: string
"""
model_class = self.args.get_net()
model = model_class()
if os.path.exists(model_file_path):
try:
model.load_state_dict(torch.load(model_file_path))
except:
self.args.get_logger().warning("Couldn't load model. Attempting to map CUDA tensors to CPU to solve error.")
model.load_state_dict(torch.load(model_file_path, map_location=torch.device('cpu')))
else:
self.args.get_logger().warning("Could not find model: {}".format(model_file_path))
return model
def get_client_index(self):
"""
Returns the client index.
"""
return self.client_idx
def get_nn_parameters(self):
"""
Return the NN's parameters.
"""
return self.net.state_dict()
def update_nn_parameters(self, new_params):
"""
Update the NN's parameters.
:param new_params: New weights for the neural network
:type new_params: dict
"""
self.net.load_state_dict(copy.deepcopy(new_params), strict=True)
def train(self, epoch):
"""
:param epoch: Current epoch #
:type epoch: int
"""
self.net.train()
# save model
if self.args.should_save_model(epoch):
self.save_model(epoch, self.args.get_epoch_save_start_suffix())
running_loss = 0.0
for i, (inputs, labels) in enumerate(self.train_data_loader, 0):
inputs, labels = inputs.to(self.device), labels.to(self.device)
# zero the parameter gradients
self.optimizer.zero_grad()
# forward + backward + optimize
outputs = self.net(inputs)
loss = self.loss_function(outputs, labels)
loss.backward()
self.optimizer.step()
# print statistics
running_loss += loss.item()
if i % self.args.get_log_interval() == 0:
self.args.get_logger().info('[%d, %5d] loss: %.3f' % (epoch, i, running_loss / self.args.get_log_interval()))
running_loss = 0.0
self.scheduler.step()
# save model
if self.args.should_save_model(epoch):
self.save_model(epoch, self.args.get_epoch_save_end_suffix())
return running_loss
def save_model(self, epoch, suffix):
"""
Saves the model if necessary.
"""
self.args.get_logger().debug("Saving model to flat file storage. Save #{}", epoch)
if not os.path.exists(self.args.get_save_model_folder_path()):
os.mkdir(self.args.get_save_model_folder_path())
full_save_path = os.path.join(self.args.get_save_model_folder_path(), "model_" + str(self.client_idx) + "_" + str(epoch) + "_" + suffix + ".model")
torch.save(self.get_nn_parameters(), full_save_path)
def calculate_class_precision(self, confusion_mat):
"""
Calculates the precision for each class from a confusion matrix.
"""
return numpy.diagonal(confusion_mat) / numpy.sum(confusion_mat, axis=0)
def calculate_class_recall(self, confusion_mat):
"""
Calculates the recall for each class from a confusion matrix.
"""
return numpy.diagonal(confusion_mat) / numpy.sum(confusion_mat, axis=1)
def test(self):
self.net.eval()
correct = 0
total = 0
targets_ = []
pred_ = []
loss = 0.0
with torch.no_grad():
for (images, labels) in self.test_data_loader:
images, labels = images.to(self.device), labels.to(self.device)
outputs = self.net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
targets_.extend(labels.cpu().view_as(predicted).numpy())
pred_.extend(predicted.cpu().numpy())
loss += self.loss_function(outputs, labels).item()
accuracy = 100 * correct / total
confusion_mat = confusion_matrix(targets_, pred_)
class_precision = self.calculate_class_precision(confusion_mat)
class_recall = self.calculate_class_recall(confusion_mat)
self.args.get_logger().debug('Test set: Accuracy: {}/{} ({:.0f}%)'.format(correct, total, accuracy))
self.args.get_logger().debug('Test set: Loss: {}'.format(loss))
self.args.get_logger().debug("Classification Report:\n" + classification_report(targets_, pred_))
self.args.get_logger().debug("Confusion Matrix:\n" + str(confusion_mat))
self.args.get_logger().debug("Class precision: {}".format(str(class_precision)))
self.args.get_logger().debug("Class recall: {}".format(str(class_recall)))
return accuracy, loss, class_precision, class_recall