-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_simulation.py
182 lines (148 loc) · 5.9 KB
/
run_simulation.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
import argparse
import json
import os
from datetime import datetime
import pandas as pd
import torch
import random
import flwr as fl
from utils import DEVICE
from data import cifar_data, femnist_data_json
from models import create_model
from client import FlowerClient
from strategy import FedStrategy
import logging
logging.basicConfig(level=logging.DEBUG)
class Simulation:
def __init__(self, conf):
self.num_clients = conf["num_clients"]
self.client_epochs = conf["client_epochs"]
self.client_dist_epochs = conf["client_epochs"]
self.client_architecture = conf["client_model"]
self.client_optimiser = conf["client_optimiser"]
self.num_rounds = conf["num_rounds"]
self.server_epochs = conf["server_epochs"]
self.server_architecture = conf["server_model"]
self.server_optimiser = conf["server_optimiser"]
self.dataset_name = conf["data_set"]
self.public_ratio = conf["public_ratio"]
self.train_bs = conf["train_bs"]
self.pub_bs = conf["pub_bs"]
strategy_conf = {
**conf,
"fraction_fit": conf["client_participation"],
"fraction_evaluate": 1.0,
"min_fit_clients": 2,
"min_evaluate_clients": 2,
"min_available_clients": 2
}
self.conf = conf
# load dataset
self.train_loaders, self.val_loaders, self.public_loader = self.load_dataset(self.dataset_name)
self.public_data = torch.cat([batch_x[0] for batch_x in self.public_loader], dim=0)
server_model = create_model(self.server_architecture, self.dataset_name) # create server model
self.strategy = FedStrategy(
server_model,
self.public_data,
strategy_conf
)
def client_fn(self, cid):
train_loader = self.train_loaders[int(cid)]
val_loader = self.val_loaders[int(cid)]
return FlowerClient(
cid,
train_loader,
val_loader,
self.public_data,
conf=self.conf
)
def load_dataset(self, data_set):
if data_set == "cifar":
return cifar_data(
self.num_clients,
balanced_data=True,
public_ratio=self.public_ratio,
train_bs=self.train_bs,
pub_bs=self.pub_bs
)
elif data_set == "femnist":
return femnist_data_json(
num_clients=self.num_clients,
public_ratio=self.public_ratio,
train_bs=self.train_bs,
pub_bs=self.pub_bs
)
def run_simulation(self):
client_resources = None
if DEVICE == "cuda":
client_resources = {"num_gpus": 0.9, "num_cpus": 8}
sim_hist = fl.simulation.start_simulation(
client_fn=self.client_fn,
num_clients=self.num_clients,
config=fl.server.ServerConfig(num_rounds=self.num_rounds),
strategy=self.strategy,
client_resources=client_resources
)
_, losses = zip(*sim_hist.losses_distributed)
_, accuracies = zip(*sim_hist.metrics_distributed["accuracy"])
_, train_accuracies = zip(*sim_hist.metrics_distributed_fit["accuracy"])
hist = {
"round": list(range(1, self.num_rounds + 1)),
"losses": losses,
"accuracies": accuracies,
"train_accuracies": train_accuracies
}
# save data
simulation.save_data(hist)
def save_data(self, history):
data = pd.DataFrame(history)
# Dateipfad
directory = "results_data"
path_prefix = (
f"{directory}/{self.server_architecture}-{self.dataset_name}-cl{self.num_clients}-nr{self.num_rounds}"
)
index = 1
while os.path.exists(f"{path_prefix}_{index}.csv"):
index += 1
# store model results
data.to_csv(f"{path_prefix}_{index}.csv", index=False)
# store model
torch.save(self.strategy.model.state_dict(), f"{path_prefix}_{index}_model.pth")
# store config
with open(f"{path_prefix}_{index}_conf.json", "w") as file:
json.dump(self.conf, file, indent=True)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run Compressed Federated Distillation Simulation")
parser.add_argument("-n", "--num_clients", type=int, default=10, help="Number of clients")
parser.add_argument("-r", "--num_rounds", type=int, default=5, help="Number of rounds")
parser.add_argument("-d", "--data_set", type=str, default="cifar", help="Specify data set")
parser.add_argument("--bup", type=int, default=8, help="Upstream precision")
parser.add_argument("--bdown", type=int, default=8, help="Downstream precision")
parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose mode")
args = parser.parse_args()
config = {
"num_clients": args.num_clients,
"num_rounds": args.num_rounds,
"data_set": args.data_set,
"verbose": args.verbose,
"client_epochs": 10,
"client_dist_epochs": 10,
"client_participation": 1.0,
"client_optimiser": "Adam",
"client_model": "resnet18",
"server_epochs": 10,
"server_optimiser": "Adam",
"server_model": "resnet18",
"public_ratio": 0.6, # percentage of train data is split for public data
"train_bs": 64, # training and validation batch size
"pub_bs": 128 # public batch size
}
simulation = Simulation(config)
print(f"Training on {DEVICE} using PyTorch {torch.__version__} and Flower {fl.__version__}")
print("Public data shape:", simulation.public_data.shape)
# start calculation runtime
start = datetime.now()
simulation.run_simulation()
end = datetime.now()
total_runtime = end - start
print("Total runtime: ", total_runtime)