├── logger.py ├── README.md ├── PFL.py ├── main.py ├── VPFL.py ├── Args.py ├── Model.py ├── utils.py ├── Node.py ├── Data.py ├── Trainer.py └── LICENSE /logger.py: -------------------------------------------------------------------------------- 1 | import os 2 | import csv 3 | import time 4 | 5 | class Logger: 6 | def __init__(self, args): 7 | # save results 8 | if args.save_dir is None: 9 | result_dir = './save/' 10 | else: 11 | result_dir = './save/{}/'.format(args.save_dir) 12 | 13 | date = time.strftime('%m%d',time.localtime(time.time())) 14 | result_f = '{}_M{}DB{}_num{}_R{}_E{}_O{}'.format( 15 | date, 16 | args.max_lost, 17 | args.dataset, 18 | args.node_num, 19 | args.R, 20 | args.E, 21 | args.optimizer 22 | ) 23 | 24 | if not os.path.exists(result_dir): 25 | os.makedirs(result_dir) 26 | 27 | self.f = open(result_dir + result_f + ".csv", 'w', newline='') 28 | self.wr = csv.writer(self.f) 29 | self.wr.writerow(['rounds', 'test_acc']) 30 | 31 | 32 | def write(self, rounds, test_acc): 33 | self.wr.writerow([rounds, test_acc]) 34 | 35 | def close(self): 36 | self.f.close() 37 | 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # No One Idles: Efficient Heterogeneous Federated Learning with Parallel Edge and Server Computation 2 | Official implementation for paper "No One Idles: Efficient Heterogeneous Federated Learning with Parallel Edge and Server Computation", ICML 2023 3 | 4 | **TLDR:** We achieve parallel computing between the central server and the edge nodes in Federated Learning. 5 | 6 | **If your project requires executing complex computational tasks on the central server, please use our solution! Our framework allows the aggregation process on the central server and the training process on edge devices to conduct in parallel, thereby improving training efficiency.** 7 | 8 | ## Citation 9 | If you use this code, please cite our paper. 10 | ```@inproceedings{shysheya2022fit, 11 | title={No One Idles: Efficient Heterogeneous Federated Learning with Parallel Edge and Server Computation}, 12 | author={Zhang, Feilong, and Liu, Xianming, and Lin, Shiyi and Wu, Gang and Zhou, Xiong and Jiang, junjun, and Ji, Xiangyang}, 13 | booktitle={International Conference on Machine Learning}, 14 | year={2022}, 15 | organization={PMLR} 16 | } 17 | ``` 18 | ## Usage 19 | 20 | Here is an example for PyTorch: 21 | ``` 22 | python PFL.py --dataset cifar10 --node_num 10 --max_lost 3 --R 200 --E 5 23 | ``` 24 | -------------------------------------------------------------------------------- /PFL.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import time 3 | from torch.cuda import random 4 | from logger import Logger 5 | from Node import Node, Global_Node, Select_Node 6 | from Args import args_parser 7 | from Data import Data 8 | from utils import LR_scheduler, Recorder, Summary 9 | from Trainer import Trainer 10 | 11 | 12 | # init args 13 | args = args_parser() 14 | args.device = torch.device(args.device if torch.cuda.is_available() else 'cpu') 15 | args.split = args.node_num 16 | args.global_model = args.local_model 17 | # args.lr=100 18 | print('Running on', args.device) 19 | Data = Data(args) 20 | Train = Trainer(args) 21 | recorder = Recorder(args) 22 | Summary(args) 23 | 24 | # logs 25 | logger = Logger(args) 26 | 27 | 28 | # init nodes 29 | Global_node = Global_Node(Data.test_all, args) 30 | Edge_nodes = [Node(k, Data.train_loader[k], Data.test_loader, args) for k in range(args.node_num)] 31 | Select_node = Select_Node(args) 32 | 33 | # train 34 | for rounds in range(args.R * args.node_num): 35 | print('===============The {:d}-th round==============='.format(rounds + 1)) 36 | LR_scheduler(rounds, Edge_nodes, args) 37 | k = Select_node.random_select() 38 | for epoch in range(args.E): 39 | Train(Edge_nodes[k]) 40 | recorder.validate(Edge_nodes[k]) 41 | recorder.printer(Edge_nodes[k]) 42 | print('-------------------------') 43 | 44 | Global_node.update(Edge_nodes[k]) # 服务器更新对应的模型参数, 注意,服务器更新的仅是其局部模型,全局模型没更新。这么做是为了避免使用中间变量 45 | Edge_nodes[k].fork(Global_node) # 节点从服务器读取全局模型后直接返回 46 | Global_node.processing() # 服务器根据其局部模型生成全局模型。可以看到中央服务器的计算过程与边缘节点是可以同时计算的。因此,可以认为是并行计算。 47 | 48 | # log 49 | recorder.validate(Global_node) 50 | recorder.printer(Global_node) 51 | logger.write(rounds=rounds + 1, test_acc=recorder.val_acc[str(Global_node.num)][rounds]) 52 | 53 | recorder.finish() 54 | logger.close() 55 | 56 | Summary(args) 57 | 58 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import time 3 | import wandb 4 | from logger import Logger 5 | from Node import Node, Global_Node 6 | from Args import args_parser 7 | from Data import Data 8 | from utils import LR_scheduler, Recorder, Summary 9 | from Trainer import Trainer 10 | 11 | 12 | # init args 13 | args = args_parser() 14 | args.device = torch.device(args.device if torch.cuda.is_available() else 'cpu') 15 | args.split = args.node_num 16 | args.global_model = args.local_model 17 | print('Running on', args.device) 18 | Data = Data(args) 19 | Train = Trainer(args) 20 | recorder = Recorder(args) 21 | Summary(args) 22 | 23 | 24 | # logs 25 | wandb.init(project="DFL", entity="paridis") # 搜一下 wandb的使用方法,entity后填你的用户名 26 | config = wandb.config 27 | config.communications_round = args.R 28 | config.max_lost = args.max_lost 29 | config.node_num = args.node_num 30 | config.dataset = args.dataset 31 | config.local_epoch = args.E 32 | config.optimizer = args.optimizer 33 | config.shuffle = 1 34 | config.local_model = args.local_model 35 | logger = Logger(args) 36 | 37 | 38 | # init nodes 39 | Global_node = Global_Node(Data.test_all, args) 40 | Edge_nodes = [Node(k, Data.train_loader[k], Data.test_loader, args) for k in range(args.node_num)] 41 | 42 | # train 43 | for rounds in range(args.R): 44 | print('===============The {:d}-th round==============='.format(rounds + 1)) 45 | LR_scheduler(rounds, Edge_nodes, args) 46 | for k in range(len(Edge_nodes)): 47 | Edge_nodes[k].fork(Global_node) # download 48 | for epoch in range(args.E): 49 | Train(Edge_nodes[k]) 50 | recorder.validate(Edge_nodes[k]) 51 | recorder.printer(Edge_nodes[k]) 52 | print('-------------------------') 53 | 54 | Global_node.merge(Edge_nodes) # upload 55 | 56 | # log 57 | recorder.validate(Global_node) 58 | recorder.printer(Global_node) 59 | logger.write(rounds=rounds + 1, test_acc=recorder.val_acc[str(Global_node.num)][rounds]) 60 | wandb.log({"DFL": recorder.val_acc[str(Global_node.num)][rounds]}) 61 | 62 | 63 | recorder.finish() 64 | logger.close() 65 | 66 | Summary(args) 67 | 68 | -------------------------------------------------------------------------------- /VPFL.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import torch 3 | import time 4 | from torch.cuda import random 5 | import wandb 6 | from logger import Logger 7 | from Node import Node, Global_Node, Select_Node 8 | from Args import args_parser 9 | from Data import Data 10 | from utils import LR_scheduler, Recorder, Summary 11 | from Trainer import Trainer 12 | 13 | 14 | # init args 15 | args = args_parser() 16 | args.device = torch.device(args.device if torch.cuda.is_available() else 'cpu') 17 | args.split = args.node_num 18 | args.global_model = args.local_model 19 | args.max_lost = 0 20 | # args.lr=100 21 | print('Running on', args.device) 22 | Data = Data(args) 23 | Train = Trainer(args) 24 | recorder = Recorder(args) 25 | Summary(args) 26 | 27 | # logs 28 | wandb.init(project="PFL", entity="paridis") 29 | config = wandb.config 30 | config.communications_round = args.R 31 | config.max_lost = args.max_lost 32 | config.node_num = args.node_num 33 | config.dataset = args.dataset 34 | config.local_epoch = args.E 35 | config.optimizer = args.optimizer 36 | config.shuffle = 1 37 | config.local_model = args.local_model 38 | logger = Logger(args) # TODO 记录的数据无法实时观看,目前只能迭代完成后才能看到每次迭代的 acc。 39 | 40 | 41 | # init nodes 42 | Global_node = Global_Node(Data.test_all, args) 43 | Edge_nodes = [Node(k, Data.train_loader[k], Data.test_loader, args) for k in range(args.node_num)] 44 | Select_node = Select_Node(args) 45 | 46 | node_count = args.node_num 47 | lr = [] 48 | # train 49 | for rounds in range(args.R): 50 | print('===============The {:d}-th round==============='.format(rounds + 1)) 51 | LR_scheduler(rounds, Edge_nodes, args) 52 | lr.append(args.lr) 53 | for k in range(len(Edge_nodes)): 54 | for epoch in range(args.E): 55 | Train(Edge_nodes[k]) 56 | recorder.validate(Edge_nodes[k]) 57 | recorder.printer(Edge_nodes[k]) 58 | print('-------------------------') 59 | Global_node.update(Edge_nodes[k]) # 服务器更新对应的模型参数, 注意,服务器更新的仅是其局部模型,全局模型没更新。这么做是为了避免使用中间变量 60 | Edge_nodes[k].fork(Global_node) # 节点从服务器读取全局模型后直接返回 61 | Global_node.processing() # 服务器根据其局部模型生成全局模型。可以看到中央服务器的计算过程与边缘节点是可以同时计算的。因此,可以认为是并行计算。 62 | 63 | # log 64 | recorder.validate(Global_node) 65 | recorder.printer(Global_node) 66 | logger.write(rounds=rounds + 1, test_acc=recorder.val_acc[str(Global_node.num)][rounds]) 67 | wandb.log({"VPFL": recorder.val_acc[str(Global_node.num)][rounds]}) 68 | 69 | recorder.finish() 70 | logger.close() 71 | 72 | Summary(args) 73 | 74 | -------------------------------------------------------------------------------- /Args.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | 4 | def args_parser(): 5 | parser = argparse.ArgumentParser() 6 | 7 | # Total 8 | parser.add_argument('--algorithm', type=str, default='fed_avg', 9 | help='Type of algorithms:{fed_mutual, fed_avg, fed_coteaching, normal, parallel}') 10 | parser.add_argument('--device', type=str, default='cuda:0', 11 | help='device: {cuda, cpu}') 12 | parser.add_argument('--node_num', type=int, default=10, 13 | help='Number of nodes') 14 | parser.add_argument('--R', type=int, default=200, 15 | help='Number of rounds: R') 16 | parser.add_argument('--E', type=int, default=5, 17 | help='Number of local epochs: E') 18 | parser.add_argument('--notes', type=str, default='', 19 | help='Notes of Experiments') 20 | parser.add_argument('--max_lost', type=int, default=1, 21 | help='The difference in the number of communication rounds between the fastest and slowest nodes ') 22 | parser.add_argument('--warmup', type=int, default=5, 23 | help='The number of warmup') 24 | parser.add_argument('--mu', type=float, default=0.2, 25 | help='Degree of non-iid') 26 | 27 | 28 | # Model 29 | parser.add_argument('--global_model', type=str, default='ResNet18', 30 | help='Type of global model: {LeNet5, MLP, CNN2, ResNet18}') 31 | parser.add_argument('--local_model', type=str, default='ResNet18', 32 | help='Type of local model: {LeNet5, MLP, CNN2, ResNet18}') 33 | 34 | # Data 35 | parser.add_argument('--dataset', type=str, default='cifar10', 36 | help='datasets: {cifar100, cifar10, femnist, mnist}') 37 | parser.add_argument('--batchsize', type=int, default=128, 38 | help='batchsize') 39 | parser.add_argument('--split', type=int, default=5, 40 | help='data split') 41 | parser.add_argument('--val_ratio', type=float, default=0.1, 42 | help='val_ratio') 43 | parser.add_argument('--all_data', type=bool, default=True, 44 | help='use all train_set') 45 | parser.add_argument('--classes', type=int, default=10, 46 | help='classes') 47 | parser.add_argument('--save_dir', type=str, default=None, help="name of save directory") 48 | parser.add_argument('--sampler', type=str, default='iid', help="iid, non-iid") 49 | 50 | # noise 51 | parser.add_argument('--noise_rate', type=float, default=0, 52 | help='噪声比例') 53 | parser.add_argument('--noise_type', type=str, default='clean', 54 | help='噪声类型: {symmetric, asymmetric, clean}') 55 | parser.add_argument('--num_gradual', type=int, default=5, 56 | help='how many epochs for linear drop rate, can be 5, 10, 15. This parameter is equal to ' 57 | 'Tk for R(T) in Co-teaching paper.') 58 | parser.add_argument('--exponent', type=float, default=1, 59 | help='exponent of the forget rate, can be 0.5, 1, 2. This parameter is equal to c in ' 60 | 'Tc for R(T) in Co-teaching paper.') 61 | parser.add_argument('--loss', type=str, default='CE', 62 | help='loss:{CE, GCE}') 63 | parser.add_argument('--is_sparse', type=int, default=0, 64 | help='if use the sparse regularizatoin mechanism') 65 | 66 | 67 | # Optima 68 | parser.add_argument('--optimizer', type=str, default='sgd', 69 | help='optimizer: {sgd, adam}') 70 | parser.add_argument('--lr', type=float, default=0.01, 71 | help='learning rate') 72 | parser.add_argument('--lr_step', type=int, default=10, 73 | help='learning rate decay step size') 74 | parser.add_argument('--stop_decay', type=int, default=50, 75 | help='round when learning rate stop decay') 76 | parser.add_argument('--momentum', type=float, default=0.9, 77 | help='SGD momentum') 78 | parser.add_argument('--alpha', type=float, default=0.5, 79 | help='local ratio of data loss') 80 | parser.add_argument('--beta', type=float, default=0.5, 81 | help='global ratio of data loss') 82 | 83 | args = parser.parse_args() 84 | return args 85 | -------------------------------------------------------------------------------- /Model.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | import torch.nn.functional as F 3 | 4 | 5 | class ResidualBlock(nn.Module): 6 | def __init__(self, inchannel, outchannel, stride=1): 7 | super(ResidualBlock, self).__init__() 8 | self.left = nn.Sequential( 9 | nn.Conv2d( 10 | inchannel, 11 | outchannel, 12 | kernel_size=3, 13 | stride=stride, 14 | padding=1, 15 | bias=False, 16 | ), 17 | nn.BatchNorm2d(outchannel), 18 | nn.ReLU(inplace=True), 19 | nn.Conv2d( 20 | outchannel, outchannel, kernel_size=3, stride=1, padding=1, bias=False 21 | ), 22 | nn.BatchNorm2d(outchannel), 23 | ) 24 | self.shortcut = nn.Sequential() 25 | if stride != 1 or inchannel != outchannel: 26 | self.shortcut = nn.Sequential( 27 | nn.Conv2d( 28 | inchannel, outchannel, kernel_size=1, stride=stride, bias=False 29 | ), 30 | nn.BatchNorm2d(outchannel), 31 | ) 32 | 33 | def forward(self, x): 34 | out = self.left(x) 35 | out += self.shortcut(x) 36 | out = F.relu(out) 37 | return out 38 | 39 | 40 | class ResNet(nn.Module): 41 | def __init__(self, residual_block, num_classes=10): 42 | super(ResNet, self).__init__() 43 | self.inchannel = 64 44 | self.conv1 = nn.Sequential( 45 | nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False), 46 | nn.BatchNorm2d(64), 47 | nn.ReLU(), 48 | ) 49 | self.layer1 = self.make_layer(residual_block, 64, 2, stride=1) 50 | self.layer2 = self.make_layer(residual_block, 128, 2, stride=2) 51 | self.layer3 = self.make_layer(residual_block, 256, 2, stride=2) 52 | self.layer4 = self.make_layer(residual_block, 512, 2, stride=2) 53 | self.fc = nn.Linear(512, num_classes) 54 | 55 | def make_layer(self, block, channels, num_blocks, stride): 56 | strides = [stride] + [1] * (num_blocks - 1) # strides=[1,1] 57 | layers = [] 58 | for stride in strides: 59 | layers.append(block(self.inchannel, channels, stride)) 60 | self.inchannel = channels 61 | return nn.Sequential(*layers) 62 | 63 | def forward(self, x): 64 | out = self.conv1(x) 65 | out = self.layer1(out) 66 | out = self.layer2(out) 67 | out = self.layer3(out) 68 | out = self.layer4(out) 69 | out = F.avg_pool2d(out, 4) 70 | out = out.view(out.size(0), -1) 71 | out = self.fc(out) 72 | return out 73 | 74 | 75 | def ResNet18(): 76 | return ResNet(ResidualBlock) 77 | 78 | 79 | class LeNet5(nn.Module): 80 | def __init__(self): 81 | super(LeNet5, self).__init__() 82 | self.conv1 = nn.Conv2d(3, 6, 5) 83 | self.conv2 = nn.Conv2d(6, 16, 5) 84 | self.fc1 = nn.Linear(16 * 5 * 5, 120) 85 | self.fc2 = nn.Linear(120, 84) 86 | self.fc3 = nn.Linear(84, 10) 87 | 88 | def forward(self, x): 89 | x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) 90 | x = F.max_pool2d(F.relu(self.conv2(x)), 2) 91 | x = x.view(-1, 16 * 5 * 5) 92 | x = F.relu(self.fc1(x)) 93 | x = F.relu(self.fc2(x)) 94 | x = self.fc3(x) 95 | return x 96 | 97 | 98 | class MLP(nn.Module): 99 | def __init__(self): 100 | super(MLP, self).__init__() 101 | self.fc1 = nn.Linear(3 * 32 * 32, 200) 102 | self.fc2 = nn.Linear(200, 200) 103 | self.fc3 = nn.Linear(200, 10) 104 | 105 | def forward(self, x): 106 | x = x.view(-1, 3 * 32 * 32) 107 | x = F.relu(self.fc1(x)) 108 | x = F.relu(self.fc2(x)) 109 | x = self.fc3(x) 110 | return x 111 | 112 | 113 | class CNN(nn.Module): 114 | def __init__(self): 115 | super(CNN, self).__init__() 116 | self.conv1 = nn.Conv2d(3, 32, 3) 117 | self.pool = nn.MaxPool2d(2, 2) 118 | self.conv2 = nn.Conv2d(32, 64, 3) 119 | self.conv3 = nn.Conv2d(64, 64, 3) 120 | self.fc1 = nn.Linear(64 * 4 * 4, 64) 121 | self.fc2 = nn.Linear(64, 10) 122 | 123 | def forward(self, x): 124 | x = self.pool(F.relu(self.conv1(x))) 125 | x = self.pool(F.relu(self.conv2(x))) 126 | x = F.relu(self.conv3(x)) 127 | x = x.view(-1, 64 * 4 * 4) 128 | x = F.relu(self.fc1(x)) 129 | x = self.fc2(x) 130 | return x 131 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import Node 3 | import numpy as np 4 | # from torch.utils.tensorboard import SummaryWriter 5 | # writer = SummaryWriter() 6 | 7 | class Recorder(object): 8 | def __init__(self, args): 9 | self.args = args 10 | self.counter = 0 11 | self.tra_loss = {} 12 | self.tra_acc = {} 13 | self.val_loss = {} 14 | self.val_acc = {} 15 | for i in range(self.args.node_num + 1): 16 | self.val_loss[str(i)] = [] 17 | self.val_acc[str(i)] = [] 18 | # self.val_loss[str(i)] = [] 19 | # self.val_acc[str(i)] = [] 20 | self.acc_best = torch.zeros(self.args.node_num + 1) 21 | self.get_a_better = torch.zeros(self.args.node_num + 1) 22 | 23 | def validate(self, node): 24 | self.counter += 1 25 | node.model.to(node.device).eval() 26 | total_loss = 0.0 27 | correct = 0.0 28 | pred_res = [] 29 | target_res = [] 30 | 31 | with torch.no_grad(): 32 | for idx, (data, target) in enumerate(node.test_data): 33 | data, target = data.to(node.device), target.to(node.device) 34 | output = node.model(data) 35 | total_loss += torch.nn.CrossEntropyLoss()(output, target) 36 | pred = output.argmax(dim=1) 37 | correct += pred.eq(target.view_as(pred)).sum().item() 38 | pred_res.append(pred) 39 | target_res.append(target) 40 | 41 | total_loss = total_loss / (idx + 1) 42 | acc = correct / len(node.test_data.dataset) * 100 43 | 44 | pred_res = torch.cat(pred_res) 45 | target_res = torch.cat(target_res) 46 | prec = [] 47 | for i in range(10): 48 | mask = target_res == i 49 | idx = np.where(mask.cpu().numpy())[0] 50 | c_ac = sum(pred_res[idx] == target_res[idx])/sum(mask) 51 | prec.append(float(c_ac.cpu().numpy())) 52 | #print(prec) 53 | 54 | self.val_loss[str(node.num)].append(total_loss) 55 | self.val_acc[str(node.num)].append(acc) 56 | 57 | if self.val_acc[str(node.num)][-1] > self.acc_best[node.num]: 58 | self.get_a_better[node.num] = 1 59 | self.acc_best[node.num] = self.val_acc[str(node.num)][-1] 60 | # torch.save(node.model.state_dict(), 61 | # './saves/model/Node{:d}_{:s}.pth'.format(node.num, node.args.local_model)) 62 | 63 | def printer(self, node): 64 | if self.get_a_better[node.num] == 1: 65 | print('Node{:d}: A Better Accuracy: {:.2f}%! Model Saved!'.format(node.num, self.acc_best[node.num])) 66 | 67 | self.get_a_better[node.num] = 0 68 | # if node.num == 0: 69 | # print(self.val_acc[str(node.num)]) 70 | # print(self.val_loss[str(node.num)]) 71 | print(f'节点 {node.num} 的准确率: {self.val_acc[str(node.num)]}') 72 | print(self.val_loss[str(node.num)]) 73 | 74 | 75 | def finish(self): 76 | # torch.save([self.val_loss, self.val_acc], 77 | # './saves/record/loss_acc_{:s}_{:s}.pt'.format(self.args.algorithm, self.args.notes)) 78 | print('Finished!\n') 79 | for i in range(self.args.node_num + 1): 80 | print('Node{}: Best Accuracy = {:.2f}%'.format(i, self.acc_best[i])) 81 | 82 | 83 | 84 | def LR_scheduler(rounds, Edge_nodes, args): 85 | 86 | for i in range(len(Edge_nodes)): 87 | Edge_nodes[i].args.lr = args.lr 88 | Edge_nodes[i].args.alpha = args.alpha 89 | Edge_nodes[i].args.beta = args.beta 90 | Edge_nodes[i].optimizer.param_groups[0]['lr'] = args.lr 91 | 92 | print('Learning rate={:.4f}'.format(args.lr)) 93 | 94 | 95 | def LR_scheduler2(rounds, Edge_nodes, args): 96 | trigger = int(args.R / 3) 97 | if rounds != 0 and rounds % trigger == 0 and rounds < args.stop_decay: 98 | args.lr *= 0.1 99 | # args.alpha += 0.2 100 | # args.beta += 0.4 101 | for i in range(len(Edge_nodes)): 102 | Edge_nodes[i].args.lr = args.lr 103 | Edge_nodes[i].args.alpha = args.alpha 104 | Edge_nodes[i].args.beta = args.beta 105 | Edge_nodes[i].optimizer.param_groups[0]['lr'] = args.lr 106 | 107 | print('Learning rate={:.4f}'.format(args.lr)) 108 | 109 | 110 | def Summary(args): 111 | print("Summary:\n") 112 | print("max_lost:{}\n".format(args.max_lost)) 113 | print("dataset:{}\tbatchsize:{}\n".format(args.dataset, args.batchsize)) 114 | print("node_num:{},\tsplit:{}\n".format(args.node_num, args.split)) 115 | # print("iid:{},\tequal:{},\n".format(args.iid == 1, args.unequal == 0)) 116 | print("global epochs:{},\tlocal epochs:{},\n".format(args.R, args.E)) 117 | print("global_model:{},\tlocal model:{},\n".format(args.global_model, args.local_model)) 118 | -------------------------------------------------------------------------------- /Node.py: -------------------------------------------------------------------------------- 1 | import copy 2 | from re import S 3 | from numpy import s_ 4 | import torch 5 | # from torch.cuda import random 6 | import random 7 | import Model 8 | 9 | 10 | def init_model(model_type): 11 | model = [] 12 | if model_type == 'LeNet5': 13 | model = Model.LeNet5() 14 | elif model_type == 'MLP': 15 | model = Model.MLP() 16 | elif model_type == 'ResNet18': 17 | model = Model.ResNet18() 18 | elif model_type == 'CNN': 19 | model = Model.CNN() 20 | return model 21 | 22 | 23 | def init_optimizer(model, args): 24 | optimizer = [] 25 | if args.optimizer == 'sgd': 26 | optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=5e-4) 27 | elif args.optimizer == 'adam': 28 | optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay=1e-4) 29 | return optimizer 30 | 31 | 32 | def weights_zero(model): 33 | for p in model.parameters(): 34 | if p.data is not None: 35 | p.data.detach_() 36 | p.data.zero_() 37 | 38 | 39 | class Node(object): 40 | def __init__(self, num, train_data, test_data, args): 41 | self.args = args 42 | self.num = num + 1 43 | self.device = self.args.device 44 | self.train_data = train_data 45 | self.test_data = test_data 46 | 47 | self.model = init_model(self.args.local_model).to(self.device) 48 | self.optimizer = init_optimizer(self.model, self.args) 49 | 50 | # self.global_model = init_model(self.args.global_model).to(self.device) 51 | # self.global_optimizer = init_optimizer(self.global_model, self.args) 52 | 53 | ## 54 | # self.s_list = [] # 存储待选择的节点名单 55 | # self.c_list = [] # 已选择的节点名单 56 | # self.node_list = list(range(1, args.node_num)) 57 | # self.max_lost = 1 # 最快节点与最慢节点的通讯回合差 58 | 59 | # for j in range(self.max_lost): 60 | # self.s_list.extend(self.node_list) 61 | 62 | def fork(self, global_node): 63 | # 每次迭代后,接收新的global_model 64 | self.model = copy.deepcopy(global_node.model).to(self.device) 65 | self.optimizer = init_optimizer(self.model, self.args) 66 | 67 | 68 | # def random_select(self): 69 | # index = random.randrange(len(self.s_list)) # 随机取下标 70 | # chosen_number = self.s_list.pop(index) # 找到下标对应的节点序号 71 | # self.c_list.append(chosen_number) # 中间变量,衡量是否全部节点完成一次通讯 72 | # print(self.c_list) 73 | 74 | # if len(set(self.c_list)) == self.args.node_num : 75 | # self.s_list.extend(self.node_list) # 判断为真,代表所有节点完成一次迭代,此时,向待选列表增加全部节点序号 76 | # self.c_list.clear() # 清空中间变量 ???要全部清空么? 77 | 78 | # return chosen_number 79 | 80 | 81 | class Select_Node(object): 82 | def __init__(self, args): 83 | self.args = args 84 | self.s_list = [] # 存储待选择的节点名单 85 | self.c_list = [] # 已选择的节点名单 86 | self.node_list = list(range(args.node_num)) 87 | self.max_lost = args.max_lost # 最快节点与最慢节点的通讯回合差 88 | 89 | for j in range(self.max_lost): 90 | self.s_list.extend(self.node_list) 91 | 92 | 93 | def random_select(self): 94 | index = random.randrange(len(self.s_list)) # 随机取下标 95 | chosen_number = self.s_list.pop(index) # 找到下标对应的节点序号 96 | self.c_list.append(chosen_number) # 中间变量,衡量是否全部节点完成一次通讯 97 | print(self.c_list) 98 | 99 | if len(set(self.c_list)) == self.args.node_num : 100 | self.s_list.extend(self.node_list) # 判断为真,代表所有节点完成一次迭代,此时,向待选列表增加全部节点序号 101 | [self.c_list.remove(i) for i in range(self.args.node_num)] # 清空中间变量 102 | 103 | return chosen_number 104 | 105 | 106 | class Global_Node(object): 107 | def __init__(self, test_data, args): 108 | self.num = 0 109 | self.args = args 110 | self.device = self.args.device 111 | self.model = init_model(self.args.global_model).to(self.device) 112 | 113 | self.test_data = test_data 114 | self.Dict = self.model.state_dict() 115 | 116 | # self.edge_node = [Model.ResNet18().to(self.device) for k in range(args.node_num)] 117 | self.edge_node = [init_model(self.args.global_model).to(self.device) for k in range(args.node_num)] 118 | self.init = False 119 | self.save = [] 120 | 121 | def merge(self, Edge_nodes): 122 | # weights_zero(self.model) 123 | Node_State_List = [copy.deepcopy(Edge_nodes[i].model.state_dict()) for i in range(len(Edge_nodes))] 124 | self.Dict = Node_State_List[0] 125 | 126 | for key in self.Dict.keys(): 127 | for i in range(1, len(Edge_nodes)): 128 | self.Dict[key] += Node_State_List[i][key] 129 | 130 | self.Dict[key] = self.Dict[key].float() # 不知道为什么数据类型会发生变化 131 | self.Dict[key] /= len(Edge_nodes) 132 | self.model.load_state_dict(self.Dict) 133 | 134 | 135 | def update(self, Edge_node): 136 | ## 中央服务器的局部模型更新 137 | self.edge_node[Edge_node.num-1] = Edge_node.model 138 | 139 | def init_processing(self): 140 | assert self.init 141 | ## warmup 142 | Node_State_List = [copy.deepcopy(self.edge_node[i].state_dict()) for i in self.save] 143 | self.Dict = Node_State_List[0] 144 | for key in self.Dict.keys(): 145 | if 'num_batches_tracked' in key: 146 | continue 147 | 148 | for i in range(1, len(Node_State_List)): 149 | self.Dict[key] += Node_State_List[i][key] 150 | 151 | # self.Dict[key] = self.Dict[key].float() # 不知道为什么数据类型会发生变化 152 | # print(self.Dict[key], key) 153 | self.Dict[key] /= float(len(Node_State_List)) 154 | 155 | self.model.load_state_dict(self.Dict) 156 | 157 | def processing(self): 158 | ## 中央服务器的全局模型更新 159 | Node_State_List = [copy.deepcopy(self.edge_node[i].state_dict()) for i in range(self.args.node_num)] 160 | self.Dict = Node_State_List[0] 161 | for key in self.Dict.keys(): 162 | if 'num_batches_tracked' in key: 163 | continue 164 | for i in range(1, self.args.node_num): 165 | self.Dict[key] += Node_State_List[i][key] 166 | # self.Dict[key] = self.Dict[key].float() # 不知道为什么数据类型会发生变化 167 | self.Dict[key] /= self.args.node_num 168 | self.model.load_state_dict(self.Dict) 169 | 170 | 171 | 172 | 173 | # class Initiate_node(object): 174 | # def __init__(self, test_data, args): 175 | # self.num = 0 176 | # self.args = args 177 | # self.device = self.args.device 178 | # self.model = init_model(self.args.global_model).to(self.device) 179 | 180 | 181 | # self.test_data = test_data 182 | # self.Dict = self.model.state_dict() 183 | 184 | 185 | 186 | # def merge(self, Edge_nodes): 187 | # # weights_zero(self.model) 188 | # Node_State_List = [copy.deepcopy(Edge_nodes[i].global_model.state_dict()) for i in range(len(Edge_nodes))] 189 | # self.Dict = Node_State_List[0] 190 | 191 | # for key in self.Dict.keys(): 192 | # for i in range(1, len(Edge_nodes)): 193 | # self.Dict[key] += Node_State_List[i][key] 194 | 195 | # self.Dict[key] = self.Dict[key].float() # 不知道为什么数据类型会发生变化 196 | # self.Dict[key] /= len(Edge_nodes) 197 | # self.model.load_state_dict(self.Dict) 198 | 199 | -------------------------------------------------------------------------------- /Data.py: -------------------------------------------------------------------------------- 1 | from random import shuffle 2 | import torch 3 | import numpy as np 4 | import os.path 5 | from torchvision.datasets import utils, MNIST, CIFAR10, CIFAR100 6 | from torchvision import transforms 7 | from torch.utils.data import Subset, DataLoader, random_split 8 | from PIL import Image 9 | # from noisify import noisify_label 10 | 11 | 12 | class FEMNIST(MNIST): 13 | """ 14 | This dataset is derived from the Leaf repository 15 | (https://github.com/TalwalkarLab/leaf) pre-processing of the Extended MNIST 16 | dataset, grouping examples by writer. Details about Leaf were published in 17 | "LEAF: A Benchmark for Federated Settings" https://arxiv.org/abs/1812.01097. 18 | """ 19 | resources = [ 20 | ('https://raw.githubusercontent.com/tao-shen/FEMNIST_pytorch/master/femnist.tar.gz', 21 | '59c65cec646fc57fe92d27d83afdf0ed')] 22 | 23 | def __init__(self, root, train=True, transform=None, target_transform=None, 24 | download=True): 25 | super(MNIST, self).__init__(root, transform=transform, 26 | target_transform=target_transform) 27 | self.train = train 28 | 29 | if download: 30 | self.download() 31 | 32 | if not self._check_exists(): 33 | raise RuntimeError('Dataset not found.' + 34 | ' You can use download=True to download it') 35 | if self.train: 36 | data_file = self.training_file 37 | else: 38 | data_file = self.test_file 39 | 40 | self.data, self.targets, self.users_index = torch.load(os.path.join(self.processed_folder, data_file)) 41 | 42 | def __getitem__(self, index): 43 | img, target = self.data[index], int(self.targets[index]) 44 | img = Image.fromarray(img.numpy(), mode='F') 45 | if self.transform is not None: 46 | img = self.transform(img) 47 | if self.target_transform is not None: 48 | target = self.target_transform(target) 49 | return img, target 50 | 51 | def download(self): 52 | """Download the FEMNIST data if it doesn't exist in processed_folder already.""" 53 | import shutil 54 | 55 | if self._check_exists(): 56 | return 57 | 58 | utils.makedir_exist_ok(self.raw_folder) 59 | utils.makedir_exist_ok(self.processed_folder) 60 | 61 | # download files 62 | for url, md5 in self.resources: 63 | filename = url.rpartition('/')[2] 64 | utils.download_and_extract_archive(url, download_root=self.raw_folder, filename=filename, md5=md5) 65 | 66 | # process and save as torch files 67 | print('Processing...') 68 | shutil.move(os.path.join(self.raw_folder, self.training_file), self.processed_folder) 69 | shutil.move(os.path.join(self.raw_folder, self.test_file), self.processed_folder) 70 | 71 | 72 | def Dataset(args): 73 | trainset, testset = None, None 74 | 75 | if args.dataset == 'cifar10': 76 | tra_trans = transforms.Compose([ 77 | transforms.RandomCrop(32, padding=4), 78 | transforms.RandomHorizontalFlip(), 79 | transforms.ToTensor(), 80 | transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), 81 | ]) 82 | val_trans = transforms.Compose([ 83 | transforms.ToTensor(), 84 | transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), 85 | ]) 86 | trainset = CIFAR10(root="./data", train=True, download=True, transform=tra_trans) 87 | testset = CIFAR10(root="./data", train=False, download=True, transform=val_trans) 88 | 89 | if args.dataset == 'femnist' or 'mnist': 90 | tra_trans = transforms.Compose([ 91 | transforms.Pad(2, padding_mode='edge'), 92 | transforms.ToTensor(), 93 | transforms.Normalize((0.1307,), (0.3081,)), 94 | ]) 95 | val_trans = transforms.Compose([ 96 | transforms.Pad(2, padding_mode='edge'), 97 | transforms.ToTensor(), 98 | transforms.Normalize((0.1307,), (0.3081,)), 99 | ]) 100 | if args.dataset == 'femnist': 101 | trainset = FEMNIST(root='./data', train=True, transform=tra_trans) 102 | testset = FEMNIST(root='./data', train=False, transform=val_trans) 103 | if args.dataset == 'mnist': 104 | trainset = MNIST(root='./data', train=True, transform=tra_trans, download= True) 105 | testset = MNIST(root='./data', train=False, transform=val_trans, download= True) 106 | if args.dataset == 'cifar100': 107 | tra_trans = transforms.Compose([ 108 | transforms.RandomCrop(32, padding=4), 109 | transforms.RandomHorizontalFlip(), 110 | transforms.ToTensor(), 111 | transforms.Normalize((0.4914, 0.4824, 0.4467), (0.2471, 0.2435, 0.2616)), 112 | ]) 113 | val_trans = transforms.Compose([ 114 | transforms.ToTensor(), 115 | transforms.Normalize((0.4914, 0.4824, 0.4467), (0.2471, 0.2435, 0.2616)), 116 | ]) 117 | trainset = CIFAR100(root="./data", train=True, download=True, transform=tra_trans) 118 | testset = CIFAR100(root="./data", train=False, download=True, transform=val_trans) 119 | 120 | 121 | return trainset, testset 122 | 123 | 124 | class Data(object): 125 | 126 | def __init__(self, args): 127 | self.args = args 128 | self.trainset, self.testset = None, None 129 | trainset, testset = Dataset(args) 130 | 131 | if args.sampler == 'iid': 132 | # 分割train set分配给边缘节点 133 | num_train = [int(len(trainset) / args.split) for _ in range(args.split)] 134 | # cumsum_train = torch.tensor(list(num_train)).cumsum(dim=0).tolist() 135 | # idx_train = range(len(trainset.targets)) 136 | # splited_trainset = [Subset(trainset, idx_train[off - l:off]) for off, l in zip(cumsum_train, num_train)] 137 | splited_trainset = random_split(trainset, num_train, generator=torch.Generator().manual_seed(42)) 138 | 139 | # 分割test set分配给边缘节点 140 | num_test = [int(len(testset) / args.split) for _ in range(args.split)] 141 | # cumsum_test = torch.tensor(list(num_test)).cumsum(dim=0).tolist() 142 | # idx_test = range(len(testset.targets)) 143 | # splited_testset = [Subset(testset, idx_test[off - l:off]) for off, l in zip(cumsum_test, num_test)] 144 | splited_testset = random_split(testset, num_test, generator=torch.Generator().manual_seed(42)) 145 | 146 | elif args.sampler == 'non-iid': 147 | # 分割train set分配给边缘节点 148 | targets = np.array(trainset.targets) 149 | num_train = [int(len(trainset) / args.split) for _ in range(args.split)] 150 | idx = [list(np.where(targets==1)[0]) for q in range(10)] 151 | kk = [idx[j][:int(args.mu*len(idx[1]))]for j in range(args.node_num)] # 得到前百分之mu的对应数据 152 | num_data = list(range(len(trainset))) # 数据集总数量 153 | kk2 = [b for a in kk for b in a] 154 | ll = list(set(num_data)-set(kk2)) # 将已经被选走的移除 155 | shuffle(ll) # 打乱 156 | ii = [ll[int(o*num_train[o]*(1-args.mu)):int((o+1)*num_train[o]*(1-args.mu))] for o in range(args.split)] # 随机将剩下的补齐 157 | zz = [kk[p]+ii[p] for p in range(args.split)] ##得到最终索引 158 | 159 | splited_trainset = [Subset(trainset, zz[q]) for q in range(args.split)] 160 | 161 | # 分割test set分配给边缘节点,没必要 162 | num_test = [int(len(testset) / args.split) for _ in range(args.split)] 163 | splited_testset = random_split(testset, num_test, generator=torch.Generator().manual_seed(42)) 164 | 165 | 166 | self.test_all = DataLoader(testset, batch_size=args.batchsize, shuffle=True, num_workers=4) 167 | self.train_loader = [DataLoader(splited_trainset[i], batch_size=args.batchsize, shuffle=True, num_workers=4) 168 | for i in range(args.node_num)] 169 | # self.test_loader = [DataLoader(splited_testset[i], batch_size=args.batchsize, shuffle=True, num_workers=4) 170 | # for i in range(args.node_num)] 171 | self.test_loader = DataLoader(testset, batch_size=args.batchsize, shuffle=True, num_workers=4) 172 | -------------------------------------------------------------------------------- /Trainer.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | import torch 3 | import torch.nn.functional as F 4 | import numpy as np 5 | from tqdm import tqdm 6 | from Node import Node 7 | # from losses import GCELoss 8 | 9 | 10 | KL_Loss = nn.KLDivLoss(reduction='batchmean') 11 | Softmax = nn.Softmax(dim=1) 12 | LogSoftmax = nn.LogSoftmax(dim=1) 13 | CE_Loss = nn.CrossEntropyLoss() 14 | 15 | 16 | def train_normal(node): 17 | node.model.to(node.device).train() 18 | train_loader = node.train_data 19 | total_loss = 0.0 20 | avg_loss = 0.0 21 | correct = 0.0 22 | acc = 0.0 23 | description = "Training (the {:d}-batch): tra_Loss = {:.4f} tra_Accuracy = {:.2f}%" 24 | with tqdm(train_loader) as epochs: 25 | for idx, (data, target) in enumerate(epochs): 26 | node.optimizer.zero_grad() 27 | epochs.set_description(description.format(idx + 1, avg_loss, acc)) 28 | data, target = data.to(node.device), target.to(node.device) 29 | output = node.model(data) 30 | loss = CE_Loss(output, target) 31 | loss.backward() 32 | node.optimizer.step() 33 | total_loss += loss 34 | avg_loss = total_loss / (idx + 1) 35 | pred = output.argmax(dim=1) 36 | correct += pred.eq(target.view_as(pred)).sum() 37 | acc = correct / len(train_loader.dataset) * 100 38 | 39 | 40 | def train_avg(node): 41 | node.model.to(node.device).train() 42 | train_loader = node.train_data 43 | total_loss = 0.0 44 | avg_loss = 0.0 45 | correct = 0.0 46 | acc = 0.0 47 | description = "Node{:d}: loss={:.4f} acc={:.2f}%" 48 | with tqdm(train_loader) as epochs: 49 | for idx, (data, target) in enumerate(epochs): 50 | node.optimizer.zero_grad() 51 | epochs.set_description(description.format(node.num, avg_loss, acc)) 52 | data, target = data.to(node.device), target.to(node.device) 53 | output = node.model(data) 54 | loss = CE_Loss(output, target) 55 | loss.backward() 56 | node.optimizer.step() 57 | total_loss += loss 58 | avg_loss = total_loss / (idx + 1) 59 | pred = output.argmax(dim=1) 60 | correct += pred.eq(target.view_as(pred)).sum() 61 | acc = correct / len(train_loader.dataset) * 100 62 | 63 | 64 | def train_mutual(node): 65 | node.model.to(node.device).train() 66 | node.global_model.to(node.device).train() 67 | train_loader = node.train_data 68 | total_local_loss = 0.0 69 | avg_local_loss = 0.0 70 | correct_local = 0.0 71 | acc_local = 0.0 72 | total_global_loss = 0.0 73 | avg_global_loss = 0.0 74 | correct_global = 0.0 75 | acc_global = 0.0 76 | description = 'Node{:d}: loss_model={:.4f} acc_model={:.2f}% loss_global={:.4f} acc_global={:.2f}%' 77 | with tqdm(train_loader) as epochs: 78 | for idx, (data, target) in enumerate(epochs): 79 | node.optimizer.zero_grad() 80 | node.global_optimizer.zero_grad() 81 | epochs.set_description(description.format(node.num, avg_local_loss, acc_local, avg_global_loss, acc_global)) 82 | data, target = data.to(node.device), target.to(node.device) 83 | output_local = node.model(data) 84 | output_global = node.global_model(data) 85 | ce_local = CE_Loss(output_local, target) 86 | kl_local = KL_Loss(LogSoftmax(output_local), Softmax(output_global.detach())) 87 | ce_global = CE_Loss(output_global, target) 88 | kl_global = KL_Loss(LogSoftmax(output_global), Softmax(output_local.detach())) 89 | loss_local = node.args.alpha * ce_local + (1 - node.args.alpha) * kl_local 90 | loss_global = node.args.beta * ce_global + (1 - node.args.beta) * kl_global 91 | loss_local.backward() 92 | loss_global.backward() 93 | node.optimizer.step() 94 | node.global_optimizer.step() 95 | 96 | ## loss与acc计算 97 | total_local_loss += loss_local 98 | avg_local_loss = total_local_loss / (idx + 1) 99 | pred_local = output_local.argmax(dim=1) 100 | correct_local += pred_local.eq(target.view_as(pred_local)).sum() 101 | acc_local = correct_local / len(train_loader.dataset) * 100 102 | total_global_loss += loss_global 103 | avg_global_loss = total_global_loss / (idx + 1) 104 | pred_global = output_global.argmax(dim=1) 105 | correct_global += pred_global.eq(target.view_as(pred_global)).sum() 106 | acc_global = correct_global / len(train_loader.dataset) * 100 107 | 108 | 109 | def train_coteaching(node, epoch, rate_schedule,R, args): 110 | node.model.to(node.device).train() 111 | node.global_model.to(node.device).train() 112 | train_loader = node.train_data 113 | total_local_loss = 0.0 114 | avg_local_loss = 0.0 115 | correct_local = 0.0 116 | acc_local = 0.0 117 | total_global_loss = 0.0 118 | avg_global_loss = 0.0 119 | correct_global = 0.0 120 | acc_global = 0.0 121 | description = 'Node{:d}: loss_model={:.4f} acc_model={:.2f}% loss_global={:.4f} acc_global={:.2f}%' 122 | 123 | # with tqdm(train_loader) as epochs: 124 | for idx, (data, target) in enumerate(train_loader): 125 | 126 | # epochs.set_description(description.format(node.num, avg_local_loss, acc_local, avg_global_loss, acc_global)) 127 | data, target = data.to(node.device), target.to(node.device) 128 | output_local = node.model(data) 129 | output_global = node.global_model(data) 130 | 131 | loss_local, loss_global, overlap = loss_coteaching(output_local, output_global, target, rate_schedule[epoch], args) 132 | node.optimizer.zero_grad() 133 | node.global_optimizer.zero_grad() 134 | 135 | loss_local.backward() 136 | loss_global.backward() 137 | node.optimizer.step() 138 | node.global_optimizer.step() 139 | # print(idx) 140 | # if epoch ==4: 141 | # node.overlap_sum += overlap 142 | # if idx ==78: 143 | # node.overlap_rate = node.overlap_sum/10000/rate_schedule[epoch] 144 | # print(node.overlap_rate) 145 | # node.overlap_sum = 0 146 | 147 | ## loss与acc计算 148 | # total_local_loss += loss_local 149 | # avg_local_loss = total_local_loss / (idx + 1) 150 | # pred_local = output_local.argmax(dim=1) 151 | # correct_local += pred_local.eq(target.view_as(pred_local)).sum() 152 | # acc_local = correct_local / len(train_loader.dataset) * 100 153 | # total_global_loss += loss_global 154 | # avg_global_loss = total_global_loss / (idx + 1) 155 | # pred_global = output_global.argmax(dim=1) 156 | # correct_global += pred_global.eq(target.view_as(pred_global)).sum() 157 | # acc_global = correct_global / len(train_loader.dataset) * 100 158 | 159 | 160 | class Trainer(object): 161 | 162 | def __init__(self, args): 163 | if args.algorithm == 'fed_mutual': 164 | self.train = train_mutual 165 | elif args.algorithm == 'fed_avg': 166 | self.train = train_avg 167 | elif args.algorithm == 'fed_coteaching': 168 | self.train = train_coteaching 169 | elif args.algorithm == 'normal': 170 | self.train = train_normal 171 | 172 | def __call__(self, node): 173 | self.train(node) 174 | 175 | 176 | 177 | def loss_coteaching(y_1, y_2, t, forget_rate, args): 178 | if args.loss == 'CE': 179 | loss_1 = F.cross_entropy(y_1, t, reduce=False) 180 | loss_2 = F.cross_entropy(y_2, t, reduce=False) 181 | 182 | elif args.loss == 'GCE': 183 | loss_1 = GCELoss(y_1, t) 184 | loss_2 = GCELoss(y_2, t) 185 | 186 | loss_1 = F.cross_entropy(y_1, t, reduce=False) 187 | ind_1_sorted = torch.argsort(loss_1.data).cuda() 188 | 189 | 190 | ind_2_sorted = torch.argsort(loss_2.data).cuda() 191 | 192 | remember_rate = 1 - forget_rate 193 | num_remember = int(remember_rate * ind_1_sorted.size()[0]) 194 | 195 | ind_1_update = ind_1_sorted[:num_remember] 196 | ind_2_update = ind_2_sorted[:num_remember] 197 | 198 | 199 | 200 | a = ind_1_update.tolist() 201 | b = ind_2_update.tolist() 202 | ovellap = len(set(a) & set(b)) 203 | 204 | 205 | # exchange 206 | loss_1_update = F.cross_entropy(y_1[ind_2_update], t[ind_2_update]) 207 | loss_2_update = F.cross_entropy(y_2[ind_1_update], t[ind_1_update]) 208 | return torch.sum(loss_1_update), torch.sum(loss_2_update), ovellap 209 | 210 | 211 | 212 | 213 | 214 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------