Download Pytorch_federated/utils_training.py from FelixOtt/gnss_federated_learning: direct link, hf CLI and curl.
- Browser
- Download file 9.68 kB
-
https://huggingface.co/datasets/FelixOtt/gnss_federated_learning/resolve/main/Pytorch_federated/utils_training.py
- Command line
-
hf download hf://datasets/FelixOtt/gnss_federated_learning/Pytorch_federated/utils_training.py
-
curl -L -o utils_training.py https://huggingface.co/datasets/FelixOtt/gnss_federated_learning/resolve/main/Pytorch_federated/utils_training.py
9.68 kB
| 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 |