File size: 17,012 Bytes
29d330e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import argparse
import torch
import torch.nn as nn
import random
import math
import os
import copy
from torchvision import models
from easyfsl.methods import PrototypicalNetworks
from easyfsl.utils import evaluate
from logging import WARNING
from utils_aggregation import aggregate, aggregate_krum, aggregate_median, aggregate_qffl, aggregate_trimmed_avg, weighted_loss_avg
from Client_setup import setup_client
from utils_training import train

random_seed = 0
np.random.seed(random_seed)
torch.manual_seed(random_seed)
random.seed(random_seed)


class federated_training():
    def __init__(
            self,
            method,
            run_name,
            model,
            station_properties,
            rounds,
            epochs,
            num_clients,
            init_weights_pth,
            weighted_loss,
            embedding_diff,
            embedding_diff_plus_loss,
            emb_diff_to_server,
            momentum_vector,
            lossfunction,
            env,
            mode=False,
    ):
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.model = model
        print(f"printing path of global model -------------------{init_weights_pth}")
        self.init_weights = torch.load(init_weights_pth, map_location=self.device)
        self.method = method
        self.rounds = rounds
        self.epochs = epochs
        self.global_model = copy.deepcopy(network_)
        self.global_model.load_state_dict(self.init_weights)
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.momentum_vector: momentum_vector
        self.station_train_loaders = {}
        self.station_valid_loaders = {}
        self.global_model_stations = {}
        self.globel_model_second = {}
        self.station_properties = station_properties
        self.run_name = run_name
        self.clients = num_clients
        self.log_files = []
        self.local_model_pth = []
        self.weighted_loss = weighted_loss
        self.embedding_diff = embedding_diff
        self.embedding_diff_plus_loss = embedding_diff_plus_loss
        self.emb_diff_to_server = emb_diff_to_server
        self.log_emb_diff = []
        self.init_weights_list = list(self.init_weights.values())
        self.server_momentum = 0.0
        self.server_learning_rate = 1.0
        self.mode = mode
        self.lsfunction = lossfunction
        self.env_list_all = env

        print(f"current device is {self.device}")

    def setup_clients(self, num_clients, station_properties, fed_method, run_name, station_train_loaders,
                      station_valid_loaders, global_model_stations, globel_model_second, log_files, local_md_pth,
                      log_emb_diff, env_list):
        for station_number in range(0, num_clients):
            self.setup_client(station_properties, station_number, fed_method, run_name, station_train_loaders,
                              station_valid_loaders, global_model_stations, globel_model_second, log_files,
                              local_md_pth, log_emb_diff, env_list[station_number])

    def setup_client(self, station_properties, station_number, fed_method, run_name, station_train_loaders,
                     station_valid_loaders, global_model_stations, globel_model_second, log_files, local_md_pth,
                     log_emb_diff, env_list):
        setup_client(station_properties, station_number, fed_method, run_name, station_train_loaders,
                     station_valid_loaders, global_model_stations, globel_model_second, log_files, local_md_pth,
                     log_emb_diff, env_list)

    def get_parameters(self, net):
        print("Im Under get_parameters")
        return [val.cpu().numpy() for _, val in net.state_dict().items()]

    def set_parameters(self, net, parameters):
        print("Im Under set_parameters")
        parameters = [param.cpu().numpy() if isinstance(param, torch.Tensor) else param for param in parameters]
        parameters = [torch.from_numpy(param).to(self.device) for param in parameters]
        state_dict = dict(zip(net.state_dict().keys(), parameters))
        net.load_state_dict(state_dict, strict=True)

    def test(self, net, remote_valid_dataset):
        """Evaluate the network on the entire test set."""
        # Evaluate and save the model if it's the best
        net.to(self.device)
        net.eval()
        validation_accuracy = evaluate(net, remote_valid_dataset, self.device, tqdm_prefix="Validation")

        return validation_accuracy

    def fit(self, weights_array_numexpl, server_round):

        if self.method == "FedAvg":
            print("-------------------------Im using FedAvg--------------------------------")
            updated_weights = aggregate(weights_array_numexpl)

        elif self.method == "FedAvgM":
            print("-------------------------Im using FedAvgM--------------------------------")
            fedavg_result = aggregate(weights_array_numexpl)
            assert self.init_weights is not None, "Model needs to be initialized."
            init_weights_list_device = [x.to(self.device) for x in self.init_weights_list]
            fedavg_result_device = [y.to(self.device) for y in fedavg_result]

            pseudo_gradient = [x - y for x, y in zip(init_weights_list_device, fedavg_result_device)]

            if isinstance(self.server_momentum, float):
                print("momentum is float")
            else:
                print("its tuple")
            print({"im underb server momentum calculation-------------------------------"})
            if self.server_momentum > 0.0:
                if server_round > 1:
                    assert self.momentum_vector, "Momentum should have been created on round 1."
                    self.momentum_vector = [
                        self.server_momentum * x + y
                        for x, y in zip(self.momentum_vector, pseudo_gradient)
                    ]
                else:
                    self.momentum_vector = pseudo_gradient

                # Assign pseudo-gradient as momentum
                pseudo_gradient = self.momentum_vector

            # SGD update
            updated_weights = [
                x - self.server_learning_rate * y
                for x, y in zip(init_weights_list_device, pseudo_gradient)
            ]

            # Update current weights
            self.init_weights_list = init_weights_list_device
        elif self.method == "FedMedian":
            print("-------------------------Im using FedMedian--------------------------------")
            updated_weights = aggregate_median(weights_array_numexpl)

        return updated_weights

    def train_fedretaed(self):
        ##set up for clients
        self.setup_clients(self.clients,
                           self.station_properties,
                           self.method,
                           self.run_name,
                           self.station_train_loaders,
                           self.station_valid_loaders,
                           self.global_model_stations,
                           self.globel_model_second,
                           self.log_files,
                           self.local_model_pth,
                           self.log_emb_diff,
                           self.env_list_all)
        prev_round_diff = [0] * self.clients  ##added
        weights_epoch_diff = [0] * self.clients  ##added

        ###########################early-epoch based methods starts here################################
        for rn in range(self.rounds):
            print(f"im runnning for round :{rn + 1}")
            print(f"weights_epoch_diff for round :{rn + 1} are---- {weights_epoch_diff}")
            # (math.floor(max(diff_2)/max(diff)*7))
            if rn == 1:
                eps = self.epochs - 1
                for i in range(len(prev_round_diff)):
                    prev_round_diff[i] = weights_epoch_diff[i]
            elif rn > 1:
                eps = max((math.floor(max(weights_epoch_diff) / max(prev_round_diff) * eps)), 2)
                eps = min(self.epochs, eps)
                eps = eps - 1
                for i in range(len(prev_round_diff)):
                    prev_round_diff[i] = weights_epoch_diff[i]
            else:
                eps = self.epochs - 1  # for rn ==0

            new_epoch = [eps]*self.clients

            if rn > 0:
                weights = [x / max(weights_epoch_diff) for x in weights_epoch_diff]
                new_epoch = [math.floor(x * y) for x, y in zip(new_epoch, weights)]

            new_epoch = [x + 1 for x in new_epoch]
            print(f"epochs for round :{rn + 1} are---- {new_epoch}")

            #################################################################################################################
            s_m = [120, 160]
            s_g = 0.1
            lr = 1e-2
            results_fed = []
            start_emb_df_accumulated = [0] * self.clients
            for station_number, model in enumerate(self.global_model_stations.values(), start=0):
                layer_diff_list = []

                if self.mode:
                    new_epoch = new_epoch  # ---------------------------------------added
                else:
                    new_epoch = [self.epochs, self.epochs, self.epochs, self.epochs]

                if self.emb_diff_to_server:
                    emb_diff_epoch = train(self.station_train_loaders[f"station_{station_number}_train_loaders"],
                                           station_model=model, model=model,
                                           global_model=self.globel_model_second[f"station_{station_number}_globalsecond"],
                                           n_epochs=new_epoch[station_number], learning_rate=lr,
                                           scheduler_milestones=s_m, scheduler_gamma=s_g,
                                           LOG_FILE=self.log_files[station_number], emb_diff_to_server=self.emb_diff_to_server,
                                           local_model=self.local_model_pth[station_number], round=rn + 1,
                                           embedding_diff=self.embedding_diff,
                                           embedding_diff_plus_loss=self.embedding_diff_plus_loss,
                                           LOG_FILE_emb=self.log_emb_diff[station_number], station_n=station_number,
                                           ls_function=self.lsfunction)
                    start_emb_df_accumulated[station_number] = emb_diff_epoch
                    results = self.get_parameters(model), len(self.station_train_loaders), {
                        "embedding_diff": start_emb_df_accumulated[station_number]}
                else:
                    embedding_loss = train(self.station_train_loaders[f"station_{station_number}_train_loaders"],
                                           station_model=model, model=model,
                                           global_model=self.globel_model_second[f"station_{station_number}_globalsecond"],
                                           n_epochs=new_epoch[station_number], learning_rate=lr,
                                           scheduler_milestones=s_m, scheduler_gamma=s_g,
                                           LOG_FILE=self.log_files[station_number], emb_diff_to_server=self.emb_diff_to_server,
                                           local_model=self.local_model_pth[station_number], round=rn + 1,
                                           embedding_diff=self.embedding_diff,
                                           embedding_diff_plus_loss=self.embedding_diff_plus_loss,
                                           LOG_FILE_emb=self.log_emb_diff[station_number], station_n=station_number,
                                           ls_function=self.lsfunction)
                    results = self.get_parameters(model), len(self.station_train_loaders), {}
                results_fed.append(results)

                weights_epoch_diff[station_number] = embedding_loss.item()

            aggregate_weights = self.fit(results_fed, rn)
            root_folder = self.method + self.run_name
            root_folder = os.path.join("../Output", root_folder)
            if aggregate_weights is not None:
                try:
                    state_dict = dict()
                    for idx, param_tensor in enumerate(self.global_model.state_dict()):
                        state_dict[param_tensor] = torch.from_numpy(
                            aggregate_weights[idx].cpu().numpy())  # Convert tensor to NumPy array
                    print(
                        "im saving model under following folder -----------------------------------------------------------------------")
                    model_dir = os.path.join(root_folder, "model")
                    os.makedirs(model_dir, exist_ok=True)
                    model_file = os.path.join(model_dir, f"round--{rn + 1}_weights.h5")
                    self.global_model.load_state_dict(state_dict, strict=False)
                    torch.save(self.global_model.state_dict(), model_file)
                except Exception as e:
                    print(f"Error saving weights for round {rn + 1}: {e}")
            for station_number, model in enumerate(self.global_model_stations.values(), start=1):
                self.set_parameters(model, aggregate_weights)


if __name__ == "__main__":

    station_properties = {
        "permutatiion": [[0, 1, 2, 5], [0, 1, 2, 5]],
        "label_list": [[0, 1, 2, 5], [0, 1, 2, 5]],
        "similarity_labels": [[0, 1, 2, 3, 4, 5, 7, 10], [0, 1, 2, 4, 5, 6, 7, 10], [0, 1, 2, 4, 5, 7, 8, 10],
                              [0, 1, 2, 4, 5, 7, 9, 10]],
        "n_way": 4,
        "n_shot": 2,
        "n_query": 8,
        "n_tasks_per_epoch": 10,  # 250
        "n_validation_tasks": 1,  # 150
        "n_workers": 0,
        "train_test_spl": "./workspace/Jammer_detection/Datasets/Diff_env_daten/base_data/train_random_dep_new.txt",
        "root_dir": "./workspace/Jammer_detection/Datasets/Diff_env_daten/base_data/data",
        "norm_vals": "./workspace/Jammer_detection/Datasets/norm_vals.npy",
        "global_model_path": "./workspace/Jammer_detection/Src/Linkhalle_federated/Src/outputs/2024-04-10/trained_0123/trained_0123/model_weights0epoch100.h5"
    }

    ##########traniner settings############

    ##define model
    model = models.resnet18(pretrained=False)
    model.fc = nn.Identity()
    network_ = PrototypicalNetworks(model)
    init_weights_pth = "./workspace/Jammer_detection/Src/federated_synthetic_data/outputs/2024-02-27/18-12-02/model_global_synthetic/model_weights0epoch100.h5"

    parser = argparse.ArgumentParser(description="Federated Training Argument Parser")
    parser.add_argument("--method", type=str, required=True, help="Training method")
    parser.add_argument("--run_name", type=str, required=True, help="Name of the run")
    parser.add_argument("--model", type=str, default=network_, help="Model name")
    parser.add_argument("--station_properties", default=station_properties, help="Properties for clients")
    parser.add_argument("--rounds", type=int, default=10, help="Number of rounds")
    parser.add_argument("--epochs", type=int, default=5, help="Number of epochs")
    parser.add_argument("--num_clients", type=int, default=2, help="Number of clients")
    parser.add_argument("--init_weights_pth", type=str, default=init_weights_pth, help="initial weights path")
    parser.add_argument("--weighted_loss", type=bool, default=False, help="weighted_loss")
    parser.add_argument("--embedding_diff", type=bool, default=False, help="embedding_diff")
    parser.add_argument("--embedding_diff_plus_loss", type=bool, default=False, help="embedding_diff_plus_loss")
    parser.add_argument("--emb_diff_to_server", type=bool, default=False, help="emb_diff_to_server")
    parser.add_argument("--momentum_vector", type=int, default=None, help="momentum vector")
    parser.add_argument("--lossfunction", type=str, default=None, help="loss function")
    parser.add_argument("--env", type=list, default=[[2, 3, 11, 4, 5], [6, 7, 8, 9, 10]], help="env list")
    parser.add_argument("--mode", type=bool, default=False, help="epoch difference")

    # Add more arguments as needed
    args = parser.parse_args()
    print(f"embeding diff to server value is : {args.emb_diff_to_server}")
    federated_training = federated_training(
        args.method,
        args.run_name,
        args.model,
        args.station_properties,
        args.rounds,
        args.epochs,
        args.num_clients,
        args.init_weights_pth,
        args.weighted_loss,
        args.embedding_diff,
        args.embedding_diff_plus_loss,
        args.emb_diff_to_server,
        args.momentum_vector,
        args.lossfunction,
        args.env,
        args.mode

    )
    federated_training.train_fedretaed()