File size: 9,681 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
from easyfsl.methods import PrototypicalNetworks, FewShotClassifier
from typing import Any
from torch.optim import SGD, Optimizer
from tqdm import tqdm
import numpy as np
import torch
from statistics import mean
from torch.optim.lr_scheduler import MultiStepLR
from easyfsl.utils import evaluate
import os


def mmd(x, y, mode=0):
    
    if mode == 0:
        diff = torch.mean(x, dim=0) - torch.mean(y, dim=0) 
    else:
        xf = x.flatten()
        yf = y.flatten()
        diff = xf - yf
    
    return diff #torch.sum(diff**2)


def training_epoch(
    model: FewShotClassifier,
    data_loader: Any,
    optimizer: Optimizer,
    epoch_: int,
    round_name: int,
    station_no: int,
    weighted_loss: bool = False,
    embedding_diff: bool = False,
    track_emb_loss_epoch: bool = False,
    globel_model_1_2: Any = None,
    embedding_diff_plus_loss: bool = False,
    emb_diff_to_server: bool = False,
    loss_funct: str = None,
    LOG_FILE_emb = Any
    
    
):
        emb_df = 0
        emb_list = []
        all_loss = []
        model.train()
        LOSS_FUNCTION = torch.nn.CrossEntropyLoss()
        DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        similar_classes = {
            0: [0,1, 3, 5, 7],
            1: [0,1, 2, 4, 5],
            2: [1,2],
            3: [0, 3,4, 6],
            4: [1, 3,4],
            5: [0, 1,5],
            6: [3,6],
            7: [0,7, 8],
            8: [7,8, 10],
            9: [9,10],
            10: [8, 9,10],
        }
        similarity_matrix = 0.75 * torch.ones((11, 11)).to(DEVICE)
           # Update the matrix with 1 for similar classes
        for class_idx, similar_list in similar_classes.items():
            similarity_matrix[class_idx, similar_list] = 1.0


        with tqdm(
            enumerate(data_loader), total=len(data_loader), desc="Training"
        ) as tqdm_train:
            for episode_index, (support_images, support_labels, query_images, query_labels, _) in tqdm_train:
                optimizer.zero_grad()
                print("im under training epoch-----------------------------")
                model.process_support_set(support_images.to(DEVICE), support_labels.to(DEVICE))
                classification_scores = model(query_images.to(DEVICE))
                weight_matrix = similarity_matrix[np.ix_([0,1,2,3,4,5,7,10],[0,1,2,3,4,5,7,10])]
                weight_matrix = weight_matrix.T
                weight_matrix = weight_matrix[query_labels]
                print(weight_matrix.shape)
                if weighted_loss:
                    print("Im Under weighted_loss")
                    classification_scores = classification_scores * weight_matrix
    
                if embedding_diff:
                    print(f"Loss function is based on embedding difference on seen classes")
                    globel_model_1_2.process_support_set(support_images.to(DEVICE), support_labels.to(DEVICE))
                    classification_scores_ref = globel_model_1_2(query_images.to(DEVICE))
                    # print("im calculating embb distance")
                    # print(classification_scores_ref.shape)
                    # print(classification_scores.shape)
                    if loss_funct == "MSE":
                        print("loss function is MSE")
                        # Assuming classification_scores_ref and classification_scores are tensors
                        emb_diff = torch.mean((classification_scores_ref - classification_scores)**2, dim=0)

                    elif loss_funct == "MMD":
                        print("loss function is MMD")
                        emb_diff = mmd(classification_scores_ref,classification_scores)
                    else:
                        print("loss function is Absolute difference")
                        emb_diff = torch.mean(abs(classification_scores_ref - classification_scores))
                       
                    emb_diff = emb_diff
                    """""you can save the embedding difference in a file"""
                    # if epoch_ == 4 or epoch_ ==1 or epoch_ == 0:
                    #     # combined_tensor = torch.stack([classification_scores, classification_scores_ref])
                    #     array_emb = emb_diff.clone().detach().cpu().numpy()
                    #     # array_emb = combined_tensor.detach().cpu().numpy()
                    #     print("Im appending the matrix--------------again and again")
                    #     log_npy_path = LOG_FILE_emb + f"_{round_name}.npy"
                    #     with open(log_npy_path, "ab") as file:
                    #         np.save(file,array_emb)
                            
                    """"choose the station number to set the embedding difference to zero"""
                    # # if epoch_ == 4:
                    # #     with open(LOG_FILE_emb, "a") as file:
                    # #         file.write(f"emb_diff: {emb_diff}\n")
                    # if station_no == 0:
                    #     emb_diff[:3] = 0
                    # elif station_no == 1:
                    #     emb_diff[:3] = 0
                    # else:
                    #     emb_diff[:3] = 0
                    # # classification_scores += emb_diff
                    emb_diff[:3] = 0
                if embedding_diff_plus_loss:
                    print(f"Loss function is based on embedding difference on seen classes and loss value")
                    globel_model_1_2.process_support_set(support_images.to(DEVICE), support_labels.to(DEVICE))
                    classification_scores_ref = globel_model_1_2(query_images.to(DEVICE))
                    emb_diff = classification_scores_ref - classification_scores
                    emb_diff = abs(emb_diff)
                    emb_diff = torch.sum(emb_diff)
                    emb_diff = emb_diff/100

                if emb_diff_to_server:
                    globel_model_1_2.process_support_set(support_images.to(DEVICE), support_labels.to(DEVICE))
                    classification_scores_ref = globel_model_1_2(query_images.to(DEVICE))
                    emb_diff = classification_scores_ref - classification_scores
                    sum_emb = torch.sum(emb_diff).item()
                    emb_df += sum_emb

                loss = LOSS_FUNCTION(classification_scores, query_labels.to(DEVICE))

                if embedding_diff:
                    if loss_funct == "MMD":
                      emb_loss_epoch = torch.sum(emb_diff**2)*0.1
                    #   loss +=  emb_loss_epoch
                    else:
                        emb_loss_epoch = torch.sum(emb_diff)*0.1
                        # loss += emb_loss_epoch

                if embedding_diff_plus_loss:
                    print(loss)
                    loss+= emb_diff
                    print(loss)
                print(loss)
                loss.backward()
                optimizer.step()

                all_loss.append(loss.item())

                tqdm_train.set_postfix(loss=mean(all_loss))

        if emb_diff_to_server:
            print("Im using emb_diff_to_server to return loss" )
            return mean(all_loss), emb_df
        else:
            return mean(all_loss), emb_loss_epoch
      
            

def train(remote_train_dataset,
          station_model,
          n_epochs,
          learning_rate,
          model,
          scheduler_milestones,
          scheduler_gamma,
          LOG_FILE,
          local_model,
          round,
          LOG_FILE_emb,
          global_model,
          station_n,
          ls_function,
          embedding_diff = False,
          emb_diff_to_server =False,
          embedding_diff_plus_loss=False,
          ):
    emb_df_accumulated =0
    ret_val = None
    for epoch in range(n_epochs):
            print("Im Under train")
            station_model = station_model
            station_optimizer = SGD(model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=5e-4)
            scheduler = MultiStepLR(station_optimizer, milestones=scheduler_milestones, gamma=scheduler_gamma)
            print(f"Epoch for station 1: {epoch}")
            average_loss = training_epoch(station_model, remote_train_dataset, station_optimizer,embedding_diff=embedding_diff,embedding_diff_plus_loss=embedding_diff_plus_loss,emb_diff_to_server=emb_diff_to_server, globel_model_1_2=global_model,LOG_FILE_emb=LOG_FILE_emb,epoch_=epoch,round_name=round,station_no=station_n,loss_funct=ls_function)
            if emb_diff_to_server:
                print(f"average_loss is {average_loss}")
                embb_difference = average_loss[1]
                emb_df_accumulated +=embb_difference
            ret_val = average_loss[1]
            # Log loss to file
            with open(LOG_FILE, "a") as file:
                file.write(f"Epoch: {epoch}, Loss: {average_loss[0]},Embedding loss: {average_loss[1]}\n")
            scheduler.step()
    print(f"local model path is ================{local_model}=============")
    model_file = os.path.join(local_model, f"round--{round}_weights.h5")
    torch.save(station_model.state_dict(), model_file)
    if emb_diff_to_server:
        return emb_df_accumulated
    else:
        return ret_val.clone().detach().cpu().numpy() ##added


def test(net, remote_valid_dataset,LOG_FILE,DEVICE):
    """Evaluate the network on the entire test set."""
    print("Im Under test")
    net.eval()
    validation_accuracy = evaluate(net, remote_valid_dataset, device=DEVICE, tqdm_prefix="Validation")
    with open(LOG_FILE, "a") as file:
            file.write(f"accuracy: {validation_accuracy}\n")
    return validation_accuracy