-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
402 lines (314 loc) · 14.6 KB
/
models.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import torch
import torch.nn.functional as F
from sklearn.metrics import accuracy_score, precision_score, recall_score, matthews_corrcoef, f1_score, roc_auc_score
import wandb
# metrics that require average parameter
metrics_with_avg = {'prec' : precision_score, 'recl' : recall_score, 'f1' : f1_score}
avg = 'macro'
# metrics that dont require average parameter
metrics_no_avg = {'accu' : accuracy_score, 'mcc' : matthews_corrcoef}
class CNN_femnist_client(torch.nn.Module):
"""
Client part model for FEMNIST task. The model structure follows the LEAF framework.
"""
def __init__(self, image_size: int = 28, num_class: int = 62) -> None:
"""
Arguments:
image_size (int): height / width of images. The images should be of rectangle shape.
num_class (int): number of classes in the dataset.
"""
super(CNN_femnist_client, self).__init__()
self.seq = torch.nn.Sequential(
# client part
torch.nn.Conv2d(in_channels = 1, out_channels = 32, kernel_size = 5, padding = 'same'),
torch.nn.ReLU(),
torch.nn.MaxPool2d(kernel_size = 2, stride = 2),
torch.nn.Conv2d(in_channels = 32, out_channels = 64, kernel_size = 5, padding = 'same'),
torch.nn.ReLU(),
torch.nn.MaxPool2d(kernel_size = 2, stride = 2),
# server part
# torch.nn.Flatten(),
# torch.nn.Linear(in_features = 64 * int(image_size / 4) * int(image_size / 4), out_features = 2048),
# torch.nn.ReLU(),
# torch.nn.Linear(in_features = 2048, out_features = num_class)
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Arguments:
x (torch.Tensor): input image tensor.
Returns:
x (torch.Tensor): features.
"""
x = self.seq(x)
return x
class CNN_femnist_server(torch.nn.Module):
"""
Server part model for FEMNIST task. The model structure follows the LEAF framework.
"""
def __init__(self, image_size: int = 28, num_class: int = 62) -> None:
"""
Arguments:
image_size (int): height / width of images. The images should be of rectangle shape.
num_class (int): number of classes in the dataset.
"""
super(CNN_femnist_server, self).__init__()
self.seq = torch.nn.Sequential(
# client part
# torch.nn.Conv2d(in_channels = 1, out_channels = 32, kernel_size = 5, padding = 'same'),
# torch.nn.ReLU(),
# torch.nn.MaxPool2d(kernel_size = 2, stride = 2),
# torch.nn.Conv2d(in_channels = 32, out_channels = 64, kernel_size = 5, padding = 'same'),
# torch.nn.ReLU(),
# torch.nn.MaxPool2d(kernel_size = 2, stride = 2),
# server part
torch.nn.Flatten(),
torch.nn.Linear(in_features = 64 * int(image_size / 4) * int(image_size / 4), out_features = 2048),
torch.nn.ReLU(),
torch.nn.Linear(in_features = 2048, out_features = num_class)
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Arguments:
x (torch.Tensor): features.
Returns:
x (torch.Tensor): logits (not softmaxed yet).
"""
x = self.seq(x)
return x
class CNN_celeba_client(torch.nn.Module):
"""
Client part model for CelebA task. The model structure follows the LEAF framework.
"""
def __init__(self, image_size: int = 84, num_class: int = 2) -> None:
"""
Arguments:
image_size (int): height / width of image. The image should be of rectangle shape.
num_class (int): number of classes in the dataset.
"""
super(CNN_celeba_client, self).__init__()
self.seq = torch.nn.Sequential(
# client part
torch.nn.Conv2d(in_channels = 3, out_channels = 32, kernel_size = 3, padding = 'same'),
torch.nn.BatchNorm2d(num_features = 32),
torch.nn.MaxPool2d(kernel_size = 2, stride = 2),
torch.nn.ReLU(),
torch.nn.Conv2d(in_channels = 32, out_channels = 32, kernel_size = 3, padding = 'same'),
torch.nn.BatchNorm2d(num_features = 32),
torch.nn.MaxPool2d(kernel_size = 2, stride = 2),
torch.nn.ReLU(),
# server part
# torch.nn.Conv2d(in_channels = 32, out_channels = 32, kernel_size = 3, padding = 'same'),
# torch.nn.BatchNorm2d(num_features = 32),
# torch.nn.MaxPool2d(kernel_size = 2, stride = 2),
# torch.nn.ReLU(),
# torch.nn.Conv2d(in_channels = 32, out_channels = 32, kernel_size = 3, padding = 'same'),
# torch.nn.BatchNorm2d(num_features = 32),
# torch.nn.MaxPool2d(kernel_size = 2, stride = 2),
# torch.nn.ReLU(),
# torch.nn.Flatten(),
# torch.nn.Linear(in_features = 32 * int(image_size / 16) * int(image_size / 16), out_features = num_class)
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Arguments:
x (torch.Tensor): input image tensor.
Returns:
x (torch.Tensor): features.
"""
x = self.seq(x)
return x
class CNN_celeba_server(torch.nn.Module):
"""
Server part model for CelebA task. The model structure follows the LEAF framework.
"""
def __init__(self, image_size: int = 84, num_class: int = 2) -> None:
"""
Arguments:
image_size (int): height / width of image. The image should be of rectangle shape.
num_class (int): number of classes in the dataset.
"""
super(CNN_celeba_server, self).__init__()
self.seq = torch.nn.Sequential(
# client part
# torch.nn.Conv2d(in_channels = 3, out_channels = 32, kernel_size = 3, padding = 'same'),
# torch.nn.BatchNorm2d(num_features = 32),
# torch.nn.MaxPool2d(kernel_size = 2, stride = 2),
# torch.nn.ReLU(),
# torch.nn.Conv2d(in_channels = 32, out_channels = 32, kernel_size = 3, padding = 'same'),
# torch.nn.BatchNorm2d(num_features = 32),
# torch.nn.MaxPool2d(kernel_size = 2, stride = 2),
# torch.nn.ReLU(),
# server part
torch.nn.Conv2d(in_channels = 32, out_channels = 32, kernel_size = 3, padding = 'same'),
torch.nn.BatchNorm2d(num_features = 32),
torch.nn.MaxPool2d(kernel_size = 2, stride = 2),
torch.nn.ReLU(),
torch.nn.Conv2d(in_channels = 32, out_channels = 32, kernel_size = 3, padding = 'same'),
torch.nn.BatchNorm2d(num_features = 32),
torch.nn.MaxPool2d(kernel_size = 2, stride = 2),
torch.nn.ReLU(),
torch.nn.Flatten(),
torch.nn.Linear(in_features = 32 * int(image_size / 16) * int(image_size / 16), out_features = num_class)
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Arguments:
x (torch.Tensor): features.
Returns:
x (torch.Tensor): logits (not softmaxed yet).
"""
x = self.seq(x)
return x
class LSTM_shakespeare_client(torch.nn.Module):
"""
Client part model for Shakespeare dataset. The model structure follows the LEAF framework.
"""
def __init__(self, embedding_dim: int = 8, hidden_size: int = 256, num_class: int = 80) -> None:
"""
Arguments:
embedding_dim (int): dimension of character embedding.
hidden_size (int): dimension of LSTM hidden state.
num_class (int): number of classes (unique characters) in the dataset.
"""
super(LSTM_shakespeare_client, self).__init__()
# client part
self.embedding = torch.nn.Embedding(num_embeddings = num_class, embedding_dim = embedding_dim)
self.encoder = torch.nn.LSTM(input_size = embedding_dim, hidden_size = hidden_size, num_layers = 2, batch_first = True)
# server part
# self.logits = torch.nn.Linear(in_features = hidden_size, out_features = num_class)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Arguments:
x (torch.Tensor): index to embeddings.
Returns:
h (torch.Tensor): features.
"""
x = self.embedding(x)
x, (hn, cn) = self.encoder(x)
h = x[:, -1, :]
return h
class LSTM_shakespeare_server(torch.nn.Module):
"""
Server part model for Shakespeare dataset. The model structure follows the LEAF framework.
"""
def __init__(self, embedding_dim: int = 8, hidden_size: int = 256, num_class: int = 80) -> None:
"""
Arguments:
embedding_dim (int): dimension of character embedding.
hidden_size (int): dimension of LSTM hidden state.
num_class (int): number of classes (unique characters) in the dataset.
"""
super(LSTM_shakespeare_server, self).__init__()
# client part
# self.embedding = torch.nn.Embedding(num_embeddings = num_class, embedding_dim = embedding_dim)
# self.encoder = torch.nn.LSTM(input_size = embedding_dim, hidden_size = hidden_size, num_layers = 2, batch_first = True)
# server part
self.logits = torch.nn.Linear(in_features = hidden_size, out_features = num_class)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Arguments:
x (torch.Tensor): features.
Returns:
x (torch.Tensor): logits (not softmaxed yet).
"""
x = self.logits(x)
return x
def model_eval(args: object,
clients: list[object],
server: object,
use_train_dataset: bool,
wandb_log: dict[str, float],
metric_prefix: str = 'prefix/',
) -> None:
"""
Evaludate the performance of a full model with differnt metrics (loss, accuracy, MCC score, precision, recall, F1 score).
Arguments:
args (argparse.Namespace): parsed argument object.
clients (list[Client]): list of clients.
server (Server): server.
use_train_dataset (bool): whether to use train loader or test loader.
wandb_log (dict[str, float]): wandb log dictionary, with metric name as key and metric value as value.
metric_prefix (str): prefix for metric name.
"""
round_labels = []
round_preds = []
server.model.to(args.device)
server.model.eval()
with torch.no_grad():
for c in clients:
c.model.to(args.device)
c.model.eval()
loader = c.train_loader if use_train_dataset else c.test_loader
for batch_id, (x, y) in enumerate(loader):
x = x.to(args.device)
y = y.to(args.device)
h = c.model(x)
preds = server.model(h)
round_labels.append(y)
round_preds.append(preds)
c.model.to('cpu')
server.model.to('cpu')
round_labels = torch.cat(round_labels).detach().to('cpu')
round_preds = torch.cat(round_preds ).detach().to('cpu')
cal_metrics(round_labels, round_preds, args.binary, wandb_log, metric_prefix)
def cal_metrics(labels: torch.Tensor, preds: torch.Tensor, binary: bool, wandb_log: dict[str, float], metric_prefix: str) -> None:
"""
Compute metrics (loss, accuracy, MCC score, precision, recall, F1 score) using ground truth labels and logits.
Arguments:
labels (torch.Tensor): ground truth labels.
preds (torch.Tensor): logits (not softmaxed yet).
binary (bool): whether doing binary classification or multi-class classification.
wandb_log (dict[str, float]): wandb log dictionary, with metric name as key and metric value as value.
metric_prefix (str): prefix for metric name.
"""
# loss
loss = F.cross_entropy(preds, labels)
wandb_log[metric_prefix + 'loss'] = loss
if not binary: # multi-class
# get probability
preds = torch.softmax(preds, axis = 1)
# ROC AUC
try:
wandb_log[metric_prefix + 'auc'] = roc_auc_score(labels, preds, multi_class = 'ovr')
except Exception:
wandb_log[metric_prefix + 'auc'] = -1
# get class prediction
preds = preds.argmax(axis = 1)
# accuracy and mcc
for metric_name, metric_func in metrics_no_avg.items():
metric = metric_func(labels, preds)
wandb_log[metric_prefix + metric_name] = metric
# precision, recall, f1 score
for metric_name, metric_func in metrics_with_avg.items():
metric = metric_func(labels, preds, average = avg, zero_division = 0)
wandb_log[metric_prefix + metric_name] = metric
else: # binary
# get probability
preds = torch.softmax(preds, axis = 1)[:, 1]
# ROC AUC
try:
wandb_log[metric_prefix + 'auc'] = roc_auc_score(labels, preds)
except Exception:
wandb_log[metric_prefix + 'auc'] = -1
# get class prediction
preds = preds.round()
# accuracy and mcc
for metric_name, metric_func in metrics_no_avg.items():
metric = metric_func(labels, preds)
wandb_log[metric_prefix + metric_name] = metric
# precision, recall, f1 score
for metric_name, metric_func in metrics_with_avg.items():
metric = metric_func(labels, preds, average = avg, zero_division = 0)
wandb_log[metric_prefix + metric_name] = metric
def eval_help(args: object, clients: list[object], server: object) -> None:
"""
Evaluatition helper.
Arguments:
args (argparse.Namespace): parsed argument object.
clients (list[Client]): list of clients.
server (Server): server.
"""
wandb_log = {}
model_eval(args, clients, server, True , wandb_log, 'train/')
model_eval(args, clients, server, False, wandb_log, 'test/' )
wandb.log(wandb_log)