-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcase2.py
193 lines (148 loc) · 6.38 KB
/
case2.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
import os
import pickle
import time
from copy import deepcopy
import numpy as np
import torch
from tqdm import tqdm
import config
from utils import clients, server
from utils.dataloader import get_loaders
from utils.model import get_model
from utils.utils import get_results, save_param, update_results, load_results
np.random.seed(42)
torch.manual_seed(42)
torch.cuda.manual_seed(42)
torch.backends.cudnn.enabled = False
torch.backends.cudnn.deterministic = True
"""
Continue training
"""
if __name__ == "__main__":
args = config.get_args()
train_loaders, test_loader, test_loader_poison = get_loaders(args)
model = get_model(args)
global_param = model.state_dict()
num_rounds = args.num_rounds
num_unlearn_rounds = args.num_unlearn_rounds
num_post_training_rounds = args.num_post_training_rounds
num_onboarding_rounds = args.num_onboarding_rounds
if not args.is_onboarding:
start_time = time.time()
global_param = torch.load(
f"./results/models/case0/case0_{args.dataset}_C{args.num_clients}_BS{args.batch_size}_R{args.num_rounds}_UR{args.num_unlearn_rounds}_PR{args.num_post_training_rounds}_E{args.local_epochs}_LR{args.lr}_round{args.num_rounds-1}.pt"
)
res = get_results(args)
# train and evaluate the FL model
end_round = (
num_rounds + num_unlearn_rounds + num_post_training_rounds
)
for round in range(num_rounds, end_round):
if round == num_rounds + num_unlearn_rounds:
total_time = time.time() - start_time
res["time"] = total_time
print(f"Time {total_time}")
print(
"Round {}/{}: lr {} {}".format(round + 1, end_round, args.lr, args.out_file)
)
train_loss, test_loss = 0, 0
train_corr, test_acc = 0, 0
train_total = 0
list_params = []
chosen_clients = [i for i in range(1, args.num_clients)]
for client in tqdm(chosen_clients):
print(f"-----------client {client} starts training----------")
tem_param, train_summ = clients.client_train(
args,
deepcopy(global_param),
train_loaders[client],
epochs=args.local_epochs,
)
# save client params
# save_param(
# args,
# param=tem_param,
# case=2,
# client=client,
# round=round,
# is_global=False,
# )
train_loss += train_summ["loss"]
train_corr += train_summ["correct"]
train_total += train_summ["total"]
list_params.append(tem_param)
res["train"]["loss"]["avg"].append(train_loss / len(chosen_clients))
res["train"]["acc"]["avg"].append(train_corr / train_total)
print(
"Train loss: {:5f} acc: {:5f}".format(
res["train"]["loss"]["avg"][-1],
res["train"]["acc"]["avg"][-1],
)
)
# server aggregation
global_param = server.FedAvg(list_params)
# save global param
save_param(args, param=global_param, case=2, round=round)
res = update_results(args, res, global_param, test_loader, test_loader_poison)
with open(args.out_file, "wb") as fp:
pickle.dump(res, fp)
else:
######################## onboarding round ############################
start_round = num_rounds + num_unlearn_rounds + num_post_training_rounds
end_round = start_round + num_onboarding_rounds
global_param = torch.load(
f"./results/models/case2/case2_{args.dataset}_C{args.num_clients}_BS{args.batch_size}_R{args.num_rounds}_UR{args.num_unlearn_rounds}_PR{args.num_post_training_rounds}_E{args.local_epochs}_LR{args.lr}_round{start_round-1}.pt"
)
res = load_results(
f"./results/case2_{args.dataset}_C{args.num_clients}_BS{args.batch_size}_R{args.num_rounds}_UR{args.num_unlearn_rounds}_PR{args.num_post_training_rounds}_E{args.local_epochs}_LR{args.lr}.pkl"
)
for round in range(start_round, end_round):
print(
"Round {}/{}: lr {} {}".format(round + 1, end_round, args.lr, args.out_file)
)
train_loss, test_loss = 0, 0
train_corr, test_acc = 0, 0
train_total = 0
list_params = []
chosen_clients = [i for i in range(args.num_clients)]
for client in tqdm(chosen_clients):
print(f"-----------client {client} starts training----------")
tem_param, train_summ = clients.client_train(
args,
deepcopy(global_param),
train_loaders[client],
epochs=args.local_epochs,
)
# save client params
# save_param(
# args,
# param=tem_param,
# case=2,
# client=client,
# round=round,
# is_global=False,
# )
train_loss += train_summ["loss"]
train_corr += train_summ["correct"]
train_total += train_summ["total"]
list_params.append(tem_param)
res["train"]["loss"]["avg"].append(train_loss / len(chosen_clients))
res["train"]["acc"]["avg"].append(train_corr / train_total)
print(
"Train loss: {:5f} acc: {:5f}".format(
res["train"]["loss"]["avg"][-1],
res["train"]["acc"]["avg"][-1],
)
)
# server aggregation
global_param = server.FedAvg(list_params)
# save global param
save_param(args, param=global_param, case=2, round=round)
res = update_results(args, res, global_param, test_loader, test_loader_poison)
with open(args.out_file, "wb") as fp:
pickle.dump(res, fp)
# total_time = time.time() - start_time
# res["time"] = total_time
# print(f"Time {total_time}")
# with open(args.out_file, "wb") as fp:
# pickle.dump(res, fp)