-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
172 lines (138 loc) · 6.2 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
import numpy as np
import copy
import torch
from torch import nn, optim
import torch.nn.functional as F
from tqdm import tqdm
class Client(object):
def __init__(self, name, model, classifier, local_bs, local_ep, lr, momentum, weight_decay, device,
train_dl_local = None, test_dl_local = None):
self.name = name
self.net = model
self.clf = classifier
self.local_bs = local_bs
self.local_ep = local_ep
self.lr = lr
self.momentum = momentum
self.weight_decay = weight_decay
self.device = device
self.loss_func = nn.CrossEntropyLoss()
self.ldr_train = train_dl_local
self.ldr_test = test_dl_local
self.acc_best = 0
self.count = 0
self.save_best = True
self.optimizer = torch.optim.SGD(self.net.parameters(), lr=self.lr/10, momentum=self.momentum, weight_decay=self.weight_decay)
self.clf_optimizer = torch.optim.SGD(self.clf.parameters(), lr=self.lr, momentum=self.momentum, weight_decay=self.weight_decay)
def train(self, clf_list, sims, inter_coeff, is_print = False):
self.net.to(self.device)
self.clf.to(self.device)
self.net.train()
self.clf.train()
for clf in clf_list:
clf.to(self.device)
epoch_loss = []
for iteration in range(self.local_ep):
batch_loss = []
for (images, images_aug, labels) in tqdm(self.ldr_train, desc = self.name):
images, images_aug, labels = images.to(self.device), images_aug.to(self.device), labels.to(self.device)
feature = self.net(images)
output = self.clf(feature)
feature_aug = self.net(images_aug)
output_aug = self.clf(feature_aug)
src_loss1 = self.loss_func(output_aug, labels)
src_loss2 = self.loss_func(output, labels)
task_loss_s = 0.5 * src_loss1 + 0.5 * src_loss2
inter_loss = 0
for i in range(len(clf_list)):
feature = self.net(images)
output_inter = clf_list[i](feature)
if i == 0:
inter_loss = sims[i] * self.loss_func(output_inter, labels)
else:
inter_loss += sims[i] * self.loss_func(output_inter, labels)
inter_loss /= len(clf_list)
loss = task_loss_s + inter_coeff * inter_loss
self.optimizer.zero_grad()
self.clf_optimizer.zero_grad()
loss.backward()
self.optimizer.step()
self.clf_optimizer.step()
batch_loss.append(loss.item())
epoch_loss.append(sum(batch_loss)/len(batch_loss))
# if self.save_best:
# _, acc = self.eval_test()
# if acc > self.acc_best:
# self.acc_best = acc
self.net.cpu()
self.clf.cpu()
for clf in clf_list:
clf.cpu()
return sum(epoch_loss) / len(epoch_loss)
def get_state_dict(self, mode):
if mode == 'clf':
return self.clf.state_dict()
return self.net.state_dict()
def get_best_acc(self):
return self.acc_best
def get_count(self):
return self.count
def get_net(self):
return self.net
def get_clf(self):
return self.clf
def set_state_dict(self, net_state_dict, clf_state_dict):
self.net.load_state_dict(net_state_dict)
self.clf.load_state_dict(clf_state_dict)
def eval_test(self):
self.net.to(self.device)
self.clf.to(self.device)
self.net.eval()
self.clf.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in self.ldr_test:
data, target = data.to(self.device), target.to(self.device)
feature = self.net(data)
output = self.clf(feature)
test_loss += F.cross_entropy(output, target, reduction='sum').item() # sum up batch loss
pred = output.data.max(1, keepdim=True)[1] # get the index of the max log-probability
correct += pred.eq(target.data.view_as(pred)).long().cpu().sum()
test_loss /= len(self.ldr_test.dataset)
accuracy = 100. * correct / len(self.ldr_test.dataset)
return test_loss, accuracy
def eval_test_glob(self, net_glob, clf_glob):
net_glob.to(self.device)
clf_glob.to(self.device)
net_glob.eval()
clf_glob.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in self.ldr_test:
data, target = data.to(self.device), target.to(self.device)
output = clf_glob(net_glob(data))
test_loss += F.cross_entropy(output, target, reduction='sum').item() # sum up batch loss
pred = output.data.max(1, keepdim=True)[1] # get the index of the max log-probability
correct += pred.eq(target.data.view_as(pred)).long().cpu().sum()
test_loss /= len(self.ldr_test.dataset)
accuracy = 100. * correct / len(self.ldr_test.dataset)
return test_loss, accuracy
def eval_train(self):
self.net.to(self.device)
self.clf.to(self.device)
self.net.eval()
self.clf.eval()
train_loss = 0
correct = 0
with torch.no_grad():
for data1, _, target in self.ldr_train:
data1, target = data1.to(self.device), target.to(self.device)
output = self.clf(self.net(data1))
train_loss += F.cross_entropy(output, target, reduction='sum').item() # sum up batch loss
pred = output.data.max(1, keepdim=True)[1] # get the index of the max log-probability
correct += pred.eq(target.data.view_as(pred)).long().cpu().sum()
train_loss /= len(self.ldr_train.dataset)
accuracy = 100. * correct / len(self.ldr_train.dataset)
return train_loss, accuracy